dsh-cortex-memory 0.4.22 → 0.4.147

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 (154) hide show
  1. package/CHANGELOG.md +2390 -154
  2. package/README.md +11 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +10 -10
  5. package/bench/synthetic.js +3 -3
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/client.js +1 -1
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/icon.svg +12 -2
  15. package/index.js +27 -3
  16. package/package.json +3 -3
  17. package/src/adapters/shiori.js +1 -1
  18. package/src/api/routes.js +1 -1
  19. package/src/core/feature-overrides.js +2 -2
  20. package/src/engines/compression.js +172 -3
  21. package/src/engines/consolidate.js +397 -26
  22. package/src/engines/encode.js +16 -3
  23. package/src/engines/extract.js +72 -8
  24. package/src/engines/fact-guard.js +51 -0
  25. package/src/engines/health.js +263 -3
  26. package/src/engines/inhibition.js +39 -0
  27. package/src/engines/life.js +14 -3
  28. package/src/engines/llm-facts.js +12 -9
  29. package/src/engines/narrative.js +150 -13
  30. package/src/engines/reflect.js +172 -14
  31. package/src/engines/retrieve.js +44 -5
  32. package/src/engines/summary-coverage.js +62 -0
  33. package/src/engines/summary-dedupe.js +77 -0
  34. package/src/engines/summon-rank.js +132 -0
  35. package/src/host/runtime.js +64 -4
  36. package/src/host/scheduler.js +224 -3
  37. package/src/llm/adapter.js +29 -8
  38. package/src/memory/query.js +1 -1
  39. package/src/memory/spacing.js +15 -0
  40. package/src/memory/tokenizer.js +1 -1
  41. package/src/prompt/tiers.js +88 -12
  42. package/src/self/alias.js +25 -0
  43. package/src/self/emotion.js +3 -1
  44. package/src/self/relationship.js +44 -13
  45. package/src/self/state.js +20 -2
  46. package/src/self/working.js +34 -3
  47. package/src/service/cortex.js +493 -53
  48. package/src/store/repositories/facts.js +34 -1
  49. package/src/store/repositories/summaries.js +8 -1
  50. package/src/store/repositories/traces.js +22 -2
  51. package/src/tools/definitions.js +118 -4
  52. package/src/vector/index.js +96 -7
  53. package/test/integration/_helpers.js +0 -128
  54. package/test/integration/acceptance.test.js +0 -803
  55. package/test/integration/ann-load.test.js +0 -61
  56. package/test/integration/api-contract.test.js +0 -1476
  57. package/test/integration/backup-privacy.test.js +0 -214
  58. package/test/integration/consolidate.test.js +0 -75
  59. package/test/integration/edge-cases.test.js +0 -1088
  60. package/test/integration/exchange.test.js +0 -326
  61. package/test/integration/life-loop.test.js +0 -188
  62. package/test/integration/load.test.js +0 -751
  63. package/test/integration/markdown-sync.test.js +0 -35
  64. package/test/integration/policy-query-api.test.js +0 -306
  65. package/test/integration/resilience-writes.test.js +0 -241
  66. package/test/integration/tools-contract.test.js +0 -1324
  67. package/test/unit/ann-edge.test.js +0 -102
  68. package/test/unit/ann.test.js +0 -77
  69. package/test/unit/api-client.test.js +0 -576
  70. package/test/unit/api-validate.test.js +0 -19
  71. package/test/unit/api.test.js +0 -555
  72. package/test/unit/appraisal.test.js +0 -48
  73. package/test/unit/attachments.test.js +0 -33
  74. package/test/unit/autonomy.test.js +0 -53
  75. package/test/unit/batch.test.js +0 -46
  76. package/test/unit/bench.test.js +0 -40
  77. package/test/unit/benchmark-synthetic.test.js +0 -52
  78. package/test/unit/cli-default-root.test.js +0 -21
  79. package/test/unit/client-contract.test.js +0 -32
  80. package/test/unit/compression.test.js +0 -76
  81. package/test/unit/core.test.js +0 -77
  82. package/test/unit/develop.test.js +0 -130
  83. package/test/unit/development.test.js +0 -68
  84. package/test/unit/digest.test.js +0 -26
  85. package/test/unit/dsr.test.js +0 -111
  86. package/test/unit/edges-candidates.test.js +0 -113
  87. package/test/unit/emotion.test.js +0 -61
  88. package/test/unit/encode.test.js +0 -98
  89. package/test/unit/evolution.test.js +0 -130
  90. package/test/unit/external-ann-search.test.js +0 -50
  91. package/test/unit/external-ann.test.js +0 -29
  92. package/test/unit/facts-belief.test.js +0 -32
  93. package/test/unit/facts.test.js +0 -107
  94. package/test/unit/feature-overrides.test.js +0 -42
  95. package/test/unit/fts-migration.test.js +0 -42
  96. package/test/unit/graph.test.js +0 -79
  97. package/test/unit/growth-reflect.test.js +0 -123
  98. package/test/unit/guard-runtime.test.js +0 -40
  99. package/test/unit/guardian.test.js +0 -91
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/hnsw.test.js +0 -35
  102. package/test/unit/host-runtime.test.js +0 -142
  103. package/test/unit/host.test.js +0 -58
  104. package/test/unit/identity.test.js +0 -98
  105. package/test/unit/induct-evaluate.test.js +0 -41
  106. package/test/unit/ingest-extracted.test.js +0 -35
  107. package/test/unit/initiative.test.js +0 -90
  108. package/test/unit/jobs.test.js +0 -93
  109. package/test/unit/json-snapshot.test.js +0 -57
  110. package/test/unit/life-consolidate.test.js +0 -34
  111. package/test/unit/life.test.js +0 -149
  112. package/test/unit/llm-facts-integration.test.js +0 -27
  113. package/test/unit/llm-facts.test.js +0 -16
  114. package/test/unit/llm.test.js +0 -45
  115. package/test/unit/locomo.test.js +0 -45
  116. package/test/unit/longmemeval.test.js +0 -56
  117. package/test/unit/markdown-import.test.js +0 -44
  118. package/test/unit/markdown.test.js +0 -34
  119. package/test/unit/memory-edit.test.js +0 -112
  120. package/test/unit/metrics.test.js +0 -26
  121. package/test/unit/migration.test.js +0 -38
  122. package/test/unit/model-config.test.js +0 -52
  123. package/test/unit/narrative.test.js +0 -62
  124. package/test/unit/playbook-consolidate.test.js +0 -24
  125. package/test/unit/privacy-scope.test.js +0 -39
  126. package/test/unit/profile-paths.test.js +0 -21
  127. package/test/unit/profile.test.js +0 -26
  128. package/test/unit/prompt.test.js +0 -42
  129. package/test/unit/providers.test.js +0 -42
  130. package/test/unit/qa.test.js +0 -100
  131. package/test/unit/query.test.js +0 -53
  132. package/test/unit/retention.test.js +0 -31
  133. package/test/unit/retrieval-ranking.test.js +0 -31
  134. package/test/unit/retrieve.test.js +0 -117
  135. package/test/unit/rotation.test.js +0 -25
  136. package/test/unit/scanner.test.js +0 -50
  137. package/test/unit/scenario.test.js +0 -78
  138. package/test/unit/scheduler.test.js +0 -136
  139. package/test/unit/self-state.test.js +0 -94
  140. package/test/unit/service.test.js +0 -72
  141. package/test/unit/shiori-import.test.js +0 -77
  142. package/test/unit/skills.test.js +0 -104
  143. package/test/unit/store.test.js +0 -111
  144. package/test/unit/temporal-graph.test.js +0 -44
  145. package/test/unit/tiers.test.js +0 -39
  146. package/test/unit/tokenizer-fts.test.js +0 -35
  147. package/test/unit/tools.test.js +0 -122
  148. package/test/unit/upgrade-0412.test.js +0 -104
  149. package/test/unit/upgrade-0413.test.js +0 -84
  150. package/test/unit/upgrade-0414.test.js +0 -101
  151. package/test/unit/vector-ann.test.js +0 -53
  152. package/test/unit/vector-async.test.js +0 -69
  153. package/test/unit/vector.test.js +0 -68
  154. package/test/unit/working.test.js +0 -80
@@ -36,6 +36,26 @@ function combineConfidence(a, b) {
36
36
  return Math.min(1, 1 - (1 - Number(a || 0)) * (1 - Number(b || 0)));
37
37
  }
38
38
 
39
+ const NEGATION_HEAD = /^(?:不|没|未|别|没有|不会|不是)/;
40
+
41
+ function normalizeLiteral(value) {
42
+ return String(value ?? '').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
43
+ }
44
+
45
+ /**
46
+ * Same subject + same predicate does not automatically mean a conflict.
47
+ * "一直在" and "一直存在着" say compatible things. Only a negation that flips
48
+ * the claim ("会一直在" vs "不会一直在") is treated as a real dispute; the
49
+ * negation must lead the literal, otherwise it is part of the object itself
50
+ * ("记忆不丢"), not a contradiction.
51
+ */
52
+ export function negationFlip(a, b) {
53
+ const left = normalizeLiteral(a);
54
+ const right = normalizeLiteral(b);
55
+ if (!left || !right) return false;
56
+ return NEGATION_HEAD.test(left) !== NEGATION_HEAD.test(right);
57
+ }
58
+
39
59
  export function createFactRepository(db) {
40
60
  function get(id) {
41
61
  return rowToFact(db.prepare('SELECT * FROM facts WHERE id = ?').get(id));
@@ -120,7 +140,20 @@ export function createFactRepository(db) {
120
140
  const later = existing.filter((fact) => fact.validFrom <= validFrom).at(-1);
121
141
  if (later) {
122
142
  if (later.validFrom === validFrom) {
123
- // Same start, different object: keep both but mark them disputed and
143
+ // Same start, different object. The compatibility rule only applies
144
+ // when both sides are free text: "一直在" and "一直存在着" can coexist.
145
+ // Entity-to-entity conflicts (likes 咖啡 vs likes 茶) still dispute.
146
+ const newLiteral = objectLiteral ?? null;
147
+ const allLiterals = Boolean(newLiteral) && existing.every((fact) => Boolean(fact.objectLiteral));
148
+ const flip = allLiterals && existing.some((fact) => negationFlip(fact.objectLiteral, newLiteral));
149
+ if (allLiterals && !flip) {
150
+ const fact = insertFact({
151
+ scopeId, subjectId, predicate, objectId, objectLiteral, validFrom, validTo,
152
+ recordedAt, confidence, status: 'active', sourceEventId, evidence,
153
+ });
154
+ return { action: 'compatible', fact, invalidated: [] };
155
+ }
156
+ // Genuinely contradictory: keep both but mark them disputed and
124
157
  // record the dispute. A later reflection/verification can resolve it.
125
158
  const disputed = existing.map((fact) => {
126
159
  db.prepare("UPDATE facts SET status = 'disputed', updated_at = ? WHERE id = ?").run(nowIso(), fact.id);
@@ -48,5 +48,12 @@ export function createSummaryRepository(db) {
48
48
  return rows.map(rowToSummary);
49
49
  }
50
50
 
51
- return { insert, get, findPeriod, list };
51
+ // Narrative threads need a retention knob: they are rebuilt from the same
52
+ // recurring topics, so without a cap the table grows forever.
53
+ function remove(id) {
54
+ const result = db.prepare('DELETE FROM summaries WHERE id = ?').run(id);
55
+ return result.changes > 0;
56
+ }
57
+
58
+ return { insert, get, findPeriod, list, remove };
52
59
  }
@@ -195,6 +195,18 @@ export function createTraceRepository(db) {
195
195
  return rows.map(rowToTrace);
196
196
  }
197
197
 
198
+ // Range query by recorded_at. listSince() walks forward from a start instant and
199
+ // stops at `limit`, so asking it for "the pool around this trace" silently
200
+ // returns the OLDEST rows when the store is older than the limit — the narrative
201
+ // engine hit that and every thread's bullets came out as 11-11/11-12 residue.
202
+ function range(scopeId = 'global', fromIso, toIso, { limit = 500, state = 'active' } = {}) {
203
+ const count = Math.max(1, Math.min(4000, Number(limit) || 500));
204
+ const rows = state
205
+ ? db.prepare('SELECT * FROM traces WHERE scope_id = ? AND state = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY recorded_at ASC LIMIT ?').all(scopeId, state, fromIso, toIso, count)
206
+ : db.prepare('SELECT * FROM traces WHERE scope_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY recorded_at ASC LIMIT ?').all(scopeId, fromIso, toIso, count);
207
+ return rows.map(rowToTrace);
208
+ }
209
+
198
210
  function update(id, patch = {}) {
199
211
  const current = get(id);
200
212
  if (!current) throw new CortexError(ERROR_CODES.NOT_FOUND, `trace not found: ${id}`);
@@ -253,7 +265,15 @@ export function createTraceRepository(db) {
253
265
  return Number(db.prepare('SELECT COUNT(*) AS c FROM traces').get().c);
254
266
  }
255
267
 
256
- function ftsCount() {
268
+ function ftsCount({ scopeId = null } = {}) {
269
+ // Without a scope this is the whole index. With one it must join through
270
+ // traces: health used to compare the *global* trace count against the
271
+ // *whole* FTS table and reported drift whenever another scope existed
272
+ // (a real store had an `agency` scope, so it warned by exactly those
273
+ // 12 rows forever).
274
+ if (scopeId) {
275
+ return Number(db.prepare('SELECT COUNT(*) AS c FROM traces_fts_index f JOIN traces t ON t.id = f.trace_id WHERE t.scope_id = ?').get(scopeId).c);
276
+ }
257
277
  return Number(db.prepare('SELECT COUNT(*) AS c FROM traces_fts_index').get().c);
258
278
  }
259
279
 
@@ -274,5 +294,5 @@ export function createTraceRepository(db) {
274
294
  `).all(scopeId, Math.max(1, Math.min(100, limit))).map((row) => ({ hash: row.hash, count: Number(row.c) }));
275
295
  }
276
296
 
277
- return { insert, get, findByEvent, findByHash, list, listSince, update, touch, remove, searchFts, count, ftsCount, reindexFts, duplicateHashes };
297
+ return { insert, get, findByEvent, findByHash, list, listSince, range, update, touch, remove, searchFts, count, ftsCount, reindexFts, duplicateHashes };
278
298
  }
@@ -50,6 +50,47 @@ function formatSelf(snapshot) {
50
50
 
51
51
  function formatHealth(report) {
52
52
  const lines = [`健康分:${report.score}/100`, `事件 ${report.counts.events} · 痕迹 ${report.counts.traces.total}(active ${report.counts.traces.active})· 事实 ${report.counts.facts.active} · 技能 ${report.counts.skills}`];
53
+ if (report.inhibition?.enabled) lines.push(`抑制:${report.inhibition.count} 条 · 均值 ${report.inhibition.average}`);
54
+ if (report.capture?.total) lines.push(`捕获:${report.capture.total} 轮 · 剥掉 ${report.capture.stripped} · 截断 ${report.capture.truncated}`);
55
+ if (report.capture?.days?.length) lines.push(`按天:${report.capture.days.slice(0, 3).map((day) => `${day.day} ${day.total}轮/剥${day.stripped}`).join(' · ')}`);
56
+ if (report.vectors) lines.push(`向量:${Math.round(report.vectors.coverage * 100)}%(${report.vectors.embedded}/${report.counts.traces.active})`);
57
+ if (report.consolidation?.dream || report.consolidation?.sleep) {
58
+ const dream = report.consolidation.dream;
59
+ const sleep = report.consolidation.sleep;
60
+ const stamp = (value) => (typeof value === 'string' ? value.slice(0, 19) : '—');
61
+ const dreamText = dream
62
+ ? `巩固 ${stamp(dream.at)} ${dream.error
63
+ ? `空转(${dream.error})`
64
+ : `${dream.status ?? 'done'},决策 ${dream.decisions}(keep ${dream.keep ?? 0})· 应用 ${dream.applied}`}`
65
+ : '巩固 还没跑过';
66
+ const sleepText = sleep
67
+ ? `睡眠 ${stamp(sleep.at)}(${sleep.consolidation ?? '—'},反思 ${sleep.reflected})`
68
+ : '睡眠 还没有记录';
69
+ lines.push(`${dreamText} · ${sleepText}`);
70
+ const today = report.consolidation?.today;
71
+ if (today && (today.archived || today.merged)) {
72
+ lines.push(`今日整理:${today.runs} 趟 · 归档 ${today.archived} 条 · 合并 ${today.merged} 条`);
73
+ } else {
74
+ lines.push('今日整理:暂无改动');
75
+ }
76
+ }
77
+ if (report.summaryLayers) {
78
+ const layers = report.summaryLayers;
79
+ const last = layers.lastEpisodeAt ? layers.lastEpisodeAt.slice(0, 16) : '—';
80
+ lines.push(`摘要:每日 ${layers.episode} 条(最近 ${last})· 合并记录 ${layers.merge} · 线 ${layers.thread}`);
81
+ }
82
+ if (report.maintain) {
83
+ const maintain = report.maintain;
84
+ const ms = Number.isFinite(maintain.ms) ? ` · ${maintain.ms}ms` : '';
85
+ lines.push(`维护:最近一趟 ${String(maintain.at).slice(0, 19)}(意图 ${maintain.intentions} · 工作记忆 ${maintain.working}${ms})`);
86
+ // A quiet pass leaves the newest audit row stale; name it separately so the
87
+ // timestamp above is not read as "nothing has run in hours".
88
+ const changed = report.maintainLastChanged;
89
+ const changedAt = changed?.passAt ?? changed?.at ?? null;
90
+ if (changedAt && changedAt !== maintain.at) {
91
+ lines.push(` 最近一次有变更:${String(changedAt).slice(0, 19)}(意图 ${changed.intentions} · 工作记忆 ${changed.working})`);
92
+ }
93
+ }
53
94
  if (report.issues.length) {
54
95
  lines.push('问题:');
55
96
  for (const issue of report.issues) lines.push(`- [${issue.severity}] ${issue.message}`);
@@ -86,6 +127,33 @@ export function createToolDefinitions(service) {
86
127
  },
87
128
  presentCall: () => ({ card: 'generic', title: '自主 tick', kind: 'other' }),
88
129
  },
130
+ {
131
+ name: 'cortex_inhibition',
132
+ description: 'Inspect or clear the retrieval-induced-forgetting marks. list shows suppressed traces with their decayed strength; clear removes the mark from one trace (id) or all of them (all: true).',
133
+ parameters: {
134
+ type: 'object',
135
+ additionalProperties: false,
136
+ required: ['action'],
137
+ properties: {
138
+ action: { type: 'string', enum: ['list', 'clear'] },
139
+ id: { type: 'string', description: '要清除的记忆 id(clear 时用)' },
140
+ all: { type: 'boolean', description: 'clear 时清全部' },
141
+ },
142
+ },
143
+ output: TEXT_OUTPUT,
144
+ isConcurrencySafe: () => false,
145
+ async execute(args = {}) {
146
+ if (args.action === 'list') {
147
+ const items = service.inhibition.list({});
148
+ if (!items.length) return { text: '没有被抑制的记忆。' };
149
+ return { text: items.slice(0, 20).map((item) => `- ${item.id} · ${item.title ?? '(untitled)'} · 强度 ${item.value}`).join('\n') };
150
+ }
151
+ if (!args.id && args.all !== true) return { text: 'clear 需要 id,或者 all: true。' };
152
+ const result = service.inhibition.clear({ id: args.id ?? null, all: args.all === true });
153
+ return { text: `已清除 ${result.cleared} 条抑制标记。` };
154
+ },
155
+ presentCall: () => ({ card: 'generic', title: '记忆抑制', kind: 'other' }),
156
+ },
89
157
  {
90
158
  name: 'cortex_digest',
91
159
  description: 'Generate a daily memory digest (counts, important traces, emotions, feedback, goals) and persist it as a digest summary.',
@@ -581,15 +649,21 @@ export function createToolDefinitions(service) {
581
649
  },
582
650
  {
583
651
  name: 'cortex_consolidate',
584
- description: 'Run LLM memory consolidation (keep/merge/archive/update/conflict) with validation and a replayable dream_runs record. Without an LLM it records a skipped run and changes nothing. Use list to inspect past runs.',
652
+ description: 'Run LLM memory consolidation (keep/merge/archive/update/conflict) with validation and a replayable dream_runs record. Without an LLM it records a skipped run and changes nothing. action=dedupe merges near-duplicate traces deterministically (no LLM; dryRun defaults to true). Use list to inspect past runs.',
585
653
  parameters: {
586
654
  type: 'object',
587
655
  additionalProperties: false,
588
656
  required: ['action'],
589
657
  properties: {
590
- action: { type: 'string', enum: ['run', 'list'] },
658
+ action: { type: 'string', enum: ['run', 'list', 'dedupe', 'preview', 'backfill'] },
591
659
  limit: { type: 'number' },
592
660
  dryRun: { type: 'boolean' },
661
+ threshold: { type: 'number', minimum: 0.5, maximum: 0.99, description: 'dedupe 相似度阈值(2-gram Jaccard),默认 0.8,超出 0.5–0.99 会被夹住' },
662
+ coverageThreshold: { type: 'number', minimum: 0.2, maximum: 0.9, description: '覆盖预演阈值(默认 0.35,超出 0.2–0.9 会被夹住)' },
663
+ windowSize: { type: 'number', minimum: 32, maximum: 60, description: '窗口补齐:每段痕迹数(32–60,默认 40)' },
664
+ maxWindows: { type: 'number', minimum: 1, maximum: 64, description: '窗口补齐:本次最多补几段(默认 8)' },
665
+ force: { type: 'boolean', description: '窗口补齐:同一窗口已存在摘要时是否重写(默认 false,幂等跳过)' },
666
+ since: { type: 'string', description: '窗口补齐:从哪个时间点续跑(传上一批的 until;不传则从最早痕迹开始)' },
593
667
  scope: { type: 'string' },
594
668
  },
595
669
  },
@@ -600,7 +674,47 @@ export function createToolDefinitions(service) {
600
674
  const runs = service.consolidation.list({ scopeId: args.scope, limit: args.limit });
601
675
  return { text: runs.length ? runs.map((run) => `- ${run.id} · ${run.at} · ${run.status} · applied ${run.applied.length} · ${run.inputDigest.slice(0, 12)}`).join('\n') : '(还没有巩固记录)' };
602
676
  }
603
- const result = await service.consolidation.run({ scopeId: args.scope, limit: args.limit ?? 30, dryRun: args.dryRun === true });
677
+ if (args.action === 'backfill') {
678
+ const report = await service.reflectBackfill({
679
+ scopeId: args.scope ?? service.settings().scope,
680
+ windowSize: args.windowSize ?? 40,
681
+ maxWindows: args.maxWindows ?? 8,
682
+ dryRun: args.dryRun !== false,
683
+ force: args.force === true,
684
+ since: args.since ?? null,
685
+ });
686
+ // The last entry can be { skipped: 'not-enough-traces' } with no window.
687
+ const windows = report.plan.filter((row) => row.since && row.until);
688
+ const first = windows[0];
689
+ const last = windows[windows.length - 1];
690
+ const span = first && last ? `${first.since.slice(0, 16)} → ${last.until.slice(0, 16)}` : '—';
691
+ const made = report.results.filter((row) => row.summaryId).length;
692
+ return { text: `窗口补齐${report.dryRun ? '预演' : ''}:每段 ${report.windowSize} 条 · 计划 ${report.planned} 段 · 跨度 ${span}${report.dryRun ? '' : ` · 新摘要 ${made}`}` };
693
+ }
694
+ if (args.action === 'preview') {
695
+ const report = service.compression.previewCoverage({ scopeId: args.scope ?? service.settings().scope, limit: args.limit ?? 5000, threshold: args.coverageThreshold ?? 0.35 });
696
+ const top = report.top.slice(0, 5).map((row) => `- ${row.r} · ${row.title}(${row.basis},命中 ${row.hit},覆盖 ${(row.rate * 100).toFixed(0)}%)`).join('\n');
697
+ return {
698
+ text: `覆盖预演(不改库):扫描 ${report.scanned} · 跳过 保护 ${report.protectedSkipped}/近访问 ${report.recentSkipped} · 摘要覆盖 ${report.summaryCovered} · 事实覆盖 ${report.factCovered}(两类都有 ${report.bothCovered})· 摘要 ${report.summaries}/事实 ${report.facts}\n分布 p50 ${report.percentiles.p50} / p90 ${report.percentiles.p90}(p90−p50 ${report.percentiles.spread})· 阈值 ${report.threshold} · 池 ${report.pool}(两类 ${report.strongPool})· 可用 ${report.usable}${report.reason ? `(${report.reason})` : ''}\n${top || '(没有可核验的覆盖候选)'}`,
699
+ };
700
+ }
701
+ if (args.action === 'dedupe') {
702
+ if (args.dryRun === false && typeof service.scopeWritable === 'function' && !service.scopeWritable(args.scope ?? service.settings().scope)) {
703
+ return { text: '未执行:该 scope 只读共享。' };
704
+ }
705
+ const result = await service.consolidation.dedupe({
706
+ scopeId: args.scope,
707
+ limit: args.limit ?? 30,
708
+ threshold: args.threshold ?? 0.8,
709
+ dryRun: args.dryRun !== false,
710
+ caller: 'tool',
711
+ });
712
+ return { text: `去重 ${result.dryRun ? '预演' : result.run.status}:${result.run.id} · 可合并组 ${result.decisions.length} · 归档 ${result.applied.length}${result.run.groupsDropped ? ` · 跳过组 ${result.run.groupsDropped}` : ''}` };
713
+ }
714
+ if (args.dryRun !== true && typeof service.scopeWritable === 'function' && !service.scopeWritable(args.scope ?? service.settings().scope)) {
715
+ return { text: '未执行:该 scope 只读共享。' };
716
+ }
717
+ const result = await service.consolidation.run({ scopeId: args.scope, limit: args.limit ?? 30, dryRun: args.dryRun === true, caller: 'tool' });
604
718
  return { text: `巩固 ${result.run.status}:${result.run.id} · 决策 ${result.decisions.length} · 应用 ${result.applied.length}${result.run.error ? ` · ${result.run.error}` : ''}` };
605
719
  },
606
720
  presentCall: () => ({ card: 'generic', title: '记忆巩固', kind: 'other' }),
@@ -618,7 +732,7 @@ export function createToolDefinitions(service) {
618
732
  isConcurrencySafe: () => true,
619
733
  async execute(args = {}) {
620
734
  if (!args.id || !String(args.id).trim()) return { text: `没有这条记忆:${args.id}` };
621
- const trace = service.get(args.id);
735
+ const trace = service.get(args.id, { revive: true });
622
736
  if (!trace) return { text: `没有这条记忆:${args.id}` };
623
737
  return {
624
738
  text: [
@@ -32,6 +32,8 @@ export function createVectorIndex({
32
32
  annOptions = {},
33
33
  externalAnnEnabled = false,
34
34
  externalAnnOptions = {},
35
+ logger = null,
36
+ queueMaxAttempts = 4,
35
37
  } = {}) {
36
38
  if (!db || !embedder) throw new Error('vector index needs db and embedder');
37
39
  const effectiveModel = model ?? embedder.model ?? 'unknown';
@@ -45,6 +47,79 @@ export function createVectorIndex({
45
47
  ? createExternalAnnClient(externalAnnOptions)
46
48
  : null;
47
49
  let annBuilt = false;
50
+ // Async embedders used to fire-and-forget: a failed call left the trace with
51
+ // no vector and nobody noticed. Keep a small persistent-in-process queue with
52
+ // backoff so a temporary outage heals itself instead of silently rotting.
53
+ const pending = new Map();
54
+ const failed = new Set();
55
+ const maxAttempts = Math.max(1, Number(queueMaxAttempts) || 4);
56
+ const isAsyncEmbedder = () => embedder.kind === 'openai-embedding' || embedder.async === true;
57
+
58
+ function enqueue(traceId, text) {
59
+ if (!traceId) return;
60
+ failed.delete(traceId);
61
+ pending.set(traceId, { text: String(text ?? ''), attempts: 0, nextAt: Date.now() });
62
+ }
63
+
64
+ async function drainQueue({ max = 20, budgetMs = 0 } = {}) {
65
+ const started = Date.now();
66
+ const now = Date.now();
67
+ const ready = [...pending.entries()]
68
+ .filter(([, task]) => task.nextAt <= now)
69
+ .slice(0, Math.max(1, Math.min(2000, Number(max) || 20)));
70
+ let ok = 0;
71
+ let gaveUp = 0;
72
+ let stoppedBy = 'done';
73
+ const budget = Math.max(0, Number(budgetMs) || 0);
74
+ for (const [traceId, task] of ready) {
75
+ if (budget > 0 && Date.now() - started >= budget) {
76
+ stoppedBy = 'time';
77
+ break;
78
+ }
79
+ try {
80
+ const vector = await embedder.embed(task.text);
81
+ // Remote embedders hand back a Float32Array, not a plain Array; the old
82
+ // Array.isArray() check rejected every real embedding, so the backfill
83
+ // queue retried forever and coverage never moved.
84
+ const length = vector && typeof vector.length === 'number' ? vector.length : -1;
85
+ if (length !== effectiveDim) throw new Error(`embedding dimension mismatch (${length} vs ${effectiveDim})`);
86
+ store(traceId, task.text, vector);
87
+ pending.delete(traceId);
88
+ ok += 1;
89
+ } catch (error) {
90
+ task.attempts += 1;
91
+ logger?.debug?.(`cortex vector attempt ${task.attempts} failed for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
92
+ if (task.attempts >= maxAttempts) {
93
+ pending.delete(traceId);
94
+ failed.add(traceId);
95
+ gaveUp += 1;
96
+ logger?.warn?.(`cortex vector failed after ${task.attempts} attempts for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
97
+ } else {
98
+ task.nextAt = now + Math.min(300_000, 1000 * (3 ** task.attempts));
99
+ // A single retryable failure must not stop the whole drain: the old code
100
+ // broke out here, so one bad item starved every other pending vector.
101
+ logger?.info?.(`cortex vector retry scheduled for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ }
104
+ }
105
+ return { ok, failed: gaveUp, pending: pending.size, elapsedMs: Date.now() - started, stoppedBy };
106
+ }
107
+
108
+ /**
109
+ * Queue every active trace that has no embedding yet. This is what makes a
110
+ * recovery possible: the index can lag behind the trace table without
111
+ * needing a full, expensive rebuild.
112
+ */
113
+ function backfillMissing({ scopeId = 'global', limit = 50 } = {}) {
114
+ const rows = db.prepare(`
115
+ SELECT t.id, t.title, t.content, t.summary FROM traces t
116
+ LEFT JOIN embeddings e ON e.trace_id = t.id
117
+ WHERE t.scope_id = ? AND t.state = 'active' AND e.trace_id IS NULL
118
+ ORDER BY t.recorded_at DESC LIMIT ?
119
+ `).all(scopeId, Math.max(1, Math.min(2000, Number(limit) || 50)));
120
+ for (const row of rows) enqueue(row.id, `${row.title ?? ''} ${row.content ?? ''} ${row.summary ?? ''}`);
121
+ return { queued: rows.length, pending: pending.size };
122
+ }
48
123
 
49
124
  function ensureAnn() {
50
125
  if (!ann || annBuilt) return;
@@ -55,11 +130,11 @@ export function createVectorIndex({
55
130
 
56
131
  function upsert(traceId, text) {
57
132
  if (!traceId) return null;
58
- // Remote providers are async. A write must not block on the network: kick
59
- // off the embedding and let it land later. Callers that need completion
60
- // use upsertAsync().
61
- if (embedder.kind === 'openai-embedding' || embedder.async === true) {
62
- upsertAsync(traceId, text).catch(() => null);
133
+ // Remote providers are async. A write must not block on the network: queue
134
+ // it, and let the scheduler drain the queue with retries. Callers that need
135
+ // completion use upsertAsync().
136
+ if (isAsyncEmbedder()) {
137
+ enqueue(traceId, text);
63
138
  return { traceId, pending: true };
64
139
  }
65
140
  const vector = embedder.embed(String(text ?? ''));
@@ -100,7 +175,8 @@ export function createVectorIndex({
100
175
  model: effectiveModel,
101
176
  dim: effectiveDim,
102
177
  count: Number(row?.c ?? 0),
103
- async: embedder.kind === 'openai-embedding' || embedder.async === true,
178
+ async: isAsyncEmbedder(),
179
+ queue: { pending: pending.size, failed: failed.size, maxAttempts },
104
180
  ann: ann ? { enabled: true, engine: annEngine === 'nsw' ? 'nsw' : 'hnsw', size: ann.size(), min: annMinCount, built: annBuilt } : { enabled: false },
105
181
  externalAnn: externalAnn ? { enabled: true, endpoint: externalAnn.endpoint } : { enabled: false },
106
182
  };
@@ -205,5 +281,18 @@ export function createVectorIndex({
205
281
  return { rebuilt, ...status() };
206
282
  }
207
283
 
208
- return { upsert, upsertAsync, remove, search, searchAsync, status, rebuild, rebuildAsync, model: effectiveModel, dim: effectiveDim };
284
+ return {
285
+ upsert,
286
+ upsertAsync,
287
+ remove,
288
+ search,
289
+ searchAsync,
290
+ status,
291
+ rebuild,
292
+ rebuildAsync,
293
+ backfillMissing,
294
+ drainQueue,
295
+ model: effectiveModel,
296
+ dim: effectiveDim,
297
+ };
209
298
  }
@@ -1,128 +0,0 @@
1
- /**
2
- * Shared helpers for the integration suite.
3
- *
4
- * The tests are deliberately black-box: every helper here only creates real
5
- * cortex instances in throwaway directories, drives real repository/engine
6
- * code, and cleans up afterwards. Nothing mocks the module under test.
7
- */
8
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import { Readable } from 'node:stream';
12
- import { createCortex } from '../../src/service/cortex.js';
13
- import { API_BASE } from '../../src/api/routes.js';
14
-
15
- export const DAY_MS = 86_400_000;
16
- /** Fixed reference instant: 2026-11-11T10:00:00+08:00. */
17
- export const BASE_MS = Date.parse('2026-11-11T10:00:00+08:00');
18
-
19
- /**
20
- * Create a cortex backed by a fresh temporary directory.
21
- * Returns the directory (for cleanup) and the service.
22
- */
23
- export function makeCortex(config = {}) {
24
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-integration-'));
25
- const dataRoot = config.dataRoot ?? path.join(dir, 'data');
26
- const dbFile = config.dbFile ?? path.join(dataRoot, 'cortex.sqlite');
27
- const cortex = createCortex({ config: { ...config, dataRoot, dbFile } });
28
- return { dir, cortex };
29
- }
30
-
31
- /**
32
- * Close every cortex first, then delete every temporary directory. Safe to
33
- * call from a finally block even when the test failed halfway through setup.
34
- */
35
- export function cleanup(...contexts) {
36
- for (const context of contexts) {
37
- try {
38
- context?.cortex?.close();
39
- } catch {
40
- /* closing is best-effort, cleanup must not mask the real assertion */
41
- }
42
- if (context?.dir) rmSync(context.dir, { recursive: true, force: true });
43
- }
44
- }
45
-
46
- /** Request stream shaped the way the API handler expects node:http objects. */
47
- export function apiRequest({
48
- method = 'GET',
49
- route = '/ping',
50
- body = null,
51
- headers = {},
52
- remoteAddress = '127.0.0.1',
53
- host = '127.0.0.1:7430',
54
- origin = 'http://127.0.0.1:7430',
55
- site = 'same-origin',
56
- url = null,
57
- } = {}) {
58
- const stream = Readable.from(body === null ? [] : [Buffer.from(JSON.stringify(body), 'utf8')]);
59
- stream.method = method;
60
- stream.url = url ?? `${API_BASE}${route}`;
61
- const merged = {
62
- host,
63
- origin,
64
- 'sec-fetch-site': site,
65
- ...(body === null ? {} : { 'content-type': 'application/json' }),
66
- ...headers,
67
- };
68
- for (const [key, value] of Object.entries(merged)) {
69
- if (value === undefined) delete merged[key];
70
- }
71
- stream.headers = merged;
72
- stream.socket = { remoteAddress };
73
- return stream;
74
- }
75
-
76
- /** Minimal ServerResponse recorder: enough for the route handler. */
77
- export function apiResponse() {
78
- return {
79
- statusCode: 0,
80
- headers: null,
81
- body: '',
82
- writeHead(code, headers) {
83
- this.statusCode = code;
84
- this.headers = headers ?? null;
85
- },
86
- end(chunk) {
87
- if (chunk != null) this.body += String(chunk);
88
- },
89
- };
90
- }
91
-
92
- export async function invokeApi(handler, options = {}) {
93
- const response = apiResponse();
94
- await handler(apiRequest(options), response);
95
- return { status: response.statusCode, headers: response.headers, json: JSON.parse(response.body || '{}') };
96
- }
97
-
98
- /**
99
- * Split an exported MEMORY.md mirror into its per-memory frontmatter blocks.
100
- *
101
- * The exporter writes one multi-entry document; the importer expects one
102
- * memory per file. This helper converts the mirror into the vault shape the
103
- * importer documents, using the same textual boundaries the exporter emits.
104
- */
105
- export function splitMirrorEntries(markdown) {
106
- const entries = [];
107
- const pattern = /^---\n([\s\S]*?)\n---\n\n([\s\S]*?)(?=\n---\n|$)/gm;
108
- for (const match of String(markdown ?? '').matchAll(pattern)) {
109
- entries.push({ frontmatter: match[1], body: match[2].trim() });
110
- }
111
- return entries;
112
- }
113
-
114
- /** Write one frontmatter memory file into a vault directory. */
115
- export function writeVaultEntry(dir, name, { frontmatter, body }) {
116
- mkdirSync(dir, { recursive: true });
117
- const file = path.join(dir, name);
118
- writeFileSync(file, `---\n${frontmatter}\n---\n\n${body}\n`, 'utf8');
119
- return file;
120
- }
121
-
122
- /** Write a raw file, mainly for hand-authored vault fixtures. */
123
- export function writeRaw(dir, name, content) {
124
- mkdirSync(dir, { recursive: true });
125
- const file = path.join(dir, name);
126
- writeFileSync(file, content, 'utf8');
127
- return file;
128
- }