mocode-ai 1.8.8 → 1.8.10

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 (61) hide show
  1. package/dist/agent/index.js +17 -17
  2. package/dist/agent/model-turn.js +8 -4
  3. package/dist/agent/run-coordinator.js +6 -0
  4. package/dist/agent/spawn.js +8 -4
  5. package/dist/agent/stages/tool-dispatcher.js +31 -11
  6. package/dist/changeset/hash.js +17 -0
  7. package/dist/changeset/index.js +6 -10
  8. package/dist/config/index.js +6 -1
  9. package/dist/context/text-search.js +28 -10
  10. package/dist/flows/cli.js +1 -1
  11. package/dist/flows/flow.js +1 -1
  12. package/dist/flows/trace.js +1 -1
  13. package/dist/headless.js +23 -0
  14. package/dist/index.js +1 -1
  15. package/dist/memory/anchor.js +319 -0
  16. package/dist/memory/audit.js +65 -0
  17. package/dist/memory/episodic.js +546 -0
  18. package/dist/memory/graph.js +233 -9
  19. package/dist/memory/health.js +208 -0
  20. package/dist/memory/index.js +12 -3
  21. package/dist/memory/pending.js +269 -0
  22. package/dist/memory/portable.js +150 -0
  23. package/dist/memory/proactive.js +588 -0
  24. package/dist/memory/recall-stats.js +1 -1
  25. package/dist/memory/reflect.js +260 -6
  26. package/dist/memory/relation-vocab.js +26 -4
  27. package/dist/memory/store.js +587 -41
  28. package/dist/memory/tail.js +88 -0
  29. package/dist/memory/write-gate.js +44 -0
  30. package/dist/permissions/computer-review.js +1 -1
  31. package/dist/permissions/flow-review.js +1 -1
  32. package/dist/repl/commands/flow.js +1 -1
  33. package/dist/repl/commands/memory.js +257 -6
  34. package/dist/repl/commands/session.js +13 -0
  35. package/dist/repl/commands/tool-group.js +6 -0
  36. package/dist/repl/episode-finalize.js +55 -0
  37. package/dist/repl/running-input.js +1 -1
  38. package/dist/repl/runtime.js +41 -3
  39. package/dist/runtime/uia-selector.js +1 -1
  40. package/dist/runtime/uia-service.js +3 -3
  41. package/dist/runtime/wait-until.js +1 -1
  42. package/dist/runtime/window-list.js +1 -1
  43. package/dist/sandbox/policy.js +49 -0
  44. package/dist/session/compact.js +47 -12
  45. package/dist/session/gui-actions.js +1 -1
  46. package/dist/tools/builtins/computer.js +5 -5
  47. package/dist/tools/builtins/memory-graph.js +12 -1
  48. package/dist/tools/builtins/memory-list.js +13 -3
  49. package/dist/tools/builtins/memory-save.js +82 -2
  50. package/dist/tools/builtins/memory-search.js +57 -2
  51. package/dist/tools/builtins/memory-update.js +52 -1
  52. package/dist/tools/builtins/read-file.js +51 -2
  53. package/dist/tools/builtins/run-flow.js +1 -1
  54. package/dist/tools/constants.js +60 -0
  55. package/dist/ui/intervention.js +38 -2
  56. package/dist/ui/layout-internal/core.js +8 -2
  57. package/dist/ui/layout-internal/input-paint.js +15 -7
  58. package/dist/ui/layout-internal/screen.js +9 -0
  59. package/dist/ui/layout-internal/scroll.js +49 -11
  60. package/dist/ui/layout-internal/state.js +8 -0
  61. package/package.json +6 -1
@@ -9,10 +9,23 @@
9
9
  // 两文件:全局 ~/.mocode/memory.jsonl + 项目 <cwd>/.mocode/memory.jsonl(镜像 resolveMemoryFiles
10
10
  // 的 global+cwd 与 sessionDir 的 cwd 习惯)。条目带 scope 字段标识归属,loadAll 时按文件归一化。
11
11
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
12
+ import { createHash } from 'node:crypto';
12
13
  import os from 'node:os';
13
14
  import path from 'node:path';
14
- import { MAX_ACTIVE, MAX_INDEX_ENTRIES, MAX_MEMORY_ENTRY, DECAY_DAYS, GC_DAYS } from '../tools/constants.js';
15
+ import { MAX_ACTIVE, MAX_INDEX_ENTRIES, MAX_MEMORY_ENTRY, DECAY_DAYS, GC_DAYS, EPISODE_DECAY_DAYS, EPISODE_GC_DAYS, EPISODE_CONSOLIDATED_DECAY_DAYS, MEMORY_SEARCH_MIN_EVIDENCE, } from '../tools/constants.js';
15
16
  import { TextSearchIndex } from '../context/text-search.js';
17
+ import { buildAnchors, evaluateAnchors } from './anchor.js';
18
+ import { memoryWriteBlockReason } from './write-gate.js';
19
+ import { appendAudit } from './audit.js';
20
+ // 写入总闸放在独立叶子模块(store/graph/pending 三处共用),这里转出,
21
+ // 让既有 `import { … } from '../memory/store.js'` 的调用方无需改动。
22
+ export { setMemoryWritesPaused, isMemoryWritesPaused, memoryWriteBlockReason, memoryWriteBlockedMessage, __resetMemoryPauseForTests, } from './write-gate.js';
23
+ /** 这三类记忆天然是条件-动作式的;fact/reference 是纯陈述,可无 trigger。 */
24
+ export const TRIGGER_REQUIRED_TYPES = new Set(['pitfall', 'decision', 'feedback']);
25
+ /** 该类型是否建议带 trigger(用于提示词与观测,不做硬拦截)。 */
26
+ export function wantsTrigger(type) {
27
+ return TRIGGER_REQUIRED_TYPES.has(type);
28
+ }
16
29
  // ── 路径 ──────────────────────────────────────────────────────────────────
17
30
  function globalPath() {
18
31
  return path.join(os.homedir(), '.mocode', 'memory.jsonl');
@@ -65,7 +78,7 @@ function readFileEntries(p) {
65
78
  return out;
66
79
  }
67
80
  /** 加载全部(global + project),按文件归一化 scope(防旧条目缺字段 / 字段错)。 */
68
- export function loadAll() {
81
+ function loadAllRaw() {
69
82
  const out = [];
70
83
  for (const scope of ['global', 'project']) {
71
84
  for (const e of readFileEntries(pathForScope(scope))) {
@@ -75,6 +88,96 @@ export function loadAll() {
75
88
  }
76
89
  return out;
77
90
  }
91
+ const pendingRecall = new Map();
92
+ /**
93
+ * 脏集阈值:达此条数就在 searchEntries 内就地 flush。
94
+ * 存在的理由是**非 REPL 入口**(headless / 单次工具调用)走不到轮末 flush,
95
+ * 脏集随进程退出就丢了。设得比典型一次搜索的命中数大,REPL 场景实际不会触发。
96
+ */
97
+ const PENDING_RECALL_FLUSH_THRESHOLD = 64;
98
+ /** 把未落盘的召回增量应用到条目上(不修改 pending)。 */
99
+ function applyPendingRecall(entries) {
100
+ if (pendingRecall.size === 0)
101
+ return entries;
102
+ for (const e of entries) {
103
+ const p = pendingRecall.get(e.id);
104
+ if (!p)
105
+ continue;
106
+ e.recallCount += p.count;
107
+ e.lastRecalledAt = p.at;
108
+ }
109
+ return entries;
110
+ }
111
+ /** 加载全部并应用未落盘的召回增量(读路径统一入口)。 */
112
+ export function loadAll() {
113
+ return applyPendingRecall(loadAllRaw());
114
+ }
115
+ /**
116
+ * 落盘所有未写入的召回增量。幂等:无 pending 时零 IO。
117
+ * 由轮末、退出、以及每个写操作的开头调用(写操作自己会整文件重写,
118
+ * 先 flush 可保证不会与待写增量重复累加)。返回落盘的条目数。
119
+ */
120
+ export function flushRecallStats() {
121
+ if (pendingRecall.size === 0)
122
+ return 0;
123
+ // 写入被拦时不落盘也**不清**脏集:清掉就丢了召回计数(R0.2 的统计口径),而刷新
124
+ // 计数不是用户可见的内容写入,恢复后仍应补上。返回 0 让调用方知道没写。
125
+ if (memoryWriteBlockReason())
126
+ return 0;
127
+ const entries = applyPendingRecall(loadAllRaw());
128
+ const touched = new Set();
129
+ for (const p of pendingRecall.values())
130
+ touched.add(p.scope);
131
+ for (const scope of touched) {
132
+ const p = pathForScope(scope);
133
+ ensureDir(p);
134
+ writeAtomic(p, entries.filter((e) => e.scope === scope));
135
+ }
136
+ const n = pendingRecall.size;
137
+ pendingRecall.clear();
138
+ return n;
139
+ }
140
+ /**
141
+ * 写回某 scope 之后调用:清除该 scope 的待落盘增量。
142
+ *
143
+ * 增量此时已烘进刚写的文件(调用方拿到的条目来自 loadAll,已含增量),
144
+ * 不清除会在下次读时再加一遍 → 重复累加;只清该 scope 才不会丢掉
145
+ * 另一次写不会覆盖的那个 scope 的增量。
146
+ */
147
+ function clearPendingScope(scope) {
148
+ for (const [id, p] of pendingRecall) {
149
+ if (p.scope === scope)
150
+ pendingRecall.delete(id);
151
+ }
152
+ }
153
+ /** 待落盘增量条数(超过阈值时 searchEntries 自动 flush,给非 REPL 入口兜底)。 */
154
+ export function pendingRecallCount() {
155
+ return pendingRecall.size;
156
+ }
157
+ /**
158
+ * 退出兜底:SIGINT / 未捕获异常不保证经过 REPL 收尾,脏集若只靠轮末 flush
159
+ * 会随进程退出丢失。这里自注册一个 exit 钩子——store 是叶子模块,不能反向
160
+ * 依赖 index.ts 的退出编排,只能自带兜底。flush 幂等且无 pending 时零 IO,
161
+ * 与轮末 flush 并存不会重复写。unref 不适用(exit 钩子本身不需要句柄)。
162
+ */
163
+ let exitHookInstalled = false;
164
+ function installExitFlush() {
165
+ if (exitHookInstalled)
166
+ return;
167
+ exitHookInstalled = true;
168
+ process.once('exit', () => {
169
+ try {
170
+ flushRecallStats();
171
+ }
172
+ catch {
173
+ // 退出路径绝不抛错
174
+ }
175
+ });
176
+ }
177
+ /** 仅供测试:清空未落盘增量(避免用例间串味)。 */
178
+ export function __resetPendingRecallForTests() {
179
+ pendingRecall.clear();
180
+ }
78
181
  /** 按 scope 分组写回:仅写有条目或文件已存在的 scope(避免凭空建空文件)。 */
79
182
  function writeBackByScope(all) {
80
183
  for (const scope of ['global', 'project']) {
@@ -86,18 +189,171 @@ function writeBackByScope(all) {
86
189
  writeAtomic(p, entries);
87
190
  }
88
191
  }
89
- // ── 工具:slugify / 截断 ───────────────────────────────────────────────────
90
- let slugCounter = 0;
91
- /** name → ASCII slug;空(纯 CJK 等)则 m+时间戳+计数防同毫秒碰撞。 */
92
- function slugify(name) {
93
- const s = name
192
+ // ── 工具:slugify / 去重键 / 截断 ─────────────────────────────────────────
193
+ /**
194
+ * 名称归一:小写、去首尾空白、内部空白压成单空格、全角空格同化。
195
+ * 只做确定性变换,不做同义词/编辑距离——模糊匹配属于检索层,不属于身份层。
196
+ */
197
+ function normalizeName(raw) {
198
+ return String(raw ?? '')
199
+ .replace(/\u3000/g, ' ')
200
+ .trim()
94
201
  .toLowerCase()
202
+ .replace(/\s+/g, ' ');
203
+ }
204
+ /**
205
+ * name → id。
206
+ *
207
+ * ASCII 名走可读 slug;**纯 CJK 名(及其它无 ASCII 音节的名)走名称哈希**——
208
+ * 历史实现用 `m+Date.now()+counter` 兜底,导致同一个中文名每次保存都得到不同 id,
209
+ * 于是 saveEntry 的「同 id 即已存在」检查对中文名完全失效,同一件事可无限重复入库。
210
+ * 改用 sha256(归一化名) 前缀后,同一名称恒定映射到同一 id,与英文名行为对齐。
211
+ * 原 `slugCounter` 随旧兜底一起删掉:哈希已保证确定性,再保留一个永不读的计数器
212
+ * 只会让 lint 报错。
213
+ */
214
+ function slugify(name) {
215
+ const s = normalizeName(name)
95
216
  .replace(/[^a-z0-9]+/g, '-')
96
217
  .replace(/^-+|-+$/g, '');
97
218
  if (s)
98
219
  return s;
99
- slugCounter++;
100
- return 'm' + Date.now().toString(36) + slugCounter.toString(36);
220
+ const h = createHash('sha256').update(normalizeName(name)).digest('hex').slice(0, 12);
221
+ return 'm-' + h;
222
+ }
223
+ /**
224
+ * 去重键:归一化 **summary + body** 的哈希(不含 name)。
225
+ *
226
+ * 为什么不含 name——id 由归一化 name 派生,若 dedupKey 也含 name,则「同 key」
227
+ * 必然「同 name」必然「同 id」,命中集合是 id 检查的子集,等于死代码。
228
+ * 去重键要解决的是 id 检查覆盖不到的另一半:**不同名、同一件事**。
229
+ * 反思很容易把同一结论写成不同标题(`user-language-chinese-replies`
230
+ * vs `万偏好中文`),只有抛开 name 比较内容才拦得住。
231
+ *
232
+ * 为什么不含 body 之外的其它字段——type/pinned/scope 是元数据,不影响
233
+ * "说的是不是同一件事"的判断;scope 另在 saveEntry 内按 scope 隔离比较。
234
+ */
235
+ export function computeDedupKey(summary, body) {
236
+ const norm = (raw) => String(raw ?? '')
237
+ .replace(/\u3000/g, ' ')
238
+ .trim()
239
+ .toLowerCase()
240
+ .replace(/\s+/g, ' ');
241
+ const s = norm(summary);
242
+ const b = norm(body);
243
+ return createHash('sha256')
244
+ .update(s + '\u0000' + b)
245
+ .digest('hex')
246
+ .slice(0, 16);
247
+ }
248
+ /** 条目去重键(旧条目无该字段时惰性按 summary+body 补算,不回写——读路径保持只读)。 */
249
+ function dedupKeyOf(e) {
250
+ return e.dedupKey || computeDedupKey(e.summary, e.body);
251
+ }
252
+ /**
253
+ * 派生关系上限。一条记忆归纳自太多源时,「任一源失效即 stale」会退化成恒 stale,
254
+ * 提示也就失去了指向性。8 条足够覆盖「同类情节归纳成语义」的典型规模。
255
+ */
256
+ const MAX_DERIVED_FROM = 8;
257
+ /** 归一 derivedFrom:去空、去自引用、去重、封顶。自引用必须滤掉,否则该条永远 stale。 */
258
+ function normalizeDerivedFrom(input, selfId) {
259
+ if (!input || input.length === 0)
260
+ return [];
261
+ const out = [];
262
+ for (const raw of input) {
263
+ const id = String(raw ?? '').trim();
264
+ if (!id || id === selfId || out.includes(id))
265
+ continue;
266
+ out.push(id);
267
+ if (out.length >= MAX_DERIVED_FROM)
268
+ break;
269
+ }
270
+ return out;
271
+ }
272
+ const NOT_STALE = { stale: false, missing: [], inactive: [] };
273
+ /**
274
+ * R14 读时级联:按源条目**当前**状态判定本条是否 stale。
275
+ *
276
+ * 只判**直接**源,不递归传播:A 被取代 → 派生自 A 的 B 变 stale;B 自己仍是 active,
277
+ * 所以派生自 B 的 C 不受影响。递归会让一次取代波及整条抽象链,而越抽象的上层结论
278
+ * 越可能依然成立——那正是「不能因为源失效就删掉派生结论」的原意。
279
+ */
280
+ export function computeStaleness(entry, byId) {
281
+ const src = entry.derivedFrom ?? [];
282
+ if (src.length === 0)
283
+ return NOT_STALE;
284
+ const missing = [];
285
+ const inactive = [];
286
+ for (const id of src) {
287
+ const s = byId.get(id);
288
+ if (!s)
289
+ missing.push(id);
290
+ else if (s.status !== 'active')
291
+ inactive.push(id);
292
+ }
293
+ if (missing.length === 0 && inactive.length === 0)
294
+ return NOT_STALE;
295
+ return { stale: true, missing, inactive };
296
+ }
297
+ /**
298
+ * 一次算出全库派生条目的失效表(只含 derivedFrom 非空的条目)。
299
+ *
300
+ * 集中在这里而不是散落在各读路径:检索、列表、概览三处都要同一套判定,
301
+ * 各算一遍迟早漂移成三种口径。调用方可传入已有的 loadAll() 结果以省一次读盘。
302
+ */
303
+ export function loadStalenessMap(all = loadAll()) {
304
+ const byId = new Map(all.map((e) => [e.id, e]));
305
+ const out = new Map();
306
+ for (const e of all) {
307
+ if (!e.derivedFrom || e.derivedFrom.length === 0)
308
+ continue;
309
+ out.set(e.id, computeStaleness(e, byId));
310
+ }
311
+ return out;
312
+ }
313
+ /**
314
+ * R2 一次算出全库**锚点**失效表(只含 anchors 非空的条目)。
315
+ *
316
+ * 与 `loadStalenessMap` 并列而非合并:两者数据源完全不同(一条查条目状态,一条读文件),
317
+ * 合并会让「只有派生关系、没有锚点」的绝大多数条目去背一次文件系统遍历。
318
+ *
319
+ * 每个锚点都要 stat(命中 mtime 缓存则免读),所以这里按条目惰性判定、不预读全部文件。
320
+ */
321
+ export function loadAnchorStaleMap(all = loadAll()) {
322
+ const out = new Map();
323
+ for (const e of all) {
324
+ if (!e.anchors || e.anchors.length === 0)
325
+ continue;
326
+ out.set(e.id, evaluateAnchors(e.anchors));
327
+ }
328
+ return out;
329
+ }
330
+ /**
331
+ * R2.4 反向查询:哪些记忆锚定了这个文件。
332
+ *
333
+ * 供 `read_file` 在结果尾部回注用——读到某个文件时,顺带告诉模型「关于这个文件,
334
+ * 你以前记过这些」。这是 R2 唯一不需要模型主动检索就能生效的一段(push 侧),
335
+ * 而 pull 侧(memory_search)实测调用次数为 0。
336
+ *
337
+ * 只返回 **active** 条目:归档/被取代的条目说的是历史,不该在写代码时冒出来。
338
+ * 调用方再按 `evaluateAnchors` 过滤 fresh——刚读到的文件内容与记忆里的一致,
339
+ * 这条记忆才有资格当场提示;对不上就说明它已经过期,此时提示反而误导。
340
+ */
341
+ export function entriesAnchoredTo(anchorPath, opts = {}) {
342
+ const limit = Math.max(1, opts.limit ?? 3);
343
+ const activeOnly = opts.activeOnly ?? true;
344
+ const out = [];
345
+ for (const e of loadAll()) {
346
+ if (!e.anchors || e.anchors.length === 0)
347
+ continue;
348
+ if (activeOnly && e.status !== 'active')
349
+ continue;
350
+ if (!e.anchors.some((a) => a.path === anchorPath))
351
+ continue;
352
+ out.push(e);
353
+ if (out.length >= limit)
354
+ break;
355
+ }
356
+ return out;
101
357
  }
102
358
  function truncateBody(body) {
103
359
  if (body.length <= MAX_MEMORY_ENTRY)
@@ -109,20 +365,45 @@ function truncateBody(body) {
109
365
  function nowIso() {
110
366
  return new Date().toISOString();
111
367
  }
112
- /** 新建:id 全局唯一(跨两文件),撞库返 exists 让工具层提示用 memory_update。 */
368
+ /**
369
+ * 新建。两道确定性去重,任一命中都返 exists 引导调用方改走 memory_update:
370
+ * ① **同 id**(同一归一化名字)——跨两文件,历史行为;
371
+ * ② **同 dedupKey**(归一化 summary+body 的哈希,不含名字)——拦住「同一件事换个写法的标题」。
372
+ * 只在 scope 内比较:global 与 project 允许各存一份同内容条目,那是刻意的
373
+ * 可见性差异,不算重复。已归档/被取代的条目也参与比较,避免复活同一件事。
374
+ */
113
375
  export function saveEntry(input) {
376
+ const blocked = memoryWriteBlockReason();
377
+ if (blocked)
378
+ return { ok: false, blocked };
114
379
  const id = slugify(input.name);
115
380
  const all = loadAll();
116
381
  if (all.some((e) => e.id === id))
117
382
  return { ok: false, exists: id };
118
383
  const scope = input.scope === 'global' ? 'global' : 'project';
384
+ // 先截断再算 key:stored entry 的 body 是截断后的版本,dedupKeyOf 也按截断后的算,
385
+ // 两边口径必须一致,否则长正文条目每次都算作"新内容"。
386
+ const body = truncateBody(input.body);
387
+ const dedupKey = computeDedupKey(input.summary, body);
388
+ const dup = all.find((e) => e.scope === scope && dedupKeyOf(e) === dedupKey);
389
+ if (dup)
390
+ return { ok: false, exists: dup.id };
119
391
  const now = nowIso();
392
+ // R1.5:trigger/action 归一为空串即视为"未填",不写空字段(避免 JSONL 里全是空键)。
393
+ const trigger = input.trigger?.trim() || undefined;
394
+ const action = input.action?.trim() || undefined;
395
+ // R14:派生来源。滤掉自引用(模型偶尔把新 id 自己写进 derivedFrom)与空串,
396
+ // 否则一条派生条目会因为"源是自己"而永远算作 stale。
397
+ const derivedFrom = normalizeDerivedFrom(input.derivedFrom, id);
398
+ // R2:锚点在**写入时**现算 hash(调用方只给 path/symbol)。算不出来的(文件不存在、
399
+ // 符号找不到)静默丢弃——存一条锚不住任何东西的锚点只会制造永久 unknown 噪音。
400
+ const anchors = buildAnchors(input.anchors);
120
401
  const entry = {
121
402
  id,
122
403
  type: input.type ?? 'fact',
123
404
  name: input.name,
124
405
  summary: input.summary,
125
- body: truncateBody(input.body),
406
+ body,
126
407
  createdAt: now,
127
408
  updatedAt: now,
128
409
  lastRecalledAt: null,
@@ -132,12 +413,20 @@ export function saveEntry(input) {
132
413
  pinned: !!input.pinned,
133
414
  scope,
134
415
  source: input.source ?? null,
416
+ dedupKey,
417
+ ...(trigger ? { trigger } : {}),
418
+ ...(action ? { action } : {}),
419
+ ...(trigger ? { triggerUpdatedAt: now } : {}),
420
+ ...(derivedFrom.length > 0 ? { derivedFrom } : {}),
421
+ ...(anchors.length > 0 ? { anchors } : {}),
135
422
  };
136
423
  const p = pathForScope(scope);
137
- const fileEntries = readFileEntries(p);
424
+ // 用 all(已含未落盘召回增量)而非裸读文件:否则写回会把这些增量的实体版本覆盖掉。
425
+ const fileEntries = all.filter((e) => e.scope === scope);
138
426
  fileEntries.push(entry);
139
427
  ensureDir(p);
140
428
  writeAtomic(p, fileEntries);
429
+ clearPendingScope(scope); // 增量已烘进文件,清掉避免下次读重复累加
141
430
  return { ok: true, id };
142
431
  }
143
432
  /**
@@ -154,8 +443,15 @@ export function searchEntries(query, opts = {}) {
154
443
  const limit = Math.max(1, Math.min(opts.limit ?? 5, 20));
155
444
  const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
156
445
  const top = [];
446
+ // R14.3:status='any' 时先多取候选再排序截断。
447
+ //
448
+ // 为什么不能只排序已取回的 limit 条:实测真实库 query="mocode" 时前 4 条全是
449
+ // archived(标题匹配得分高),limit=5 就会把 active 的那条彻底挤出去——排序再对
450
+ // 也排不出一个根本没被取回的条目。多取一截、排完再截,才能保证「active 优先」
451
+ // 在结果条数受限时也成立。
452
+ const searchN = status === 'any' ? Math.min(pool.length, Math.max(limit * 4, limit + 10)) : limit;
157
453
  if (terms.length === 0) {
158
- top.push(...pool.slice(0, limit));
454
+ top.push(...pool.slice(0, searchN));
159
455
  }
160
456
  else {
161
457
  const index = new TextSearchIndex(pool.map((e) => ({
@@ -166,44 +462,82 @@ export function searchEntries(query, opts = {}) {
166
462
  { text: e.summary, weight: 5 },
167
463
  { text: e.body, weight: 1 },
168
464
  ],
169
- })));
465
+ })),
466
+ // R15.5:相关性下限。BM25 只排序、不判「相关与否」,任何 token 重合都返回;
467
+ // 实测 6 条无关查询(红烧肉/签证/kubernetes…)全部被召回,误报率 100%。
468
+ // 加下限后误报 0、正例 recall@1 仍 98%(代价见 constants.ts 该常量注释)。
469
+ // 用「证据词元命中数」而非分数阈值:分数随 N/idf 漂移(同一份探针在
470
+ // fixture 最优 31.94、真实库 40.60),写死哪个都会在另一套数据上失效。
471
+ { minEvidenceMatched: MEMORY_SEARCH_MIN_EVIDENCE });
170
472
  const byId = new Map(pool.map((e) => [e.id, e]));
171
- for (const hit of index.search(query, limit)) {
473
+ for (const hit of index.search(query, searchN)) {
172
474
  const e = byId.get(hit.id);
173
475
  if (e)
174
476
  top.push(e);
175
477
  }
176
478
  }
479
+ if (status === 'any' && top.length > 0) {
480
+ // 稳定排序:同组内保持 BM25 分数序,只是把 active 整体提到非 active 之前。
481
+ const rank = (e) => (e.status === 'active' ? 0 : 1);
482
+ top.sort((a, b) => rank(a) - rank(b));
483
+ top.length = Math.min(top.length, limit);
484
+ }
177
485
  if (top.length === 0)
178
486
  return [];
179
- // bump recall:只写有命中的 scope 文件
487
+ // bump recall:只累加到内存脏集,不落盘(R0.2)。搜索是纯读语义,不该让每次
488
+ // memory_search 都整文件重写;增量由 loadAll 即时体现(计数立刻可见),
489
+ // 落盘交给轮末 / 退出 / 下一个写操作。同一条目多次命中在脏集内累加。
180
490
  const now = nowIso();
181
- const hitIds = new Set(top.map((x) => x.id));
182
- for (const e of all) {
183
- if (hitIds.has(e.id)) {
184
- e.recallCount++;
185
- e.lastRecalledAt = now;
186
- }
187
- }
188
- const hitScopes = new Set(top.map((x) => x.scope));
189
- for (const scope of hitScopes) {
190
- const p = pathForScope(scope);
191
- const entries = all.filter((e) => e.scope === scope);
192
- ensureDir(p);
193
- writeAtomic(p, entries);
491
+ installExitFlush(); // 脏集出现即保障退出兜底(幂等)
492
+ for (const e of top) {
493
+ const prev = pendingRecall.get(e.id);
494
+ pendingRecall.set(e.id, {
495
+ scope: e.scope,
496
+ count: (prev?.count ?? 0) + 1,
497
+ at: now,
498
+ });
499
+ e.recallCount++;
500
+ e.lastRecalledAt = now;
194
501
  }
502
+ // 兜底:非 REPL 入口(headless / 单次工具调用)不会走到轮末 flush,
503
+ // 脏集长期不落盘会随进程退出丢失。攒够阈值就地刷一次。
504
+ if (pendingRecall.size >= PENDING_RECALL_FLUSH_THRESHOLD)
505
+ flushRecallStats();
195
506
  return top;
196
507
  }
197
508
  /** 索引(无 body、不 bump recall)。 */
198
509
  export function listEntries(opts = {}) {
199
510
  const status = opts.status ?? 'active';
200
- return loadAll()
511
+ const all = loadAll();
512
+ const stale = loadStalenessMap(all);
513
+ const anchorStale = loadAnchorStaleMap(all);
514
+ return all
201
515
  .filter((e) => (status === 'any' ? true : e.status === status))
202
516
  .filter((e) => (opts.type ? e.type === opts.type : true))
203
- .map((e) => ({ id: e.id, name: e.name, summary: e.summary, type: e.type, status: e.status }));
517
+ .map((e) => {
518
+ const s = stale.get(e.id);
519
+ const a = anchorStale.get(e.id);
520
+ const anchorCount = e.anchors?.length ?? 0;
521
+ return {
522
+ id: e.id,
523
+ name: e.name,
524
+ summary: e.summary,
525
+ type: e.type,
526
+ status: e.status,
527
+ hasTrigger: !!e.trigger,
528
+ // 只在确实是派生条目且确实失效时才带该字段:非派生条目占绝大多数,
529
+ // 一律写 `stale: false` 会把可选字段变成噪音。
530
+ ...(s?.stale ? { stale: true } : {}),
531
+ ...(a?.stale ? { anchorStale: true } : {}),
532
+ ...(anchorCount > 0 ? { anchorCount } : {}),
533
+ };
534
+ });
204
535
  }
205
536
  /** 原地改:id 不变(name 可改 → 但 id 仍是旧 slug,故 name 改不会触发重 slug);记 lastUpdateReason;pinned 可切换。 */
206
537
  export function updateEntry(id, patch) {
538
+ const blocked = memoryWriteBlockReason();
539
+ if (blocked)
540
+ return { ok: false, blocked };
207
541
  const all = loadAll();
208
542
  const e = all.find((x) => x.id === id);
209
543
  if (!e)
@@ -214,15 +548,63 @@ export function updateEntry(id, patch) {
214
548
  e.summary = patch.summary;
215
549
  if (patch.body)
216
550
  e.body = truncateBody(patch.body);
551
+ // dedupKey 必须随内容一起重算。它缓存在条目上,只在 saveEntry 时算过一次;
552
+ // 若这里不更新,改完内容后两次判重都会错:
553
+ // ① 用**新内容**再 saveEntry 不被拦 → 同一件事重复入库(dedupKey 本该拦的正是这个);
554
+ // ② 用**更新前**的旧内容再 saveEntry 反而被拦 → 已经改掉的结论复活不了。
555
+ // 比较放在赋值之后、写盘之前:两条 dedupKey 都按截断后的 body 算,口径与 saveEntry 一致。
556
+ if (patch.summary !== undefined || patch.body !== undefined) {
557
+ e.dedupKey = computeDedupKey(e.summary, e.body);
558
+ }
217
559
  if (patch.reason)
218
560
  e.lastUpdateReason = patch.reason;
219
561
  if (patch.pinned !== undefined)
220
562
  e.pinned = patch.pinned;
563
+ // trigger/action 用 `!== undefined` 判定:空串是合法的"清空"意图,
564
+ // 不能用真值判断(否则用户永远删不掉一条写错的 trigger)。
565
+ if (patch.trigger !== undefined) {
566
+ const t = patch.trigger.trim();
567
+ if (t) {
568
+ e.trigger = t;
569
+ e.triggerUpdatedAt = nowIso();
570
+ }
571
+ else {
572
+ delete e.trigger;
573
+ delete e.triggerUpdatedAt;
574
+ }
575
+ }
576
+ if (patch.action !== undefined) {
577
+ const a = patch.action.trim();
578
+ if (a)
579
+ e.action = a;
580
+ else
581
+ delete e.action;
582
+ }
583
+ // R2:锚点整体替换(空数组 = 清空)。hash 现算,算不出来的静默丢弃。
584
+ if (patch.anchors !== undefined) {
585
+ const anchors = buildAnchors(patch.anchors);
586
+ if (anchors.length > 0)
587
+ e.anchors = anchors;
588
+ else
589
+ delete e.anchors;
590
+ }
591
+ // R11:巩固标记。空串 = 清除(撤销一次错误巩固);不校验 id 是否存在——
592
+ // 目标条目被硬删后这里会留下悬空指针,但它只被分组器用来"排除已巩固的情节",
593
+ // 悬空指针的语义(巩固过)仍然正确,强行校验只会让巩固写入多一次失败路径。
594
+ if (patch.derivedInto !== undefined) {
595
+ const t = patch.derivedInto.trim();
596
+ if (t)
597
+ e.derivedInto = t;
598
+ else
599
+ delete e.derivedInto;
600
+ }
221
601
  e.updatedAt = nowIso();
222
602
  const p = pathForScope(e.scope);
603
+ // all 来自 loadAll,已含未落盘的召回增量;写回即把增量烘进文件,故随后清该 scope 的 pending。
223
604
  const entries = all.filter((x) => x.scope === e.scope);
224
605
  ensureDir(p);
225
606
  writeAtomic(p, entries);
607
+ clearPendingScope(e.scope);
226
608
  return { ok: true };
227
609
  }
228
610
  /**
@@ -231,6 +613,9 @@ export function updateEntry(id, patch) {
231
613
  * 而不是"过期清理"。pinned 条目同样允许被取代(取代链是显式修正,不是自动遗忘)。
232
614
  */
233
615
  export function supersedeEntry(oldId, newId, reason) {
616
+ const blocked = memoryWriteBlockReason();
617
+ if (blocked)
618
+ return { ok: false, blocked };
234
619
  const all = loadAll();
235
620
  const oldE = all.find((x) => x.id === oldId);
236
621
  if (!oldE)
@@ -242,10 +627,14 @@ export function supersedeEntry(oldId, newId, reason) {
242
627
  oldE.lastUpdateReason = reason;
243
628
  const p = pathForScope(oldE.scope);
244
629
  writeAtomic(p, all.filter((x) => x.scope === oldE.scope));
630
+ clearPendingScope(oldE.scope);
245
631
  return { ok: true };
246
632
  }
247
633
  /** 归档(默认,可复活)/ 硬删;pinned 拒删。 */
248
634
  export function forgetEntry(id, mode = 'archive') {
635
+ const blocked = memoryWriteBlockReason();
636
+ if (blocked)
637
+ return { ok: false, blocked };
249
638
  const all = loadAll();
250
639
  const e = all.find((x) => x.id === id);
251
640
  if (!e)
@@ -266,25 +655,177 @@ export function forgetEntry(id, mode = 'archive') {
266
655
  }
267
656
  ensureDir(p);
268
657
  writeAtomic(p, entries);
658
+ clearPendingScope(e.scope);
269
659
  return { ok: true, mode };
270
660
  }
661
+ /**
662
+ * 批量**真删**(不是 archived)。
663
+ *
664
+ * 与 `forgetEntry(id, 'delete')` 的关系:那个是单条、给模型用的;这个是给用户批量用的。
665
+ * 三处刻意设计:
666
+ * ① **pinned 永不删**——pinned 的语义就是"用户明确要长期留着",批量操作不该推翻它;
667
+ * ② **必须至少给一个条件**:全空调用返回空结果而不是清库,防手滑(要清库就 --all);
668
+ * ③ **先算名单再落盘**:dryRun 与真删走同一段筛选,预览与执行不可能不一致。
669
+ */
670
+ export function purgeEntries(opts = {}) {
671
+ const dryRun = opts.dryRun === true;
672
+ // dryRun 只是预演,不写盘,因此不受暂停闸限制——被 pause 的用户更需要能先看看会删什么。
673
+ if (!dryRun) {
674
+ const blocked = memoryWriteBlockReason();
675
+ if (blocked)
676
+ return { ok: false, blocked };
677
+ }
678
+ const all = loadAll();
679
+ const match = opts.match?.trim().toLowerCase() ?? '';
680
+ const sinceMs = opts.since ? Date.parse(opts.since) : NaN;
681
+ const hasCond = opts.all === true || Boolean(match) || Number.isFinite(sinceMs);
682
+ // 无任何条件 → 什么都不做。返回成功但空名单,调用方据此提示用法,而不是悄悄清库。
683
+ if (!hasCond)
684
+ return { ok: true, ids: [], pinned: 0, dryRun };
685
+ const hit = all.filter((e) => {
686
+ if (opts.scope && e.scope !== opts.scope)
687
+ return false;
688
+ if (match) {
689
+ const hay = `${e.id}\n${e.name}\n${e.summary}\n${e.body}`.toLowerCase();
690
+ if (!hay.includes(match))
691
+ return false;
692
+ }
693
+ if (Number.isFinite(sinceMs)) {
694
+ const t = Date.parse(e.createdAt);
695
+ if (!Number.isFinite(t) || t < sinceMs)
696
+ return false;
697
+ }
698
+ return true;
699
+ });
700
+ const ids = hit.filter((e) => !e.pinned).map((e) => e.id);
701
+ const pinned = hit.length - ids.length;
702
+ if (dryRun || ids.length === 0)
703
+ return { ok: true, ids, pinned, dryRun };
704
+ const drop = new Set(ids);
705
+ for (const scope of ['global', 'project']) {
706
+ if (opts.scope && scope !== opts.scope)
707
+ continue;
708
+ const p = pathForScope(scope);
709
+ const kept = all.filter((e) => e.scope === scope && !drop.has(e.id));
710
+ // 该 scope 本来就没有文件、也没有要删的条目 → 不要凭空建空文件(R8.5 同口径)。
711
+ if (kept.length === 0 && !existsSync(p))
712
+ continue;
713
+ ensureDir(p);
714
+ writeAtomic(p, kept);
715
+ clearPendingScope(scope);
716
+ }
717
+ // 审计行写在落盘**之后**:只有真的删成了才记「已删」,否则日志会撒谎。
718
+ // 只记 id 与条件,**不记正文**——审计文件同样躺在磁盘上,删掉的隐私不该换个文件继续存。
719
+ const cond = [
720
+ opts.all ? '--all' : '',
721
+ opts.scope ? `--scope ${opts.scope}` : '',
722
+ opts.since ? `--since ${opts.since}` : '',
723
+ match ? `--match ${match}` : '',
724
+ ]
725
+ .filter(Boolean)
726
+ .join(' ');
727
+ appendAudit({
728
+ at: nowIso(),
729
+ action: 'purge',
730
+ detail: `批量删除 ${ids.length} 条${pinned ? `(保留 pinned ${pinned} 条)` : ''} ${cond}`.trim(),
731
+ ids,
732
+ ...(opts.scope ? { scope: opts.scope } : {}),
733
+ });
734
+ return { ok: true, ids, pinned, dryRun };
735
+ }
736
+ /**
737
+ * 按 id 合并导入条目(R8.1 导出文件的还原端)。
738
+ *
739
+ * 冲突策略是**时序而非覆盖**(R9.2 的验收口径):同 id 时比 `updatedAt`,
740
+ * 新的胜出;相等则保留本地(本地是用户此刻真实看到的,不该被一个更早导出
741
+ * 的文件顶掉)。这不是"最后写入者胜",而是"更近的事实胜"——两台机器来回同步时,
742
+ * 单看写入顺序会把较早但被编辑过的那份覆盖掉。
743
+ *
744
+ * 刻意**不做 schema 迁移**:旧包的缺字段由各处读路径的惰性迁移兜住(与
745
+ * `dedupKey` / `trigger` / `anchors` 的既有约定一致),这里补一遍只会制造第二份真相。
746
+ */
747
+ export function importEntries(incoming) {
748
+ const blocked = memoryWriteBlockReason();
749
+ if (blocked)
750
+ return { ok: false, blocked };
751
+ const all = loadAll();
752
+ const byId = new Map(all.map((e) => [e.id, e]));
753
+ let added = 0;
754
+ let updated = 0;
755
+ let skipped = 0;
756
+ for (const raw of incoming) {
757
+ if (!raw || typeof raw.id !== 'string' || !raw.id) {
758
+ skipped++;
759
+ continue;
760
+ }
761
+ const cur = byId.get(raw.id);
762
+ if (!cur) {
763
+ // scope 以包内为准;缺失时保守落 project(不把别人的条目擅自升成全局)。
764
+ const e = { ...raw, scope: raw.scope === 'global' ? 'global' : 'project' };
765
+ all.push(e);
766
+ byId.set(e.id, e);
767
+ added++;
768
+ continue;
769
+ }
770
+ const curTs = Date.parse(cur.updatedAt || cur.createdAt) || 0;
771
+ const inTs = Date.parse(raw.updatedAt || raw.createdAt) || 0;
772
+ if (inTs <= curTs) {
773
+ skipped++;
774
+ continue;
775
+ }
776
+ const idx = all.findIndex((e) => e.id === raw.id);
777
+ if (idx >= 0) {
778
+ all[idx] = { ...raw, scope: cur.scope };
779
+ byId.set(raw.id, all[idx]);
780
+ updated++;
781
+ }
782
+ else {
783
+ skipped++;
784
+ }
785
+ }
786
+ if (added > 0 || updated > 0) {
787
+ writeBackByScope(all);
788
+ clearPendingScope('global');
789
+ clearPendingScope('project');
790
+ }
791
+ return { ok: true, added, updated, skipped };
792
+ }
271
793
  // ── 遗忘 GC(纯数据,不调 LLM)─────────────────────────────────────────────
272
794
  const DAY_MS = 86400000;
273
795
  /**
274
796
  * 遗忘策略(全同步,后台调):
275
- * ① archived 超 GC_DAYS → 硬删;
276
- * ② active + !pinned + (lastRecalledAt|createdAt) 早于 DECAY_DAYS → archived;
277
- * ③ active 数 > MAX_ACTIVE → 按 recallCount 低 × 最近未召回久 淘汰到 archived。
797
+ * ① archived 超 GC_DAYS → 硬删(**情节用 EPISODE_GC_DAYS**);
798
+ * ② active + !pinned + (lastRecalledAt|createdAt) 早于 DECAY_DAYS → archived
799
+ * (**情节用 EPISODE_DECAY_DAYS**);
800
+ * ③ active 数 > MAX_ACTIVE → 按 recallCount 低 × 最近未召回久 淘汰到 archived
801
+ * (**情节不参与**:它有自己的 ① ②,若再占事实记忆的名额,每个会话一条会在
802
+ * 两个月内把长期知识全部挤出封顶)。
278
803
  * pinned 豁免一切自动衰减。写回两文件(均按 scope 过滤)。
279
804
  */
280
805
  export function gcMemories() {
806
+ // 暂停/关闭期间不跑 GC:GC 会归档与硬删条目,那是比「写入」更重的破坏性动作。
807
+ // 返回全零让调用方(启动/轮末/反思)无感跳过。
808
+ if (memoryWriteBlockReason())
809
+ return { decayed: 0, capped: 0, gced: 0 };
281
810
  const all = loadAll();
282
811
  if (all.length === 0)
283
812
  return { decayed: 0, capped: 0, gced: 0 };
284
813
  const now = Date.now();
285
- const decayMs = DECAY_DAYS * DAY_MS;
286
- const gcMs = GC_DAYS * DAY_MS;
287
814
  const result = { decayed: 0, capped: 0, gced: 0 };
815
+ /**
816
+ * 该条目适用的衰减/清除周期(R6:情节远比事实短命)。
817
+ *
818
+ * R11 起分三档:情节 7 天、**已巩固的情节 3 天**(内容已进语义条目,只剩追溯价值)、
819
+ * 事实 30 天。降权刻意只动衰减周期而不动 status:`archived` 会让它掉出
820
+ * `computeStaleness` 的 active 判定,反过来把依赖它的语义条目判成 stale——
821
+ * 巩固完成立刻让结论显示"根据已失效",恰好是反的。让它自然衰减即可。
822
+ */
823
+ const decayMsOf = (e) => {
824
+ if (e.type !== 'episode')
825
+ return DECAY_DAYS * DAY_MS;
826
+ return (e.derivedInto ? EPISODE_CONSOLIDATED_DECAY_DAYS : EPISODE_DECAY_DAYS) * DAY_MS;
827
+ };
828
+ const gcMsOf = (e) => (e.type === 'episode' ? EPISODE_GC_DAYS : GC_DAYS) * DAY_MS;
288
829
  const refTs = (e) => {
289
830
  const r = e.lastRecalledAt ? Date.parse(e.lastRecalledAt) : Date.parse(e.createdAt);
290
831
  return Number.isFinite(r) ? r : now;
@@ -294,7 +835,7 @@ export function gcMemories() {
294
835
  if (e.status !== 'archived')
295
836
  continue;
296
837
  const u = Date.parse(e.updatedAt || e.createdAt);
297
- if (Number.isFinite(u) && now - u > gcMs) {
838
+ if (Number.isFinite(u) && now - u > gcMsOf(e)) {
298
839
  e.status = '__DELETE__'; // 标记硬删(下方过滤)
299
840
  result.gced++;
300
841
  }
@@ -303,15 +844,15 @@ export function gcMemories() {
303
844
  for (const e of all) {
304
845
  if (e.status !== 'active' || e.pinned)
305
846
  continue;
306
- if (now - refTs(e) > decayMs) {
847
+ if (now - refTs(e) > decayMsOf(e)) {
307
848
  e.status = 'archived';
308
849
  e.updatedAt = nowIso();
309
850
  result.decayed++;
310
851
  }
311
852
  }
312
- // ③ cap active
853
+ // ③ cap active —— 情节不计入(它已在 ② 走完自己的短周期)
313
854
  const active = all
314
- .filter((e) => e.status === 'active')
855
+ .filter((e) => e.status === 'active' && e.type !== 'episode')
315
856
  .sort((a, b) => a.recallCount - b.recallCount || refTs(a) - refTs(b));
316
857
  const excess = active.length - MAX_ACTIVE;
317
858
  if (excess > 0) {
@@ -330,6 +871,8 @@ export function gcMemories() {
330
871
  if (result.gced === 0 && result.decayed === 0 && result.capped === 0)
331
872
  return result;
332
873
  writeBackByScope(survivors);
874
+ clearPendingScope('global'); // 两个 scope 的文件都刚被重写,增量已烘入
875
+ clearPendingScope('project');
333
876
  return result;
334
877
  }
335
878
  // ── 启动索引段(注入 systemPrompt,同步)────────────────────────────────────
@@ -353,7 +896,10 @@ export function buildMemoryIndexSection(memoryEnabled = true) {
353
896
  if (!memoryEnabled)
354
897
  return '';
355
898
  const all = loadAll();
356
- const active = all.filter((e) => e.status === 'active');
899
+ // R6.3:episode 走 `buildEpisodeSection` 的独立小节,不进这张主索引。
900
+ // 混排会让「最近三次会话做了什么」在索引里反复刷存在感,而索引的价值是
901
+ // 长期知识的稳定清单;两者只是都借用 JSONL 存储,生命周期差一个数量级。
902
+ const active = all.filter((e) => e.status === 'active' && e.type !== 'episode');
357
903
  if (active.length === 0)
358
904
  return '';
359
905
  const now = Date.now();