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
@@ -14,7 +14,59 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
14
14
  import os from 'node:os';
15
15
  import path from 'node:path';
16
16
  import { MAX_GRAPH_EDGES, MAX_GRAPH_ENTITIES } from '../tools/constants.js';
17
- import { isSingleValueProfile, isKnownRelation } from './relation-vocab.js';
17
+ import { isSingleValueProfile, isKnownRelation, normalizeRelation } from './relation-vocab.js';
18
+ // R8.3/R8.5:写入总闸与条目库共用同一份状态(独立叶子模块,避免 graph → store 的运行时环)。
19
+ import { memoryWriteBlockReason } from './write-gate.js';
20
+ /**
21
+ * 合并导入实体与边(R8.1 导出的还原端)。
22
+ *
23
+ * 与条目库的 `importEntries` 刻意不同:图里同 id 意味着**同一条事实**,而实体/边
24
+ * 的时间语义(validAt/invalidAt)本身就承载了"何时成立/何时被取代"。按 id 直接跳过
25
+ * 是最安全的选择——覆盖一条边会抹掉它的 invalidAt,等于把一段历史"复活"。
26
+ * 新边仍可能因 (src,relation,dst) 与既有 active 边重复而出现两条,但那是既有
27
+ * `addTriple` 的去重职责,不该在这里重实现一遍(重复导入两次的结果应是幂等的:
28
+ * 第二次全部 skip)。
29
+ */
30
+ export function importGraphPart(entities, edges) {
31
+ const blocked = memoryWriteBlockReason();
32
+ if (blocked)
33
+ return { blocked };
34
+ const result = { addedEntities: 0, addedEdges: 0, skipped: 0 };
35
+ for (const scope of ['global', 'project']) {
36
+ const inScopeEnts = entities.filter((e) => (e.scope === 'global' ? 'global' : 'project') === scope);
37
+ const inScopeEdges = edges.filter((e) => (e.scope === 'global' ? 'global' : 'project') === scope);
38
+ if (inScopeEnts.length === 0 && inScopeEdges.length === 0)
39
+ continue;
40
+ const g = loadScopeGraph(scope);
41
+ const entIds = new Set(g.entities.map((e) => e.id));
42
+ const edgeIds = new Set(g.edges.map((e) => e.id));
43
+ let dirty = false;
44
+ for (const e of inScopeEnts) {
45
+ if (entIds.has(e.id)) {
46
+ result.skipped++;
47
+ continue;
48
+ }
49
+ // scope 以文件为准,防止包里 scope 字段缺失/错标把实体挂到另一个库。
50
+ g.entities.push({ ...e, scope });
51
+ entIds.add(e.id);
52
+ result.addedEntities++;
53
+ dirty = true;
54
+ }
55
+ for (const e of inScopeEdges) {
56
+ if (edgeIds.has(e.id)) {
57
+ result.skipped++;
58
+ continue;
59
+ }
60
+ g.edges.push({ ...e, scope, invalidAt: e.invalidAt ?? null });
61
+ edgeIds.add(e.id);
62
+ result.addedEdges++;
63
+ dirty = true;
64
+ }
65
+ if (dirty)
66
+ writeGraphForScope(scope, g);
67
+ }
68
+ return result;
69
+ }
18
70
  // ── 路径 / 原子写(同 store.ts 风格)──────────────────────────────────────
19
71
  function globalGraphPath() {
20
72
  return path.join(os.homedir(), '.mocode', 'memory-graph.json');
@@ -89,6 +141,10 @@ export function loadAllGraph() {
89
141
  return out;
90
142
  }
91
143
  function writeGraphForScope(scope, g) {
144
+ // 纵深防御:即便某条迁移路径忘了在入口判闸,也不能落盘。改动只发生在内存副本上,
145
+ // 下一次 loadScopeGraph 会重新读盘,因此 no-op 等价于「什么都没发生」。
146
+ if (memoryWriteBlockReason())
147
+ return;
92
148
  const p = graphPathForScope(scope);
93
149
  ensureDir(p);
94
150
  writeGraphAtomic(p, { entities: g.entities, edges: g.edges });
@@ -104,11 +160,36 @@ export function loadScopeGraph(scope) {
104
160
  }
105
161
  // ── 实体 ─────────────────────────────────────────────────────────────────
106
162
  const norm = (s) => s.trim().toLowerCase();
163
+ /**
164
+ * 跟随 `mergedInto` 重定向到活实体。
165
+ *
166
+ * 为什么必须做:mergeEntities 保留 source 并标 `mergedInto`(可追溯),但 source 的
167
+ * name/别名仍留在它自己的字段里。若查找直接返回 source,后续写入会挂到墓碑实体上,
168
+ * 于是被并掉的碎片反复重现(实测:`万` 精确命中墓碑 ent-* 而非 person-primary)。
169
+ * 环与目标缺失都原地返回,不丢数据。
170
+ */
171
+ function resolveTombstone(g, e) {
172
+ let cur = e;
173
+ const seen = new Set([cur.id]);
174
+ for (;;) {
175
+ const target = cur.mergedInto;
176
+ if (!target)
177
+ return cur;
178
+ if (seen.has(target))
179
+ return cur; // 环保护
180
+ const next = g.entities.find((x) => x.id === target);
181
+ if (!next)
182
+ return cur; // 目标缺失(手工编辑/半迁移):保持原样
183
+ seen.add(target);
184
+ cur = next;
185
+ }
186
+ }
107
187
  function findEntityIn(g, name) {
108
188
  const q = norm(name);
109
189
  if (!q)
110
190
  return undefined;
111
- return g.entities.find((e) => e.id === q || norm(e.name) === q || e.aliases.some((a) => norm(a) === q));
191
+ const hit = g.entities.find((e) => e.id === q || norm(e.name) === q || e.aliases.some((a) => norm(a) === q));
192
+ return hit ? resolveTombstone(g, hit) : undefined;
112
193
  }
113
194
  /** 全局找实体(两 scope,project 优先——项目事实比全局更具体)。 */
114
195
  export function findEntity(name) {
@@ -122,6 +203,9 @@ export function findEntity(name) {
122
203
  * scope 容量保护:超限先清孤儿实体(无任何 active 边相连);仍超 → 拒绝新实体。
123
204
  */
124
205
  export function upsertEntity(name, opts = {}) {
206
+ const blocked = memoryWriteBlockReason();
207
+ if (blocked)
208
+ return { id: '', created: false, rejected: `write-${blocked}` };
125
209
  const scope = opts.scope === 'global' ? 'global' : 'project';
126
210
  const trimmed = name.trim();
127
211
  if (!trimmed)
@@ -181,6 +265,22 @@ export function upsertEntity(name, opts = {}) {
181
265
  writeGraphForScope(scope, g);
182
266
  return { id: ent.id, created: true };
183
267
  }
268
+ /**
269
+ * 目标是否为本仓库的源码相对路径(`src/...` / `tests/...`)。
270
+ *
271
+ * 作用域守卫的判定依据是**目标形态**,不是 src 身份——单机单用户下 global 承载
272
+ * 跨项目通用知识(相机、数据集、外部服务),那些本来就该在 global;只有描述
273
+ * 「本仓库哪个文件实现了什么」的边才属于 project 格。实测曾因此有 5 条源码结构边
274
+ * 落进 global 图(2026-10-30 已迁回)。
275
+ */
276
+ export function isRepoSourcePath(raw) {
277
+ const p = String(raw ?? '')
278
+ .trim()
279
+ .replace(/\\/g, '/')
280
+ .replace(/^\.\//, '')
281
+ .toLowerCase();
282
+ return /^(src|tests)\//.test(p);
283
+ }
184
284
  /**
185
285
  * 写一条三元组。src/dst 自动 upsert 为实体。
186
286
  * 冲突策略:
@@ -191,15 +291,26 @@ export function upsertEntity(name, opts = {}) {
191
291
  * 容量保护:边超限先清已失效边;仍超 → 拒绝。
192
292
  */
193
293
  export function addTriple(input) {
294
+ const blocked = memoryWriteBlockReason();
295
+ if (blocked)
296
+ return { ok: false, reason: `write-${blocked}` };
194
297
  const src = input.src?.trim();
195
298
  const dst = input.dst?.trim();
196
- const relation = input.relation?.trim().toLowerCase().replace(/\s+/g, '_');
299
+ // 关系名在此处(唯一写入漏斗)归一到规范形,而不是依赖各调用方:
300
+ // 曾经只有 reflect.ts 的三处抽取点调 normalizeRelation,memory_save.links 与
301
+ // memory_graph add 走内联小写,导致 `cals`/`suports_override`/`prefer` 这类
302
+ // 别名绕开归一直接落库(2026-10-30 实测)。
303
+ const relation = normalizeRelation(input.relation ?? '');
197
304
  if (!src || !dst || !relation)
198
305
  return { ok: false, reason: 'missing src/relation/dst' };
199
306
  if (src.length > 80 || dst.length > 80 || relation.length > 60) {
200
307
  return { ok: false, reason: 'src/dst/relation too long' };
201
308
  }
202
- const scope = input.scope === 'global' ? 'global' : 'project';
309
+ const requested = input.scope === 'global' ? 'global' : 'project';
310
+ // 作用域守卫(R0.6.2):目标是本仓库源码路径的边只可能是 project 知识。
311
+ // 凭 dst 形态确定性改判,不信调用方——反思可能把源码结构事实误归画像轨。
312
+ const scopeEscalated = requested === 'global' && isRepoSourcePath(dst);
313
+ const scope = scopeEscalated ? 'project' : requested;
203
314
  const s = upsertEntity(src, { scope });
204
315
  if (s.rejected)
205
316
  return { ok: false, reason: `src entity: ${s.rejected}` };
@@ -220,7 +331,13 @@ export function addTriple(input) {
220
331
  // 完全等价(src+relation+dst 全等且 fact 相同/空)→ 幂等跳过。
221
332
  const exact = sameKey.find((e) => e.dst === d.id && (!fact || e.fact === fact));
222
333
  if (exact) {
223
- return { ok: true, edgeId: exact.id, superseded: 0, duplicate: true };
334
+ return {
335
+ ok: true,
336
+ edgeId: exact.id,
337
+ superseded: 0,
338
+ duplicate: true,
339
+ ...(scopeEscalated ? { scopeEscalated } : {}),
340
+ };
224
341
  }
225
342
  let superseded = 0;
226
343
  const ts = nowIso();
@@ -254,10 +371,13 @@ export function addTriple(input) {
254
371
  }
255
372
  g.edges.push(edge);
256
373
  writeGraphForScope(scope, g);
257
- return { ok: true, edgeId: edge.id, superseded };
374
+ return { ok: true, edgeId: edge.id, superseded, ...(scopeEscalated ? { scopeEscalated } : {}) };
258
375
  }
259
376
  /** 按时序失效一条边(不删除,可审计);edge id 或 (src,relation,dst 候选) 定位。 */
260
377
  export function invalidateEdge(edgeId, reason = 'manual') {
378
+ const blocked = memoryWriteBlockReason();
379
+ if (blocked)
380
+ return { ok: false, reason: `write-${blocked}` };
261
381
  const id = edgeId.trim();
262
382
  if (!id)
263
383
  return { ok: false, reason: 'missing edge id' };
@@ -278,6 +398,9 @@ export function invalidateEdge(edgeId, reason = 'manual') {
278
398
  * 仅对 person-primary 出发的画像边生效(/profile confirm 的落地点)。
279
399
  */
280
400
  export function promoteEdge(edgeId) {
401
+ const blocked = memoryWriteBlockReason();
402
+ if (blocked)
403
+ return { ok: false, reason: `write-${blocked}` };
281
404
  const id = edgeId.trim();
282
405
  if (!id)
283
406
  return { ok: false, reason: 'missing edge id' };
@@ -309,6 +432,9 @@ export function promoteEdge(edgeId) {
309
432
  * 只对 person-primary 出发的 global 画像边开放;project triples 不参与画像分级。
310
433
  */
311
434
  export function voteEdge(edgeId, vote) {
435
+ const blocked = memoryWriteBlockReason();
436
+ if (blocked)
437
+ return { ok: false, reason: `write-${blocked}` };
312
438
  const id = edgeId.trim();
313
439
  if (!id)
314
440
  return { ok: false, reason: 'missing edge id' };
@@ -342,6 +468,11 @@ export function voteEdge(edgeId, vote) {
342
468
  * 返回失效条数。
343
469
  */
344
470
  export function invalidateProfileEdges(relation, dst) {
471
+ // 返回条数的函数没有失败形状可报,只能返 0 —— 与「没有匹配的边」同形。
472
+ // 可接受:这是后台纠正动作,用户不会盯着它的返回值;
473
+ // 真正需要明确告知的写入口(saveEntry/updateEntry/addTriple)都带了 blocked 分支。
474
+ if (memoryWriteBlockReason())
475
+ return 0;
345
476
  const rel = relation.trim().toLowerCase().replace(/\s+/g, '_');
346
477
  if (!rel)
347
478
  return 0;
@@ -627,15 +758,39 @@ export function pathBetween(aNameOrId, bNameOrId) {
627
758
  }
628
759
  export function graphStats() {
629
760
  const g = loadAllGraph();
761
+ const active = g.edges.filter((e) => !e.invalidAt);
630
762
  const count = (scope) => ({
631
763
  entities: g.entities.filter((e) => e.scope === scope).length,
632
- edges: g.edges.filter((e) => e.scope === scope && !e.invalidAt).length,
764
+ edges: active.filter((e) => e.scope === scope).length,
633
765
  });
766
+ // 注意:边上的 dst 是**实体 id**(如 `src-llm-reasoning-ts`),不是原始路径。
767
+ // 必须解析回实体名(`src/llm/reasoning.ts`)再判定,否则该指标恒为 0(死指标)。
768
+ const nameOf = new Map(g.entities.map((e) => [e.id, e.name]));
769
+ const vocabOf = (scope) => {
770
+ const edges = active.filter((e) => e.scope === scope);
771
+ const inVocab = edges.filter((e) => isKnownRelation(e.relation, scope)).length;
772
+ return { total: edges.length, inVocab, outVocab: edges.length - inVocab };
773
+ };
774
+ const provDistribution = {};
775
+ for (const e of active) {
776
+ const k = e.prov ?? 'none';
777
+ provDistribution[k] = (provDistribution[k] ?? 0) + 1;
778
+ }
634
779
  return {
635
780
  entities: g.entities.length,
636
- edgesActive: g.edges.filter((e) => !e.invalidAt).length,
637
- edgesInvalid: g.edges.filter((e) => !!e.invalidAt).length,
781
+ edgesActive: active.length,
782
+ edgesInvalid: g.edges.length - active.length,
638
783
  byScope: { project: count('project'), global: count('global') },
784
+ globalRepoPathEdges: active.filter((e) => e.scope === 'global' && isRepoSourcePath(nameOf.get(e.dst) ?? e.dst))
785
+ .length,
786
+ vocab: { project: vocabOf('project'), global: vocabOf('global') },
787
+ provDistribution,
788
+ crossScopeRelationUse: {
789
+ // 用了 global 词表内、但 project 词表外的关系(中性观测,不代表写错)。
790
+ projectUsesProfileRel: active.filter((e) => e.scope === 'project' && isKnownRelation(e.relation, 'global') && !isKnownRelation(e.relation, 'project')).length,
791
+ globalUsesProjectRel: active.filter((e) => e.scope === 'global' && isKnownRelation(e.relation, 'project') && !isKnownRelation(e.relation, 'global')).length,
792
+ },
793
+ typedEntities: g.entities.filter((e) => entityType(e) !== UNKNOWN_TYPE).length,
639
794
  };
640
795
  }
641
796
  // ── 规范用户画像实体(G0 身份归一)──────────────────────────────────────────
@@ -723,6 +878,9 @@ export function ensurePrimaryPerson(displayName) {
723
878
  * 幂等:source===target 或不存在则 no-op(null)。
724
879
  */
725
880
  export function mergeEntities(targetId, sourceId, scope = 'global') {
881
+ const blocked = memoryWriteBlockReason();
882
+ if (blocked)
883
+ return { target: targetId, merged: [], dedupedEdges: 0, rejected: `write-${blocked}` };
726
884
  if (targetId === sourceId)
727
885
  return null;
728
886
  const g = loadScopeGraph(scope);
@@ -838,3 +996,69 @@ export function migrateLegacyProfileProvenance(force = false) {
838
996
  export function __resetLegacyMigrationForTests() {
839
997
  legacyMigrationDone = false;
840
998
  }
999
+ export function migrateRelationAliases(scope) {
1000
+ const g = loadScopeGraph(scope);
1001
+ const renamed = [];
1002
+ for (const e of g.edges) {
1003
+ if (e.invalidAt)
1004
+ continue;
1005
+ const next = normalizeRelation(e.relation);
1006
+ if (next === e.relation)
1007
+ continue;
1008
+ renamed.push({ from: e.relation, to: next });
1009
+ e.relation = next;
1010
+ }
1011
+ if (renamed.length > 0)
1012
+ writeGraphForScope(scope, g);
1013
+ return { migrated: renamed.length, renamed };
1014
+ }
1015
+ // ── R0.5.4 实体类型确定性回填 ──────────────────────────────────────────────
1016
+ //
1017
+ // 分型只走**确定性规则**,不猜:一条边若 (a) 关系语义指向"文件/目录"且
1018
+ // (b) dst 实体名确实是本仓库路径,才把 dst 标成 FilePath。两个条件缺一不可——
1019
+ // 只看关系名会把 `implemented_in → src/models` 之外的误标,只看名字形状则等于
1020
+ // 靠名字猜(设计文档明确反对)。
1021
+ //
1022
+ // 只写 type 缺失或为 unknown 的实体;已有类型的绝不覆盖(人工/其它规则优先)。
1023
+ /** 目标语义是"仓库文件/目录"的关系。 */
1024
+ const FILE_TARGET_RELATIONS = new Set([
1025
+ 'implemented_in',
1026
+ 'tests',
1027
+ 'tested_in',
1028
+ 'documented_in',
1029
+ 'reads',
1030
+ 'writes',
1031
+ 'stored_in',
1032
+ 'configured_by',
1033
+ ]);
1034
+ /** 文件类实体的类型标记。 */
1035
+ export const FILE_TYPE = 'FilePath';
1036
+ export function migrateEntityTypes(scope) {
1037
+ const g = loadScopeGraph(scope);
1038
+ const byId = new Map(g.entities.map((e) => [e.id, e]));
1039
+ const patch = new Map();
1040
+ for (const e of g.edges) {
1041
+ if (e.invalidAt)
1042
+ continue;
1043
+ if (!FILE_TARGET_RELATIONS.has(normalizeRelation(e.relation)))
1044
+ continue;
1045
+ const dst = byId.get(e.dst);
1046
+ if (!dst)
1047
+ continue;
1048
+ if (!isRepoSourcePath(dst.name))
1049
+ continue;
1050
+ if (entityType(dst) !== UNKNOWN_TYPE)
1051
+ continue;
1052
+ patch.set(dst.id, FILE_TYPE);
1053
+ }
1054
+ for (const [id, type] of patch) {
1055
+ const ent = byId.get(id);
1056
+ if (!ent)
1057
+ continue;
1058
+ ent.type = type;
1059
+ ent.updatedAt = nowIso();
1060
+ }
1061
+ if (patch.size > 0)
1062
+ writeGraphForScope(scope, g);
1063
+ return { typed: patch.size };
1064
+ }
@@ -0,0 +1,208 @@
1
+ // health.ts —— R4.1 记忆健康快照。
2
+ //
3
+ // 存在的理由:在此之前,"记忆到底有没有用"只能靠手感。文档 §2.1 早就写着
4
+ // 「先有尺子再造家具」,但尺子一直是缺的 —— R3 前摄、R6 情节、R11 巩固都实现完了,
5
+ // 却没有任何一个数字能回答"它在真实使用中命中过吗"。
6
+ //
7
+ // 只做**汇总**,不做采集:
8
+ // - 条目/锚点/派生来自 `store.ts` 的读时判定(不新增埋点,零写放大);
9
+ // - 检索来自 `recall-stats.ts`(已有);
10
+ // - 前摄来自 `proactive.ts` 的计数器(R4.1 新增,内存累计 + 退出落盘);
11
+ // - 画像来自 `persona.ts` 的两张清单。
12
+ //
13
+ // 叶子依赖:只读 memory 模块内部状态与 node 标准库,不依赖 config/agent/repl。
14
+ // 开关由调用方判定后经 `enabled` 传入(同 store.ts 的既有约定),这样 health 本身
15
+ // 可测试、也不会在"记忆已关闭"时偷偷建文件。
16
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { loadAll, loadAnchorStaleMap, loadStalenessMap, wantsTrigger, } from './store.js';
19
+ import { readRecallStats } from './recall-stats.js';
20
+ import { proactiveCounters } from './proactive.js';
21
+ import { listInternalizedProfile, listProfileCandidates } from './persona.js';
22
+ import { MAX_ACTIVE } from '../tools/constants.js';
23
+ /** 快照结构版本。字段增删时自增,让读旧文件的人能立刻发现口径变了。 */
24
+ export const MEMORY_HEALTH_SCHEMA_VERSION = 1;
25
+ function rate(num, den) {
26
+ if (den <= 0)
27
+ return 0;
28
+ // 保留三位小数:这个文件会被 diff 比较,浮点评比点好看。
29
+ return Math.round((num / den) * 1000) / 1000;
30
+ }
31
+ /** 汇总一份快照。纯读,不写盘、不改任何条目。 */
32
+ export function buildMemoryHealth() {
33
+ const all = loadAll();
34
+ const active = all.filter((e) => e.status === 'active');
35
+ const byType = {};
36
+ const byScope = {};
37
+ for (const e of active) {
38
+ byType[e.type] = (byType[e.type] ?? 0) + 1;
39
+ byScope[e.scope] = (byScope[e.scope] ?? 0) + 1;
40
+ }
41
+ // trigger 覆盖:分母只含建议带 trigger 的类型(理由见 MemoryHealth.trigger)
42
+ const triggerRequired = active.filter((e) => e.type !== 'episode' && wantsTrigger(e.type));
43
+ const withTrigger = triggerRequired.filter((e) => !!e.trigger?.trim());
44
+ const staleness = loadStalenessMap(all);
45
+ const anchorStale = loadAnchorStaleMap(all);
46
+ const derivedEntries = active.filter((e) => (e.derivedFrom?.length ?? 0) > 0);
47
+ const anchorEntries = active.filter((e) => (e.anchors?.length ?? 0) > 0);
48
+ const episodes = active.filter((e) => e.type === 'episode');
49
+ const consolidated = episodes.filter((e) => !!e.derivedInto);
50
+ const recall = readRecallStats();
51
+ const pc = proactiveCounters();
52
+ let internalized = 0;
53
+ let candidates = 0;
54
+ try {
55
+ internalized = listInternalizedProfile().length;
56
+ candidates = listProfileCandidates().length;
57
+ }
58
+ catch {
59
+ // 图谱读失败只是少两项画像数字,不该让整个快照失败
60
+ }
61
+ const health = {
62
+ schemaVersion: MEMORY_HEALTH_SCHEMA_VERSION,
63
+ generatedAt: new Date().toISOString(),
64
+ entries: {
65
+ total: all.length,
66
+ active: active.length,
67
+ archived: all.filter((e) => e.status === 'archived').length,
68
+ superseded: all.filter((e) => e.status === 'superseded').length,
69
+ byType,
70
+ byScope,
71
+ activeCapUsage: rate(active.filter((e) => e.type !== 'episode').length, MAX_ACTIVE),
72
+ },
73
+ trigger: {
74
+ required: triggerRequired.length,
75
+ withTrigger: withTrigger.length,
76
+ coverage: rate(withTrigger.length, triggerRequired.length),
77
+ },
78
+ anchors: {
79
+ anchored: anchorEntries.length,
80
+ stale: anchorEntries.filter((e) => anchorStale.get(e.id)?.stale).length,
81
+ staleRate: rate(anchorEntries.filter((e) => anchorStale.get(e.id)?.stale).length, anchorEntries.length),
82
+ },
83
+ derived: {
84
+ total: derivedEntries.length,
85
+ stale: derivedEntries.filter((e) => staleness.get(e.id)?.stale).length,
86
+ staleRate: rate(derivedEntries.filter((e) => staleness.get(e.id)?.stale).length, derivedEntries.length),
87
+ },
88
+ episodes: {
89
+ active: episodes.length,
90
+ consolidated: consolidated.length,
91
+ consolidationRate: rate(consolidated.length, episodes.length),
92
+ },
93
+ retrieval: {
94
+ searches: recall.searches,
95
+ graphHits: recall.graphHits,
96
+ graphHitRate: rate(recall.graphHits, recall.searches),
97
+ lastSearchedAt: recall.lastSearchedAt,
98
+ neverRecalled: active.filter((e) => e.type !== 'episode' && e.recallCount === 0).length,
99
+ },
100
+ proactive: {
101
+ ...pc,
102
+ injectRate: rate(pc.injections, pc.toolCalls),
103
+ staleAnchorRate: rate(pc.staleAnchorHits, pc.anchorHits),
104
+ },
105
+ profile: { internalized, candidates },
106
+ warnings: [],
107
+ };
108
+ health.warnings = collectWarnings(health);
109
+ return health;
110
+ }
111
+ /**
112
+ * 把"数字异常"翻译成人话。
113
+ *
114
+ * 为什么值得写:纯数字文件没人看。每条 warning 都指向一个**可执行**的动作,
115
+ * 而不是复述指标本身 —— 否则它只是把同一组数字换个说法。
116
+ */
117
+ function collectWarnings(h) {
118
+ const out = [];
119
+ if (h.retrieval.searches === 0 && h.entries.active > 0) {
120
+ out.push('memory_search 从未被调用:记忆只写不读,pull 侧优化全部无效,优先看 push(R3/R3.6)是否命中');
121
+ }
122
+ if (h.trigger.required >= 5 && h.trigger.coverage < 0.5) {
123
+ out.push(`trigger 覆盖率仅 ${Math.round(h.trigger.coverage * 100)}%(${h.trigger.withTrigger}/${h.trigger.required}),前摄索引会命中不到东西`);
124
+ }
125
+ if (h.proactive.toolCalls >= 50 && h.proactive.injections === 0) {
126
+ out.push(`前摄 ${h.proactive.toolCalls} 次可匹配调用零注入:检查 trigger 用词是否与真实任务文本重合`);
127
+ }
128
+ if (h.proactive.staleAnchorRate > 0.3 && h.proactive.anchorHits >= 5) {
129
+ out.push(`锚点注入里 ${Math.round(h.proactive.staleAnchorRate * 100)}% 已失效:考虑加固符号片段或降低 stale 注入优先级`);
130
+ }
131
+ if (h.episodes.active >= 6 && h.episodes.consolidated === 0) {
132
+ out.push(`已有 ${h.episodes.active} 条情节但零巩固:检查 R11 分组阈值是否过严,或巩固任务是否被开关关掉`);
133
+ }
134
+ if (h.entries.activeCapUsage > 0.8) {
135
+ out.push(`active 已占封顶 ${Math.round(h.entries.activeCapUsage * 100)}%:即将开始淘汰低召回条目`);
136
+ }
137
+ if (h.derived.total > 0 && h.derived.staleRate > 0.5) {
138
+ out.push(`派生条目 ${Math.round(h.derived.staleRate * 100)}% 已因源失效待复核:需要一轮反思去重写结论`);
139
+ }
140
+ return out.slice(0, 6);
141
+ }
142
+ function healthPath() {
143
+ return path.join(process.cwd(), '.mocode', 'memory-health.json');
144
+ }
145
+ /**
146
+ * 写快照。`enabled=false` 时不落盘(关闭记忆就不该留下任何记忆文件,R8.5 同一口径)。
147
+ * 原子写(tmp+rename),失败静默:健康快照是可观测性产物,绝不能拖垮主流程。
148
+ */
149
+ export function writeMemoryHealth(enabled = true) {
150
+ if (!enabled)
151
+ return null;
152
+ let health;
153
+ try {
154
+ health = buildMemoryHealth();
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ try {
160
+ const p = healthPath();
161
+ mkdirSync(path.dirname(p), { recursive: true });
162
+ const tmp = p + '.tmp';
163
+ writeFileSync(tmp, JSON.stringify(health, null, 2) + '\n', 'utf8');
164
+ renameSync(tmp, p);
165
+ }
166
+ catch {
167
+ // 静默:观测失败不影响功能
168
+ }
169
+ return health;
170
+ }
171
+ /** 读回既有快照(供 `/memory health --last` 之类场景);缺失/损坏返 null。 */
172
+ export function readMemoryHealth() {
173
+ try {
174
+ const p = healthPath();
175
+ if (!existsSync(p))
176
+ return null;
177
+ const o = JSON.parse(readFileSync(p, 'utf8'));
178
+ return o && typeof o === 'object' ? o : null;
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ }
184
+ const pct = (v) => `${Math.round(v * 100)}%`;
185
+ /** 供 `/memory health` 渲染的多行文本(无 UI 依赖,命令层自己上色)。 */
186
+ export function formatMemoryHealth(h = buildMemoryHealth()) {
187
+ const lines = [];
188
+ lines.push(`条目:active ${h.entries.active} / total ${h.entries.total}` +
189
+ `(archived ${h.entries.archived}${h.entries.superseded ? `, superseded ${h.entries.superseded}` : ''})` +
190
+ ` · 封顶占用 ${pct(h.entries.activeCapUsage)}`);
191
+ const types = Object.entries(h.entries.byType)
192
+ .map(([t, n]) => `${t} ${n}`)
193
+ .join(' ');
194
+ if (types)
195
+ lines.push(`按类:${types}`);
196
+ lines.push(`trigger 覆盖:${h.trigger.withTrigger}/${h.trigger.required}(${pct(h.trigger.coverage)})`);
197
+ lines.push(`锚点:${h.anchors.anchored} 条已锚 · stale ${h.anchors.stale}(${pct(h.anchors.staleRate)})` +
198
+ ` | 派生:${h.derived.total} 条 · 待复核 ${h.derived.stale}(${pct(h.derived.staleRate)})`);
199
+ lines.push(`情节:active ${h.episodes.active} · 已巩固 ${h.episodes.consolidated}(${pct(h.episodes.consolidationRate)})`);
200
+ lines.push(`检索:memory_search ${h.retrieval.searches} 次 · 图谱命中 ${h.retrieval.graphHits}(${pct(h.retrieval.graphHitRate)})` +
201
+ ` · 从未被召回的 active ${h.retrieval.neverRecalled} 条`);
202
+ lines.push(`前摄:可匹配调用 ${h.proactive.toolCalls} · 注入 ${h.proactive.injections}(${pct(h.proactive.injectRate)})` +
203
+ ` · trigger ${h.proactive.triggerHits} / 锚点 ${h.proactive.anchorHits}(其中失效 ${h.proactive.staleAnchorHits},${pct(h.proactive.staleAnchorRate)})`);
204
+ lines.push(`画像:内化 ${h.profile.internalized} · 候选 ${h.profile.candidates}`);
205
+ for (const w of h.warnings)
206
+ lines.push(`⚠ ${w}`);
207
+ return lines;
208
+ }
@@ -2,8 +2,17 @@
2
2
  // AGENTS.md is intentionally not loaded here either: config/index.ts
3
3
  // (buildAgentsImportSection) auto-imports the workspace-root AGENTS.md body into the
4
4
  // system prompt — independent of the memory switch — truncating it when it exceeds the cap.
5
- export { buildMemoryIndexSection, loadAll, gcMemories, supersedeEntry, } from './store.js';
6
- export { addTriple, upsertEntity, findEntity, searchGraph, searchGraphFacts, neighborsOf, pathBetween, graphStats, ensurePrimaryPerson, mergeEntities, canonicalizePrimaryPerson, invalidateEdge, promoteEdge, voteEdge, invalidateProfileEdges, migrateLegacyProfileProvenance, __resetLegacyMigrationForTests, PRIMARY_PERSON_ID, } from './graph.js';
5
+ export { buildMemoryIndexSection, loadAll, gcMemories, supersedeEntry, flushRecallStats, pendingRecallCount, computeDedupKey, computeStaleness, loadStalenessMap, __resetPendingRecallForTests,
6
+ // R8.2 / R8.5 / R8.3 / R9.2:用户主权面
7
+ purgeEntries, importEntries, forgetEntry, searchEntries, setMemoryWritesPaused, isMemoryWritesPaused, memoryWriteBlockReason, memoryWriteBlockedMessage, __resetMemoryPauseForTests, } from './store.js';
8
+ export { appendAudit, readAudit, auditPath } from './audit.js';
9
+ export { buildPack, writePack, parsePack, applyPack, importPackFile, defaultPackPath, MEMORY_PACK_SCHEMA_VERSION, } from './portable.js';
10
+ export { addTriple, upsertEntity, loadAllGraph, importGraphPart, findEntity, searchGraph, searchGraphFacts, neighborsOf, pathBetween, graphStats, ensurePrimaryPerson, mergeEntities, canonicalizePrimaryPerson, invalidateEdge, promoteEdge, voteEdge, invalidateProfileEdges, migrateLegacyProfileProvenance, __resetLegacyMigrationForTests, PRIMARY_PERSON_ID, } from './graph.js';
7
11
  export { buildAboutYouSection, initPersona, isInternalizedEdge, listProfileCandidates, listInternalizedProfile, inspectPrimaryProfile, __resetPersonaInitForTests, ABOUT_YOU_MAX_CHARS, } from './persona.js';
8
12
  export { buildProjectGraphHint, GRAPH_HINT_MAX_CHARS } from './recall.js';
9
- export { kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, } from './reflect.js';
13
+ export { isProactiveEnabled, proactiveHint, resetProactiveTurn, proactiveTurnCount, proactiveFiredIds, proactiveCounters, flushProactiveStats, __resetProactiveForTests, __resetProactiveCountersForTests, } from './proactive.js';
14
+ export { buildMemoryHealth, writeMemoryHealth, readMemoryHealth, formatMemoryHealth, MEMORY_HEALTH_SCHEMA_VERSION, } from './health.js';
15
+ export { captureMemoryBaseline, buildMemoryTailSection, __resetMemoryBaselineForTests, } from './tail.js';
16
+ export { isCompactHandoffEnabled, appendPendingCandidates, loadPendingCandidates, trimPendingCandidates, pendingCandidateCount, extractMemoryCandidates, formatPendingForReflect, memoryCandidatesInstruction, MEMORY_CANDIDATES_HEADING, } from './pending.js';
17
+ export { kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, kickoffConsolidation, runConsolidation, parseConsolidationPlan, getLastConsolidationResult, clearLastConsolidationResult, formatConsolidationResult, } from './reflect.js';
18
+ export { isEpisodicEnabled, isConsolidationEnabled, collectChangedFiles, extractCompactionSummary, parsePendingSteps, buildEpisode, recordSessionEpisode, listEpisodes, buildEpisodeSection, episodeFactsOf, findConsolidationGroups, applyConsolidation, CONSOLIDATED_NAME_SUFFIX, } from './episodic.js';