@modusensus/dsh-mneme 0.8.2 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -633
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4362
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -500
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -513
  22. package/lib/inject.js +299 -253
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -308
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -260
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -0
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2071
  42. package/lib/settings.js +430 -419
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -500
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -513
  75. package/src/inject.js +299 -253
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -308
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -260
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -0
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2071
  95. package/src/settings.js +430 -419
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1481
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -0
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -229
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -0
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
package/src/service.js CHANGED
@@ -1,2071 +1,2171 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { TYPE_FILE } from "./mirror.js";
3
- import { updatedAtBounds } from "./store.js";
4
- import { normalizeExplicitScope, scopeKeyOf } from "./scope.js";
5
- import { STR, langOf } from "./lang.js";
6
- import { computeHeat } from "./heat.js";
7
- import { evaluateMemoryQuality } from "./quality-filter.js";
8
- import { applyDecisions } from "./dream/decisions.js";
9
- import { createBM25Index } from "./search/bm25.js";
10
- import { adaptiveThreshold } from "./search/adaptive.js";
11
-
12
- const INJECT_TYPES = new Set(["preference", "project", "decision", "summary", "rejected_solution", "pitfall", "constraint"]);
13
-
14
- // 编码记忆类型(codingRetrospect):rejected_solution / pitfall / constraint
15
- // 只在编码任务时注入(防噪声污染其他业务),且编码场景下按 codingBoostFactor
16
- // 加权排序提前。
17
- const CODING_MEMORY_TYPES = new Set(["rejected_solution", "pitfall", "constraint"]);
18
-
19
- /**
20
- * 判断一段文本是否编码类任务(关键词匹配,codingRetrospect 读取侧门控)。
21
- * 纯函数,无副作用,便于单测。
22
- */
23
- export function isCodingTask(text, keywords = []) {
24
- const t = String(text ?? "").toLowerCase();
25
- return keywords.some((kw) => t.includes(String(kw).toLowerCase()));
26
- }
27
-
28
- // Epistemic trust weights (v0.4.5): when config.trustEpistemicWeighting is on,
29
- // each recall candidate's existing score is multiplied by the weight of its
30
- // epistemic_status before ranking — measured facts outrank guesses. Missing /
31
- // unknown statuses are unscaled (×1). Off by default, so nothing changes.
32
- const EPISTEMIC_WEIGHTS = { observation: 1.0, inferred: 0.85, subjective: 0.7 };
33
-
34
- // Bug5: content version history cap (FIFO — the newest 20 versions are kept,
35
- // older ones dropped). Entries are {content, source, updated_at}; source marks
36
- // how the version was superseded (auto_merge | human_override | overwrite).
37
- const CONTENT_HISTORY_MAX = 20;
38
-
39
- // Issue #135 附属发现 2:质量过滤器写下的系统信号标签(「为什么被降权/归档」的
40
- // 唯一审计线索)。更新路径整组替换 tags 会把它们抹掉——更新时按此清单并集保留。
41
- // 清单必须与 quality-filter.js 的写入端对齐(6 个,含 type 自指的 self_referential)。
42
- const SIGNAL_TAGS = ["low_quality", "duplicate", "meta", "repetitive", "short_content", "self_referential"];
43
-
44
- // scopeKeyOf 已上提到 ./scope.js(v0.8.1,issue #170 第 2 步):与 sleep 的跨
45
- // scope 配对共用同一把比较钥匙,避免两处定义漂移。
46
-
47
- // v0.8.0 A2(issue #17)scope 检索加权系数:两维都无法确立 foreign 的候选
48
- // (命中行、未标注行、当前侧维度解析不到的行)→ 加成;只有确立了 foreign
49
- // (记忆带标注 + 当前维度可解析 + 值不等)→ 降权但保留可见(硬过滤是 A3
50
- // strictScope)。即未标注行与命中行同列、不吃惩罚,但注意它们吃的是 BOOST
51
- // 而非 ×1 中性。系数是模块常量而非配置项:A2 只定性行为,数值要等线上检索
52
- // 质量反馈再调(加配置面=提前优化)。
53
- const SCOPE_MATCH_BOOST = 1.25;
54
- const SCOPE_FOREIGN_PENALTY = 0.5;
55
-
56
- /**
57
- * 单条候选的 scope 乘数。匹配语义与去重键一致(scopeKeyOf):记忆侧未标注视同
58
- * 该维度命中(全局记忆对谁都可见);当前会话侧某维度解析不到则该维度不参与
59
- * 比较(无法比较 ≠ 不匹配)。
60
- */
61
- function scopeMultiplier(m, current) {
62
- const agentForeign = scopeKeyOf(m.agent_scope) !== null
63
- && current.agent_scope !== null
64
- && scopeKeyOf(m.agent_scope) !== current.agent_scope;
65
- const workspaceForeign = scopeKeyOf(m.workspace_scope) !== null
66
- && current.workspace_scope !== null
67
- && scopeKeyOf(m.workspace_scope) !== current.workspace_scope;
68
- return (agentForeign || workspaceForeign) ? SCOPE_FOREIGN_PENALTY : SCOPE_MATCH_BOOST;
69
- }
70
-
71
- /**
72
- * v0.8.0 A2:occurred_at 后置过滤谓词(搜索融合池用)。行侧取
73
- * COALESCE(occurred_at, created_at)——与 store.list 的 SQL 过滤同口径,未标注
74
- * 行回退创建时间;时间戳损坏的行保留(宁可放宽也不误杀,同 summarize inWindow)。
75
- */
76
- function inOccurredBounds(m, bounds) {
77
- const t = Date.parse(String(m.occurred_at ?? m.created_at ?? ""));
78
- if (!Number.isFinite(t)) return true;
79
- if (bounds.from && t < Date.parse(bounds.from)) return false;
80
- if (bounds.to && t > Date.parse(bounds.to)) return false;
81
- return true;
82
- }
83
-
84
- /**
85
- * v0.8.0 A3(issue #17)strictScope 可见性谓词:issue 的四象限可见性公式
86
- * (agent 不对称可见性)——记忆对当前会话可见 ⇔ (agent 维:未标注 或 命中当前
87
- * agent) AND (workspace 维:未标注 或 命中当前 workspace)。NULL=未标注=全局;
88
- * 当前会话某维度解析不到时,该维度带标注的记忆一律不可见(fail-closed:身份
89
- * 不明的会话只见全局,不冒认)。sensitivity 是标签不参与可见性判定(其语义
90
- * 留给后续批次)。store.list 的 SQL 过滤与此谓词同口径(见 store.js visibility)。
91
- */
92
- function isVisibleInScope(m, current) {
93
- // v0.8.1 第 3 步(issue #170 4.3,作者已确认):硬过滤只认显式声明。某维
94
- // 仅当「该维有标注且来源为 explicit」才构成硬墙;auto(含 v0.8.0 存量的
95
- // NULL 来源行)只吃 A2 软加权(foreign ×0.5 保留可见),不进硬过滤。
96
- // 显式全局(值 NULL + source explicit)与未标注同形,天然恒可见。
97
- if (m.agent_scope_source === "explicit") {
98
- const agent = scopeKeyOf(m.agent_scope);
99
- if (agent !== null && (current.agent_scope === null || agent !== current.agent_scope)) return false;
100
- }
101
- if (m.workspace_scope_source === "explicit") {
102
- const ws = scopeKeyOf(m.workspace_scope);
103
- if (ws !== null && (current.workspace_scope === null || ws !== current.workspace_scope)) return false;
104
- }
105
- return true;
106
- }
107
-
108
- /** Prepend the previous content to a memory's content_history (FIFO capped). */
109
- function pushContentHistory(existing, source) {
110
- const history = Array.isArray(existing?.content_history) ? existing.content_history : [];
111
- return [
112
- { content: existing?.content ?? "", source, updated_at: new Date().toISOString() },
113
- ...history
114
- ].slice(0, CONTENT_HISTORY_MAX);
115
- }
116
-
117
- /** Bug5: same-title merge appends the new content under a timestamped `---`
118
- * separator instead of overwriting, so a re-noted memory never loses history.
119
- * The `---` line is compatible with the mirror's readHumanEdits (which strips
120
- * only the LAST structural `---` when parsing the human-editable file). */
121
- function appendContent(oldContent, newContent) {
122
- const ts = new Date().toISOString();
123
- return `${oldContent}\n\n---\n[${ts}] ${newContent}`;
124
- }
125
-
126
- /**
127
- * Standard retrieval-quality metrics over the ordered candidate ids actually
128
- * returned vs the ids the evaluator marked relevant (方案 B). Pure + total, so
129
- * callers (and tests) get deterministic numbers without touching a store:
130
- * precision = |relevant ∩ retrieved| / |retrieved|
131
- * recall = |relevant ∩ retrieved| / |expected|
132
- * mrr = 1 / rank of the first relevant doc (0 when none retrieved)
133
- * hit_count is the raw intersection size. Values are rounded to 4 decimals so
134
- * repeated divisions (e.g. 1/3) never surface binary-float noise.
135
- */
136
- export function computeRetrievalMetrics(actualIds, expectedIds) {
137
- const expected = new Set(Array.isArray(expectedIds) ? expectedIds : []);
138
- const actual = Array.isArray(actualIds) ? actualIds : [];
139
- const relevant = actual.filter((id) => expected.has(id)).length;
140
- const round4 = (x) => Math.round(x * 10000) / 10000;
141
- let mrr = 0;
142
- for (let i = 0; i < actual.length; i++) {
143
- if (expected.has(actual[i])) { mrr = 1 / (i + 1); break; }
144
- }
145
- return {
146
- precision: round4(actual.length ? relevant / actual.length : 0),
147
- recall: round4(expected.size ? relevant / expected.size : 0),
148
- mrr: round4(mrr),
149
- hit_count: relevant
150
- };
151
- }
152
-
153
- export function createService({ store, mirror, config, onWrite, logger }) {
154
- const language = langOf(config);
155
- // Optional dream scheduler hook, installed via setDreamHook after creation
156
- // (the scheduler holds a reference back to the service, so it cannot be
157
- // passed in the constructor). Fired on the same write events as onWrite.
158
- let dreamHook = null;
159
-
160
- // Optional sleep scheduler hook (v0.4.0), installed via setSleepHook after
161
- // creation. Fired on the same write events as onWrite: it tells the sleep
162
- // scheduler the store just changed so the idle-detection clock resets.
163
- let sleepHook = null;
164
-
165
- // Optional vector embedder, installed via setEmbedder after creation. After
166
- // any content write it fire-and-forgets a re-embed of the row so vector
167
- // search stays in sync; failures are swallowed inside the embedder.
168
- let embedder = null;
169
-
170
- // Optional entity extractor, installed via setEntityExtractor after creation
171
- // (index.js injects it so the service never depends on the LLM directly).
172
- // After a new memory is saved it fire-and-forgets an extraction pass for the
173
- // entity gene (v0.3.0); failures are swallowed so a broken extraction never
174
- // surfaces as a write failure. Extraction only runs when
175
- // config.entityExtractionEnabled is true.
176
- let entityExtractor = null;
177
- let vectorIndex = null;
178
- let reranker = null;
179
-
180
- // Optional recall recorder, installed via setRecallRecorder after creation.
181
- // When searchMemories is called with recordRecall=true it receives the
182
- // actual merged recall scene (candidates + scores + source + threshold) so
183
- // the retrieval layer can be audited/replayed — the sibling of the dream
184
- // judgment-layer audit trail (dream_runs).
185
- let recallRecorder = null;
186
-
187
- // Bug4: semantic recall cache for the injection path. The system-prompt
188
- // interpolator renders context synchronously, so injectCandidates cannot
189
- // fire a fresh async embed. The most recent searchMemories recall is cached
190
- // here (query + ordered candidates) and reused when the injection query
191
- // matches, giving semantic-first injection without breaking the sync render.
192
- let lastSemanticRecall = null;
193
-
194
- // Transaction nesting depth. Inside service.transaction the per-mutation side
195
- // effects (mirror render, write notify, re-embed) are deferred so a ROLLBACK
196
- // never leaves the mirror file diverged from the database; transaction()
197
- // replays them exactly once against the committed state.
198
- let txDepth = 0;
199
-
200
- // Serial task queue (sleep v0.4.0). Long-running background passes — dream
201
- // consolidation, sleep cycles — must never overlap: two sleep runs racing
202
- // would double-demote or double-mint patterns. enqueue chains the task onto
203
- // a promise tail so N callers can queue work that runs strictly one at a
204
- // time. A task that rejects doesn't poison the queue (the tail swallows the
205
- // rejection) but the rejection still propagates to that caller.
206
- let queueTail = Promise.resolve();
207
- function enqueue(fn) {
208
- const next = queueTail.then(fn, fn);
209
- queueTail = next.catch(() => {});
210
- return next;
211
- }
212
-
213
- // issue #6 (part 2): startup race defense. A local embedder (LocalEmbedder /
214
- // Ollama) exposes an async init(), so between `setEmbedder` and init()
215
- // resolving there is a window where embedSingle would throw "not initialized"
216
- // and the re-embed would be silently dropped. When the embedder carries a
217
- // `ready` flag we queue writes in embedPending until init sets ready=true,
218
- // then flush them through the embedder's real interface. Embedders without a
219
- // `ready` flag (legacy OpenAI, instantly usable) keep their old behavior.
220
- let embedPending = [];
221
- let embedReadyTimer = null;
222
- const EMBED_PENDING_MAX = 100; // bound the queue; drop oldest beyond this
223
- const EMBED_READY_POLL_MS = 100;
224
- const EMBED_READY_POLL_LIMIT = 30; // ~3s ceiling; never poll forever
225
-
226
- /** Flush the queued re-embeds once the embedder is ready. Fail-safe. */
227
- function flushEmbedPending() {
228
- if (!embedder || embedPending.length === 0) return;
229
- const batch = embedPending.splice(0, embedPending.length);
230
- for (const memory of batch) {
231
- try {
232
- if (!memory?.id) continue;
233
- if (typeof embedder.schedule === "function") {
234
- embedder.schedule(memory);
235
- } else if (typeof embedder.embedSingle === "function") {
236
- const text = [memory.title, memory.content].filter(Boolean).join("\n");
237
- if (!text) continue;
238
- embedder
239
- .embedSingle(text)
240
- .then((vec) => {
241
- if (Array.isArray(vec) && vec.length) {
242
- store.setEmbedding(memory.id, vec);
243
- }
244
- })
245
- .catch((err) => {
246
- logger?.warn?.("flushEmbedPending embedSingle failed:", err);
247
- });
248
- }
249
- } catch (err) {
250
- logger?.warn?.("flushEmbedPending failed:", err);
251
- }
252
- }
253
- }
254
-
255
- function stopEmbedReadyPolling() {
256
- if (embedReadyTimer) {
257
- clearInterval(embedReadyTimer);
258
- embedReadyTimer = null;
259
- }
260
- }
261
-
262
- function scheduleEmbed(memory) {
263
- try {
264
- if (txDepth > 0) return; // deferred to the transaction's commit
265
- if (!embedder || !memory?.id) return;
266
-
267
- // Readiness gate: embedder exposes `ready` (async init) and is not ready
268
- // yet — queue instead of firing embedSingle into a half-built extractor.
269
- const hasReady = "ready" in embedder;
270
- if (hasReady && embedder.ready !== true) {
271
- if (embedPending.length >= EMBED_PENDING_MAX) embedPending.shift();
272
- embedPending.push(memory);
273
- return;
274
- }
275
-
276
- if (typeof embedder.schedule === "function") {
277
- embedder.schedule(memory);
278
- return;
279
- }
280
-
281
- if (typeof embedder.embedSingle === "function") {
282
- const text = [memory.title, memory.content].filter(Boolean).join("\n");
283
- if (!text) return;
284
-
285
- embedder
286
- .embedSingle(text)
287
- .then((vec) => {
288
- if (Array.isArray(vec) && vec.length) {
289
- store.setEmbedding(memory.id, vec);
290
- }
291
- })
292
- .catch((err) => {
293
- logger?.warn?.("scheduleEmbed embedSingle failed:", err);
294
- });
295
- }
296
- } catch (err) {
297
- logger?.warn?.("scheduleEmbed failed:", err);
298
- }
299
- }
300
-
301
- /**
302
- * Fire-and-forget entity extraction for a freshly saved memory (entity gene
303
- * v0.3.0). Opt-in via config.entityExtractionEnabled; the extractor is
304
- * injected as a hook so the service never needs a direct LLM reference.
305
- * The hook itself is expected to resolve to { ok:boolean } and never throw;
306
- * a thrown rejection is swallowed here as a final fail-safe.
307
- */
308
- function scheduleEntityExtraction(memory) {
309
- if (txDepth > 0) return; // deferred to the transaction's commit
310
- if (!config.entityExtractionEnabled || !entityExtractor) return;
311
- try {
312
- entityExtractor(memory).catch((err) => {
313
- logger?.warn?.("entity extraction failed:", err);
314
- });
315
- } catch (err) {
316
- logger?.warn?.("entity extraction failed:", err);
317
- }
318
- }
319
-
320
- /**
321
- * Cross-encoder rerank over a candidate list (best effort). Reranker
322
- * failures degrade to the original candidate order — reranking is an
323
- * accuracy upgrade, never a correctness gate.
324
- */
325
- async function rerankCandidates(query, candidates, topK) {
326
- if (!reranker || !candidates.length) return candidates.slice(0, topK);
327
- try {
328
- const scored = await reranker.rerank(query, candidates.map((c) => ({ id: c.id, title: c.title, content: c.content })));
329
- if (!Array.isArray(scored)) return candidates.slice(0, topK);
330
- const byId = new Map(candidates.map((c) => [c.id, c]));
331
- const out = [];
332
- for (const s of scored) {
333
- const c = byId.get(s.id);
334
- if (c) { out.push({ ...c, score: s.score, source: "rerank" }); if (out.length >= topK) break; }
335
- }
336
- return out.length ? out : candidates.slice(0, topK);
337
- } catch {
338
- return candidates.slice(0, topK);
339
- }
340
- }
341
-
342
- /**
343
- * Search for memories attached to a named entity (v0.3.0 Phase 3).
344
- * 合并优先级:entity_attrs.memory_id 精确关联 = 1.0 > 关键词提及 = 0.7;
345
- * attr 命中不覆盖,keyword 只补充召回,最后按 _score 降序取 topK。
346
- * @param {string} entityName
347
- * @param {object} [options]
348
- * @param {number} [options.topK=20]
349
- * @returns {any[]}
350
- */
351
- function searchByEntity(entityName, { topK = 20 } = {}) {
352
- const entity = store.findEntityByName(entityName);
353
- if (!entity) return [];
354
- const attrs = store.getCurrentAttrs(entity.id);
355
- const memoryIds = [...new Set(attrs.map((a) => a.memory_id).filter(Boolean))];
356
- const attrHits = memoryIds.map((id) => store.getById(id)).filter(Boolean);
357
- const keywordHits = store.search(entityName, { limit: topK });
358
- const merged = new Map();
359
- for (const mem of attrHits) merged.set(mem.id, { ...mem, _source: "entity_attr", _score: 1.0 });
360
- for (const mem of keywordHits) {
361
- if (!merged.has(mem.id)) merged.set(mem.id, { ...mem, _source: "keyword", _score: 0.7 });
362
- }
363
- const hits = Array.from(merged.values()).sort((a, b) => b._score - a._score).slice(0, topK);
364
- touchRecalled(hits);
365
- return hits;
366
- }
367
-
368
- /**
369
- * Search for memories by attribute key/value (v0.3.0 Phase 3).
370
- * value 为空时由 store.findMemoriesByAttr 返回该 key 的全部有效记忆。
371
- * @param {string} key
372
- * @param {string | undefined} value
373
- * @param {object} [options]
374
- * @param {number} [options.topK=20]
375
- * @returns {any[]}
376
- */
377
- function searchByAttr(key, value, { topK = 20 } = {}) {
378
- if (!key) return [];
379
- // value 可能为 undefined(attr:key 无 = 值):归一为空串后交给
380
- // store.findMemoriesByAttr —— 空 value 契约 = 返回该 attr_key 的全部
381
- // 当前有效记忆(v0.3.0,store.js 已实现)。
382
- const rows = store.findMemoriesByAttr(key, value ?? "");
383
- const hits = rows.slice(0, topK);
384
- touchRecalled(hits);
385
- return hits;
386
- }
387
-
388
- /**
389
- * Semantic-aware memory search: keyword recall (store.search) plus optional
390
- * vector recall + rerank. mode:
391
- * auto (default) keyword first, vector fills remaining slots (legacy)
392
- * hybrid vector first, keyword fills remaining slots
393
- * vector vector only, falls back to keyword when unavailable
394
- * keyword text only, never touches the embedder
395
- * useRerank runs the cross-encoder over the merged list when a reranker is
396
- * installed; results carry an extra `score` when reranked.
397
- */
398
- // Weighted blend factor for hybrid search; exposed so callers can tune it.
399
- const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
400
-
401
- // Cosine over two plain arrays (shared by the search-time semantic dedup).
402
- function cosineVec(a, b) {
403
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
404
- let dot = 0, na = 0, nb = 0;
405
- for (let i = 0; i < a.length; i++) {
406
- dot += a[i] * b[i];
407
- na += a[i] * a[i];
408
- nb += b[i] * b[i];
409
- }
410
- if (na === 0 || nb === 0) return 0;
411
- return dot / (Math.sqrt(na) * Math.sqrt(nb));
412
- }
413
-
414
- /**
415
- * BM25 third recall path (v0.5.0 1.1). Scores the query tokens against the
416
- * live non-archived rows and returns the top `limit` hits with scores
417
- * normalized to [0,1]. Failures degrade to [] — BM25 is a recall booster,
418
- * never a correctness gate.
419
- */
420
- function bm25Recall(q, limit) {
421
- if (config?.bm25SearchEnabled === false) return [];
422
- try {
423
- const docs = store.list({ limit: 500, includeForgotten: false }).filter((m) => !m.archived);
424
- if (!docs.length) return [];
425
- return createBM25Index(docs).search(q, { limit });
426
- } catch {
427
- return [];
428
- }
429
- }
430
-
431
- /**
432
- * Search-time semantic dedup (v0.5.0 2.3): greedy pass dropping candidates
433
- * whose embedding similarity to an already-kept row exceeds the threshold.
434
- * Rows without a stored embedding are always kept (no signal = no drop).
435
- */
436
- function semanticDeduplicate(candidates) {
437
- // Opt-in aggressive mode (default off): collapsing near-duplicates can
438
- // drop legitimately distinct rows on small embedding models, so it ships
439
- // behind searchSemanticDedup=true.
440
- if (config?.searchSemanticDedup !== true || candidates.length < 2) return candidates;
441
- const threshold = config?.searchSemanticDedupThreshold ?? 0.95;
442
- try {
443
- const vecs = store.getEmbeddings(candidates.map((c) => c.id));
444
- if (vecs.size < 2) return candidates;
445
- const kept = [];
446
- for (const c of candidates) {
447
- const v = vecs.get(c.id);
448
- if (!v) { kept.push(c); continue; }
449
- const dup = kept.some((k) => {
450
- const kv = vecs.get(k.id);
451
- return kv && cosineVec(v, kv) > threshold;
452
- });
453
- if (!dup) kept.push(c);
454
- }
455
- return kept;
456
- } catch {
457
- return candidates;
458
- }
459
- }
460
-
461
- /**
462
- * Give a keyword-hit row a relevance score in [0,1]: title hits score
463
- * higher than content hits, then scaled by importance (1-5). This lets
464
- * keyword results participate in weighted hybrid blends.
465
- */
466
- function scoreKeyword(row, q) {
467
- const ql = q.toLowerCase();
468
- const title = (row.title ?? "").toLowerCase();
469
- const content = (row.content ?? "").toLowerCase();
470
- const titleHit = title.includes(ql);
471
- const base = titleHit ? 1 : content.includes(ql) ? 0.6 : 0.3;
472
- return base * (0.5 + (row.importance ?? 3) / 10);
473
- }
474
-
475
- /**
476
- * Recall touch (v0.4.0 sleep; v0.7.0 heat gating): any memory surfaced by
477
- * recall or auto-injection gets its last_accessed_at bumped, so the "unrecalled
478
- * N days → demote/archive" tiering counts real access — and the heat clock
479
- * resets (heat ref = last_accessed_at). Best-effort and gated on
480
- * config.heatEnabled — when heat is off this is a complete no-op (no writes
481
- * on the hot recall path). A touch failure must never break search/inject.
482
- */
483
- function touchRecalled(memories) {
484
- if (config?.heatEnabled === false || !Array.isArray(memories) || memories.length === 0) return;
485
- for (const m of memories) {
486
- if (!m?.id) continue;
487
- try {
488
- store.touchLastAccess(m.id);
489
- } catch { /* touch is best effort */ }
490
- }
491
- }
492
-
493
- /**
494
- * Recall fusion (plan #1). Turns the three ranked signal lists (keyword,
495
- * vector, BM25) into a single merged list. Three recipes, selected by
496
- * config.recallFusion:
497
- * - blend (default): legacy behavior — weighted sum for vector/hybrid, union
498
- * backfill for auto. Byte-identical to pre-fusion code, so enabling the
499
- * config never regresses anybody.
500
- * - rrf: Reciprocal Rank Fusion — Σ 1/(k + rank + 1) over each list a row
501
- * appears in. Rank-based, so the unit mismatch (raw cosine vs keyword
502
- * score vs normalized IDF) is irrelevant.
503
- * - minmax: min-max normalize each source list's scores to [0,1] then take
504
- * the weighted sum — a scale-aware version of `blend`.
505
- * Returns { merged, signals }, where signals is Map<id, {keyword, vector,
506
- * bm25}> so searchMemories can decorate rows when signalTransparency is on.
507
- */
508
- function fuseRecall({ keyword, vector, bm25, lim, mode, wv, wk, wb }) {
509
- const recipe = config?.recallFusion ?? "blend";
510
-
511
- // Per-source scores are recorded for every recipe so signalTransparency
512
- // works regardless of how the ranking was produced.
513
- const signals = new Map();
514
- const addSig = (id, field, sc) => {
515
- const cur = signals.get(id) ?? {};
516
- cur[field] = sc;
517
- signals.set(id, cur);
518
- };
519
- for (const m of keyword) addSig(m.id, "keyword", m.score ?? 0);
520
- for (const m of vector) addSig(m.id, "vector", m.score ?? 0);
521
- for (const m of bm25) addSig(m.id, "bm25", m.score ?? 0);
522
-
523
- const vectorIds = new Set(vector.map((m) => m.id));
524
- const keywordIds = new Set(keyword.map((m) => m.id));
525
-
526
- // Mode contract (aligns rrf/minmax with blend): keyword-only searches must
527
- // stay keyword-only regardless of recipe, so enabling an opt-in recipe can
528
- // never pull vector/BM25 rows into a mode="keyword" request. This mirrors
529
- // the blend branch's `mode === "keyword"` short-circuit (byte-for-byte).
530
- if (mode === "keyword") {
531
- return { merged: keyword.slice(0, lim), signals };
532
- }
533
-
534
- let merged;
535
- if (recipe === "rrf") {
536
- // Rank-based: only the position of a row inside each surviving source
537
- // list matters, so no cross-signal scale calibration is needed.
538
- const k = 60; // standard RRF constant (plan #1 documents k=60)
539
- const rows = new Map();
540
- const addList = (list) => list.forEach((m, idx) => {
541
- const s = 1 / (k + idx + 1);
542
- const cur = rows.get(m.id);
543
- if (cur) cur.score += s;
544
- else rows.set(m.id, { ...m, score: s });
545
- });
546
- addList(keyword);
547
- addList(vector);
548
- addList(bm25);
549
- merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
550
- } else if (recipe === "minmax") {
551
- // Scale-aware weighted sum: each source list is min-max normalized to
552
- // [0,1] before blending, so raw cosine and keyword score live on the
553
- // same footing.
554
- const norm = (list) => {
555
- if (!list.length) return new Map();
556
- let min = Infinity, max = -Infinity;
557
- for (const m of list) { const s = m.score ?? 0; if (s < min) min = s; if (s > max) max = s; }
558
- const range = max - min;
559
- const out = new Map();
560
- for (const m of list) out.set(m.id, range > 0 ? ((m.score ?? 0) - min) / range : 0.5);
561
- return out;
562
- };
563
- const kw = norm(keyword), ve = norm(vector), bm = norm(bm25);
564
- const rows = new Map();
565
- const seed = (m) => { if (!rows.has(m.id)) rows.set(m.id, { ...m, score: 0 }); };
566
- for (const m of keyword) seed(m);
567
- for (const m of vector) seed(m);
568
- for (const m of bm25) seed(m);
569
- for (const [id, row] of rows) {
570
- const k = kw.get(id) ?? 0;
571
- const v = ve.get(id) ?? 0;
572
- const b = bm.get(id) ?? 0;
573
- row.score = v * wv + k * wk + b * wb;
574
- }
575
- merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
576
- } else {
577
- // blend — the pre-existing per-mode behavior, extracted verbatim.
578
- if (mode === "keyword") {
579
- merged = keyword;
580
- } else if (mode === "vector" || mode === "hybrid") {
581
- const byId = new Map();
582
- for (const m of vector) {
583
- const rec = byId.get(m.id);
584
- byId.set(m.id, rec ? { ...rec, score: Math.max(rec.score ?? 0, m.score ?? 0) } : m);
585
- }
586
- for (const m of keyword) {
587
- const rec = byId.get(m.id);
588
- if (rec) {
589
- byId.set(m.id, { ...rec, score: (rec.score ?? 0) * wv + (m.score ?? 0) * wk });
590
- } else {
591
- byId.set(m.id, m);
592
- }
593
- }
594
- for (const m of bm25) {
595
- const rec = byId.get(m.id);
596
- if (rec) {
597
- if (keywordIds.has(m.id)) continue;
598
- byId.set(m.id, { ...rec, score: (rec.score ?? 0) + wb * (m.score ?? 0) });
599
- } else {
600
- byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
601
- }
602
- }
603
- const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
604
- merged = ranked.slice(0, lim);
605
- if (merged.length < lim && !merged.length) {
606
- merged = keyword.slice(0, lim);
607
- }
608
- } else {
609
- // auto: keyword leads, vector + BM25 fill remaining slots.
610
- merged = keyword.slice(0, lim);
611
- const seen = new Set(merged.map((m) => m.id));
612
- for (const m of vector) {
613
- if (merged.length >= lim) break;
614
- if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
615
- }
616
- for (const m of bm25) {
617
- if (merged.length >= lim) break;
618
- if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
619
- }
620
- }
621
- }
622
-
623
- // Mode contract, auto (aligns rrf/minmax with blend): keyword leads, the
624
- // recipe fills the remaining slots. blend.auto already front-loads keyword;
625
- // rrf/minmax rank across sources, so re-apply the same "keyword first"
626
- // ordering here to preserve the pre-fusion auto contract — the keyword
627
- // hit list keeps its power, and only slots it couldn't fill go to the
628
- // recipe's ranking.
629
- if (recipe !== "blend" && mode === "auto" && keyword.length) {
630
- const head = keyword.slice(0, lim);
631
- const seen = new Set(head.map((m) => m.id));
632
- const tail = merged.filter((m) => !seen.has(m.id)).slice(0, Math.max(0, lim - head.length));
633
- merged = head.concat(tail);
634
- }
635
-
636
- return { merged, signals };
637
- }
638
-
639
- /**
640
- * Search memories for a query. Merges up to three recall sources (keyword,
641
- * vector, BM25) according to config.recallFusion (blend/rrf/minmax — see
642
- * fuseRecall), then optionally decorates rows with per-source signals
643
- * (config.signalTransparency), applies semantic dedup (non-keyword modes),
644
- * reranking, and epistemic trust re-weighting, and finally hands the merged
645
- * list to the recall-layer recorder.
646
- *
647
- * options:
648
- * mode — 'auto' (default) | 'keyword' | 'vector' | 'hybrid'
649
- * topK — max rows (default 20)
650
- * threshold — explicit vector score floor (overrides adaptive)
651
- * useRerank — apply the reranker if available (default true)
652
- * recordRecall — write a recall_runs audit row (default from config)
653
- *
654
- * Returns an array of memory rows { id, title, content, score, source, ... },
655
- * with `signals` added when config.signalTransparency is on. Never throws:
656
- * a vector/rerank failure degrades to keyword results.
657
- */
658
- async function searchMemories(query, options = {}) {
659
- const {
660
- mode = "auto",
661
- topK = 20,
662
- threshold,
663
- useRerank = true,
664
- // v0.8.0 A2(issue #17):当前会话 scope(工具层从 exec 解析后传入)与
665
- // occurred_at 时间窗。两者都只在显式传入时生效,既有调用方(注入/梦/评测)
666
- // 不传 → 行为与 A2 前一致。
667
- scope = null,
668
- occurredFrom = null,
669
- occurredTo = null,
670
- recordRecall = options.recordRecall ?? (config?.recallRecordDefault ?? true)
671
- } = options;
672
- const q = String(query ?? "").trim();
673
- if (!q) return [];
674
-
675
- // entity:/attr: 前缀路由(v0.3.0 Phase 3)。entitySearchEnabled 关闭时走原逻辑。
676
- if (config?.entitySearchEnabled) {
677
- if (q.startsWith("entity:")) {
678
- return searchByEntity(q.slice(7).trim(), options);
679
- }
680
- if (q.startsWith("attr:")) {
681
- const [key, value] = q.slice(5).split("=");
682
- return searchByAttr(key, value, options);
683
- }
684
- }
685
-
686
- const lim = topK > 0 ? topK : 20;
687
-
688
- // Keyword results, decorated with a score so they can be weight-blended
689
- // with vector results and reported uniformly. source tracks where each
690
- // candidate came from for the recall layer receipt.
691
- const rawKeyword = store.search(q, { limit: lim });
692
- const keyword = rawKeyword.map((m) => ({ ...m, score: scoreKeyword(m, q), source: "keyword" }));
693
- const wantVector = mode === "vector" || mode === "hybrid" || (mode === "auto" && !!embedder);
694
- let vector = [];
695
- if (wantVector && embedder) {
696
- try {
697
- // Legacy embedders expose embed(query); local ones expose embedSingle.
698
- const embedSingle = typeof embedder.embedSingle === "function"
699
- ? embedder.embedSingle.bind(embedder)
700
- : embedder.embed.bind(embedder);
701
- const qv = await embedSingle(q);
702
- if (qv?.length) {
703
- // Adaptive threshold (v0.5.0 1.2): the fetch runs at the loosest
704
- // branch floor so the head-gap rule can still re-admit the tail;
705
- // the final cutoff is computed against the fetched score
706
- // distribution. Explicit `threshold` wins; disabled → legacy 0.
707
- const adaptive = config?.adaptiveThresholdEnabled !== false;
708
- const fetchThreshold = adaptive && threshold === undefined
709
- ? Math.min(0.5, adaptiveThreshold(q))
710
- : (threshold ?? 0);
711
- const search = vectorIndex
712
- ? vectorIndex.search(qv, { limit: lim * 2, threshold: fetchThreshold })
713
- : store.searchVector(qv, { limit: lim * 2, threshold: fetchThreshold });
714
- const finalThreshold = adaptive && threshold === undefined
715
- ? adaptiveThreshold(q, search)
716
- : (threshold ?? 0);
717
- vector = search
718
- .filter((m) => (m.score ?? 1) >= finalThreshold)
719
- .map((m) => ({ ...m, vector: true, source: "vector" }));
720
- }
721
- } catch { /* vector unavailable: keep keyword results */ }
722
- }
723
-
724
- // BM25 third path (v0.5.0 1.1): IDF-weighted token overlap recalls rows
725
- // whose query terms are scattered — the gap LIKE substring matching
726
- // cannot close. Scores are already normalized to [0,1].
727
- const bm25 = bm25Recall(q, lim).map((m) => ({ ...m, source: "bm25" }));
728
- // Loose blend weight: BM25 confirms and backfills, never dominates the
729
- // semantic signal. Same-memory overlap boosts, unseen ids backfill.
730
- const wb = 0.3;
731
-
732
- // Hybrid blending weights from config when provided.
733
- const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
734
- const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
735
-
736
- const { merged: fusedMerged, signals } = fuseRecall({ keyword, vector, bm25, lim, mode, wv, wk, wb });
737
- let merged = fusedMerged;
738
- // v0.8.0 A3(issue #17):strictScope 硬过滤——他 scope 的候选直接出局
739
- // (区别于 A2 的降权保留可见);未标注行与命中行保留。strict 与 A2 加权
740
- // 叠加:过滤后剩下的命中行仍吃加成。scope 未传(flag 关)或完全解析不到
741
- // 时跳过——identity 为空的对象({null,null})按 fail-closed 过滤。
742
- if (config.strictScope === true && scope) {
743
- merged = merged.filter((m) => isVisibleInScope(m, scope));
744
- }
745
- // v0.8.0 A2:occurred_at 时间过滤——在融合池上先滤再 dedup/slice,rerank
746
- // 只看窗内候选,topK 槽位不被窗外行占用。
747
- const occurredBounds = updatedAtBounds(occurredFrom, occurredTo);
748
- if (occurredBounds.from || occurredBounds.to) {
749
- merged = merged.filter((m) => inOccurredBounds(m, occurredBounds));
750
- }
751
- // Signal transparency (#2): decorate each returned row with its per-source
752
- // scores and the final fused score. Purely additive — never changes rank.
753
- if (config?.signalTransparency === true) {
754
- merged = merged.map((m) => ({ ...m, signals: { ...(signals.get(m.id) ?? {}), final: m.score ?? 0 } }));
755
- }
756
-
757
- // Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
758
- // dropped before the reranker sees them, so topK slots carry distinct
759
- // information instead of the same memory twice. Keyword mode is exempt —
760
- // it is the documented text-only path and must not be altered by
761
- // embedding state.
762
- merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
763
- merged = merged.slice(0, lim);
764
- let result = useRerank && reranker && merged.length
765
- ? await rerankCandidates(q, merged, lim)
766
- : merged;
767
- // Epistemic trust (v0.4.5): opt-in re-weighting of the final candidate
768
- // scores by source credibility. When off (default) `result` is returned
769
- // untouched — exactly the legacy behavior.
770
- if (config.trustEpistemicWeighting === true) {
771
- result = result
772
- .map((m) => ({
773
- ...m,
774
- score: (m.score ?? 0) * (EPISTEMIC_WEIGHTS[m.epistemic_status] ?? 1)
775
- }))
776
- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
777
- .slice(0, lim);
778
- }
779
-
780
- // v0.8.0 A2(issue #17):scope 检索加权——两维都无法确立 foreign 的候选
781
- // (命中/未标注/当前侧解析不到)加成,确立 foreign 的候选降权但保留可见
782
- // (硬过滤是 A3 strictScope);未标注行与命中行同列吃 BOOST、不被压制。
783
- // flag 关或调用方未传 scope 时不动分,排序与 A2 前逐字节一致。与
784
- // epistemic 加权同款收尾:乘分 → 降序 → 截 topK。
785
- if (config.scopeEnabled === true && scope && (scope.agent_scope || scope.workspace_scope)) {
786
- result = result
787
- .map((m) => ({ ...m, score: (m.score ?? 0) * scopeMultiplier(m, scope) }))
788
- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
789
- .slice(0, lim);
790
- }
791
-
792
- // Recall layer receipt: with recordRecall on, hand the actual merged
793
- // candidate list (id/title/content/score/source) to the injected recorder
794
- // before returning, making the retrieval scene replayable — the sibling of
795
- // the dream judgment-layer audit trail. Recorder failures must never break
796
- // the search itself.
797
- if (recordRecall && recallRecorder) {
798
- try {
799
- recallRecorder({
800
- query: q,
801
- mode,
802
- topK: lim,
803
- threshold: threshold ?? null,
804
- candidates: result.map((m) => ({
805
- id: m.id,
806
- title: m.title,
807
- content: m.content,
808
- score: m.score ?? null,
809
- source: m.source ?? "keyword"
810
- })),
811
- createdAt: new Date().toISOString()
812
- });
813
- } catch { /* recall receipt is best effort */ }
814
- }
815
- // Bug4: cache the latest semantic recall so the sync injection path can
816
- // reuse it when the injection query matches (no async embed available).
817
- lastSemanticRecall = { query: q, items: result };
818
- touchRecalled(result);
819
- return result;
820
- }
821
-
822
- /**
823
- * Retrieval evaluation (方案 B): run one search for `query`, compare the ids
824
- * it actually returned against `expectedIds`, and return the computed
825
- * metrics. When persistence is on (config.evalPersistTestResults, or an
826
- * explicit `persist` override per call) the snapshot is written to the
827
- * recall_evals table — a SEPARATE store from the recall_runs production audit,
828
- * so test/eval data never inflates the production trail.
829
- *
830
- * options:
831
- * mode/topK/threshold/useRerank — passed through to searchMemories
832
- * evalType — label for the snapshot (default 'manual')
833
- * recordRecall — also write a recall_runs audit row for the
834
- * same scene and link it via recall_run_id
835
- * (default false: eval stays unlinked)
836
- * recallRunId — explicit link to an existing recall_runs id
837
- * persist — override the config gate for this call
838
- *
839
- * Returns { metrics, actualIds, expectedIds, recallRunId, persisted }.
840
- * Never throws on persistence failures: a broken eval write must not break
841
- * the retrieval quality measurement.
842
- */
843
- async function evaluateRetrieval(query, expectedIds, options = {}) {
844
- const q = String(query ?? "").trim();
845
- const expected = Array.isArray(expectedIds) ? expectedIds : [];
846
- const {
847
- mode = "auto",
848
- topK = 20,
849
- threshold,
850
- useRerank = true,
851
- evalType = "manual",
852
- recordRecall = false,
853
- recallRunId = null,
854
- persist = config.evalPersistTestResults === true
855
- } = options;
856
- if (!q) {
857
- const empty = computeRetrievalMetrics([], expected);
858
- return { metrics: empty, actualIds: [], expectedIds: expected, recallRunId: null, persisted: false };
859
- }
860
-
861
- const rows = await searchMemories(q, { mode, topK, threshold, useRerank, recordRecall: false });
862
- const actualIds = rows.map((m) => m.id);
863
- const metrics = computeRetrievalMetrics(actualIds, expected);
864
-
865
- // Optional recall_runs audit for the same scene; the eval row then links to
866
- // it. Kept separate from the production recorder (which fires only on
867
- // recordRecall=true inside searchMemories) — eval never double-records.
868
- // An explicit recallRunId wins; recordRecall only mints a NEW audit run when
869
- // the caller did not already link one (never clobber an existing link).
870
- let runId = recallRunId ?? null;
871
- if (recordRecall && runId === null) {
872
- try {
873
- const run = store.saveRecallRun({
874
- query: q,
875
- mode,
876
- topK,
877
- threshold: threshold ?? null,
878
- candidates: rows.map((m) => ({
879
- id: m.id,
880
- title: m.title,
881
- content: m.content,
882
- score: m.score ?? null,
883
- source: m.source ?? "keyword"
884
- })),
885
- created_at: new Date().toISOString()
886
- });
887
- runId = run.id;
888
- } catch { /* non-fatal: the eval itself still succeeds */ }
889
- }
890
-
891
- let persisted = false;
892
- if (persist) {
893
- try {
894
- store.saveRecallEval({
895
- recall_run_id: runId,
896
- query: q,
897
- expected_ids: expected,
898
- actual_ids: actualIds,
899
- metrics,
900
- eval_type: evalType,
901
- created_at: new Date().toISOString()
902
- });
903
- persisted = true;
904
- } catch { /* non-fatal: measurement survives a failed eval write */ }
905
- }
906
- return { metrics, actualIds, expectedIds: expected, recallRunId: runId, persisted };
907
- }
908
-
909
- /**
910
- * Fire-and-forget write notification; errors are swallowed to keep write
911
- * paths clean. The store mutation has already committed, so a throwing
912
- * subscriber must not surface as a write failure. Archive/forget flags are
913
- * state toggles, not content writes, so they never notify.
914
- */
915
- function notifyWrite() {
916
- if (txDepth > 0) return; // deferred to the transaction's commit
917
- if (onWrite) {
918
- try { onWrite(); } catch { /* ignore */ }
919
- }
920
- if (dreamHook) {
921
- try { dreamHook(); } catch { /* ignore */ }
922
- }
923
- if (sleepHook) {
924
- try { sleepHook(); } catch { /* ignore */ }
925
- }
926
- }
927
-
928
- /**
929
- * Run several store mutations atomically (SQLite BEGIN/COMMIT/ROLLBACK) and
930
- * fire the deferred side effects once against the committed state. A throwing
931
- * body rolls the whole batch back — no partial writes, no diverged mirror.
932
- * Errors propagate to the caller. NOTE: the commit path re-renders the mirror
933
- * and notifies subscribers, but re-embedding is left to the caller (the dream
934
- * flow re-embeds through maintainIndexAfterDream).
935
- */
936
- function transaction(fn) {
937
- store.db.exec("BEGIN");
938
- txDepth++;
939
- try {
940
- const result = fn();
941
- store.db.exec("COMMIT");
942
- return result;
943
- } catch (error) {
944
- try { store.db.exec("ROLLBACK"); } catch { /* store may be closed */ }
945
- throw error;
946
- } finally {
947
- txDepth--;
948
- // Sync failures are surfaced, not swallowed (peer blocker 2): the mirror
949
- // debt was already recorded by markMirrorDirty inside syncMirror, so a
950
- // restart recovers — but the operator must see it now, not after restart.
951
- const syncResult = syncMirror();
952
- if (!syncResult?.success && !syncResult?.deferred) {
953
- logger?.warn?.("mirror sync failed after transaction:", syncResult?.error);
954
- }
955
- notifyWrite();
956
- }
957
- }
958
-
959
- /**
960
- * Embed an arbitrary query text and return its vector (null on failure / no
961
- * embedder). Used by the injector to prefetch the semantic-first recall
962
- * vector for the current user message — the system-prompt render is
963
- * synchronous, so the vector must be cached in advance (Bug4).
964
- */
965
- async function embedQuery(query) {
966
- const q = String(query ?? "").trim();
967
- if (!q || !embedder) return null;
968
- try {
969
- const embedSingle = typeof embedder.embedSingle === "function"
970
- ? embedder.embedSingle.bind(embedder)
971
- : embedder.embed.bind(embedder);
972
- const vector = await embedSingle(q);
973
- return Array.isArray(vector) && vector.length ? vector : null;
974
- } catch {
975
- return null;
976
- }
977
- }
978
-
979
- /**
980
- * 写入端同会话语义去重(Issue #127,opt-in,默认 off):落库前把新条目与
981
- * 「同会话 + 时间窗」内已落库的记忆比对,命中即并入既有条目,不再新造一行。
982
- *
983
- * 分层:title 档走零成本的标题归一化;vector 档复用已有 embedding 列做近邻,
984
- * 新条目的向量由 embedder 现算(embedQuery),全程无 LLM 调用。embedder 不可用
985
- * 或向量缺失一律返回 undefined 回落正常写入——去重是增强,绝不能成为写入依赖。
986
- *
987
- * 作用域刻意限定「同会话」:跨会话的同类事实仍交给 autoDream / sleep 的批量裁决。
988
- * 比对逻辑与并入动作分别复用 cosineVec 与 saveWithDedupe 的 _mergeInto 分支。
989
- *
990
- * @returns {{action: "merged", memory: object, sim: number}|undefined} 命中则返回
991
- * 并入目标与相似度;未命中(含任何异常)返回 undefined。
992
- */
993
- async function findSessionDuplicate(memory, { mode = "off", minSim = 0.92, windowHours = 24, source } = {}) {
994
- if (mode === "off" || !source || !memory?.title) return undefined;
995
- try {
996
- const sinceMs = windowHours > 0 ? Date.now() - windowHours * 3600000 : 0;
997
- const inWindow = (m) => {
998
- if (sinceMs <= 0) return true;
999
- const t = Date.parse(m.created_at ?? "");
1000
- return !Number.isFinite(t) || t >= sinceMs; // 时间戳损坏时不误杀
1001
- };
1002
- const candidates = store
1003
- .list({ type: memory.type, source, limit: 200 })
1004
- .filter((m) => !m.archived && inWindow(m));
1005
- if (!candidates.length) return undefined;
1006
-
1007
- if (mode === "title") {
1008
- const norm = (s) => String(s ?? "").toLowerCase().replace(/[\s\p{P}]+/gu, "");
1009
- const key = norm(memory.title);
1010
- if (!key) return undefined;
1011
- const hit = candidates.find((m) => norm(m.title) === key);
1012
- return hit ? { action: "merged", memory: hit, sim: 1 } : undefined;
1013
- }
1014
- if (mode !== "vector") return undefined;
1015
-
1016
- const vecs = store.getEmbeddings(candidates.map((m) => m.id));
1017
- if (!vecs.size) return undefined;
1018
- const probe = await embedQuery([memory.title, memory.content].filter(Boolean).join("\n"));
1019
- if (!probe) return undefined;
1020
- let best;
1021
- for (const m of candidates) {
1022
- const v = vecs.get(m.id);
1023
- if (!v) continue; // 无向量的既有行不参与比对(无信号 = 不判定)
1024
- const sim = cosineVec(probe, v);
1025
- if (sim >= minSim && (!best || sim > best.sim)) best = { action: "merged", memory: m, sim };
1026
- }
1027
- return best;
1028
- } catch {
1029
- return undefined; // 去重失败绝不阻塞写入
1030
- }
1031
- }
1032
-
1033
- /**
1034
- * Save a memory, merging into an existing one when title matches within the same type.
1035
- *
1036
- * Bug5: a same-title merge no longer overwrites — the new content is appended
1037
- * under a timestamped `---` separator (`旧内容\n\n---\n[时间戳] 新内容`) and the
1038
- * previous content is archived into content_history (source: auto_merge, FIFO
1039
- * capped at 20). importance takes the max of both (capped at 5). Callers that
1040
- * truly replace a row (dream summary regeneration) pass `_overwrite: true` to
1041
- * overwrite directly while still archiving the old version (source: overwrite).
1042
- * mergeHumanEdits entry points pass `_humanEdited: true` — same direct
1043
- * overwrite semantics, source: human_override.
1044
- *
1045
- * Bug7 (memory quality filter): when config.memoryQualityFilter.enabled, the
1046
- * memory is scored after dedupe, before write:
1047
- * score >= degradeThreshold → stored normally (score persisted)
1048
- * archiveThreshold <= score < 60 → persisted + ranked degraded
1049
- * score < archiveThreshold → archived + tagged low_quality (still
1050
- * explicitly searchable via includeArchived)
1051
- * @returns {{action: "created"|"merged", memory: object}}
1052
- */
1053
- function saveWithDedupe(memory) {
1054
- // Bug7: score quality once (after dedupe lookup, before write). Failures
1055
- // inside the evaluator are impossible (pure function), but the write that
1056
- // records the score must never fail the save — wrap defensively.
1057
- const qf = config.memoryQualityFilter;
1058
- let quality = null;
1059
- if (qf?.enabled === true) {
1060
- try {
1061
- const recentContents = store.all().slice(0, 20).map((m) => m.content ?? "");
1062
- quality = evaluateMemoryQuality(memory, {
1063
- minContentLength: qf.minContentLength ?? 10,
1064
- recentContents
1065
- });
1066
- } catch { /* quality scoring is best-effort */ }
1067
- }
1068
- // dream 总览按 source 身份去重,而非本地化标题:memory.language 切换后
1069
- // 标题变化,若仍按 (type, title) 匹配会出现两个活跃的 summary 同时注入。
1070
- // 其余类型维持 (type, title) 匹配不变。
1071
- const candidates = store.list({ type: memory.type, limit: 100 });
1072
- // v0.8.0 A1(issue #17):去重键由 (type, title) 扩展为
1073
- // (type, title, agent_scope, workspace_scope, sensitivity)——不同作用域的同
1074
- // 标题记忆绝不互相物理合并(旧逻辑跨 agent/workspace 并行,事后无法拆分)。
1075
- // NULL 归一为「未标注」:未标注行之间互相匹配(含存量行),与已标注行不
1076
- // 匹配。
1077
- // v0.8.1(issue #170 复核项 1):比较不再受 scopeEnabled 门控——显式声明
1078
- // flag 关也生效(工具层明写「读了自动标注也生效」,去重必须同口径),否则
1079
- // 关自动标注后同标题不同 scope 的行会物理合并进第一行的归属。存量全 NULL
1080
- // 行互相匹配,A1 前行为不变。
1081
- const scopeMatches = (m) =>
1082
- scopeKeyOf(m.agent_scope) === scopeKeyOf(memory.agent_scope) &&
1083
- scopeKeyOf(m.workspace_scope) === scopeKeyOf(memory.workspace_scope) &&
1084
- scopeKeyOf(m.sensitivity) === scopeKeyOf(memory.sensitivity);
1085
- // Issue #127:写入端语义去重命中时,调用方用 _mergeInto 指定并入目标——复用
1086
- // 下面这段并入逻辑(appendContent + content_history + 质量处置),不另写第二份
1087
- // 实现。目标已被并发删除时回落到常规匹配。显式目标同样过 scope 门:跨作用域
1088
- // 的语义相似不并入(防泄漏),回落为独立新行。
1089
- const explicitTarget = memory._mergeInto ? store.getById(memory._mergeInto) : undefined;
1090
- const existing = explicitTarget
1091
- ? (scopeMatches(explicitTarget) ? explicitTarget : undefined)
1092
- : (memory.type === "summary" && memory.source === "dream")
1093
- ? (candidates.find((m) => m.source === "dream" && scopeMatches(m))
1094
- ?? candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim()))
1095
- : candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim());
1096
- if (existing) {
1097
- const newContent = String(memory.content ?? "");
1098
- if (!newContent.trim()) {
1099
- // Nothing to merge: the row stays untouched.
1100
- return { action: "merged", memory: existing };
1101
- }
1102
- const direct = memory._overwrite === true || memory._humanEdited === true;
1103
- const content = direct
1104
- ? newContent
1105
- : appendContent(existing.content, newContent);
1106
- const importance = Math.min(5, Math.max(existing.importance, memory.importance ?? existing.importance));
1107
- // v0.8.1 底座(issue #170):去重命中=scope 值完全同键,此时显式写入把
1108
- // 被并入行的同维来源升级为 explicit(用户刚刚显式声明了同一归属),
1109
- // 并刷新 scope_decided_at。仅升级来源、不改值——值改变会走新行。
1110
- const scopeUpgrade = {};
1111
- if (memory.agent_scope_source === "explicit" && existing.agent_scope_source !== "explicit") {
1112
- scopeUpgrade.agent_scope_source = "explicit";
1113
- }
1114
- if (memory.workspace_scope_source === "explicit" && existing.workspace_scope_source !== "explicit") {
1115
- scopeUpgrade.workspace_scope_source = "explicit";
1116
- }
1117
- if (Object.keys(scopeUpgrade).length) scopeUpgrade.scope_decided_at = new Date().toISOString();
1118
- const merged = store.update(existing.id, {
1119
- content,
1120
- importance,
1121
- tags: memory.tags ?? existing.tags,
1122
- title: memory.title ?? existing.title,
1123
- content_history: pushContentHistory(existing, direct
1124
- ? (memory._humanEdited === true ? "human_override" : "overwrite")
1125
- : "auto_merge"),
1126
- ...scopeUpgrade,
1127
- ...(quality ? { quality_score: quality.score } : {})
1128
- });
1129
- // v0.8.1(issue #170 review 3):来源升级也是归属性质改变——与
1130
- // updateMemory 的显式修正同等待遇,落一行 scope_changes(actor=tool:
1131
- // 只有 memory_save 的显式参数会带 explicit 来源走到这里)。审计失败只
1132
- // warn 不反噬合并。升级只在来源首次变化时触发,不会每次并入都写。
1133
- if (Object.keys(scopeUpgrade).length) {
1134
- try {
1135
- store.saveScopeChange({
1136
- memory_id: existing.id,
1137
- actor: "tool",
1138
- prev_agent_scope: existing.agent_scope ?? null,
1139
- prev_workspace_scope: existing.workspace_scope ?? null,
1140
- next_agent_scope: merged.agent_scope ?? null,
1141
- next_workspace_scope: merged.workspace_scope ?? null,
1142
- agent_scope_source: merged.agent_scope_source ?? null,
1143
- workspace_scope_source: merged.workspace_scope_source ?? null,
1144
- decided_at: scopeUpgrade.scope_decided_at
1145
- });
1146
- } catch (e) {
1147
- try { logger?.warn?.(`[dsh-mneme] scope upgrade audit failed: ${String(e)}`); } catch { /* 不反噬 */ }
1148
- }
1149
- }
1150
- // Bug7: a degraded/archived result is applied on top of the merged row.
1151
- const result = applyQualityDisposition(merged, quality, qf);
1152
- afterSync("write");
1153
- notifyWrite();
1154
- scheduleEmbed(result);
1155
- return { action: "merged", memory: result };
1156
- }
1157
- const created = store.save({
1158
- type: memory.type,
1159
- title: memory.title,
1160
- content: memory.content,
1161
- tags: memory.tags ?? [],
1162
- importance: memory.importance ?? 3,
1163
- source: memory.source ?? "manual",
1164
- // v0.8.0 A1:scope 标注透传(store 端归一化,未标注落 NULL)。
1165
- // v0.8.1 底座:来源(auto/explicit)与决策时间随行透传。
1166
- agent_scope: memory.agent_scope,
1167
- workspace_scope: memory.workspace_scope,
1168
- agent_scope_source: memory.agent_scope_source,
1169
- workspace_scope_source: memory.workspace_scope_source,
1170
- scope_decided_at: memory.scope_decided_at,
1171
- sensitivity: memory.sensitivity,
1172
- occurred_at: memory.occurred_at,
1173
- ...(quality ? { quality_score: quality.score } : {})
1174
- });
1175
- const result = applyQualityDisposition(created, quality, qf);
1176
- afterSync("write");
1177
- notifyWrite();
1178
- scheduleEmbed(result);
1179
- scheduleEntityExtraction(result);
1180
- return { action: "created", memory: result };
1181
- }
1182
-
1183
- /**
1184
- * Bug7: apply the quality verdict to a freshly written row. Below the archive
1185
- * threshold the memory is archived + tagged low_quality (still searchable
1186
- * explicitly via includeArchived); between archive and degrade thresholds the
1187
- * score is already persisted and only the injection ranking is affected
1188
- * (importance × score/100). Best-effort: a disposition write failure must
1189
- * never fail the save. Returns the (possibly refreshed) memory row so callers
1190
- * see the archived/tagged state, not the pre-disposition snapshot.
1191
- *
1192
- * Issue #135 附属发现 1:importance ≥ memoryQualityFilter.exemptImportance
1193
- * (默认 4)的记忆不参与静默自动归档——评分与信号标签照常写入(可观测),
1194
- * 注入排序照常按 importance × score/100 降权,但 setArchived 跳过。报告实测
1195
- * 150 条低分归档里 128 条 importance ≥ 4(51 条 = 5):一条被显式标为重要的
1196
- * 记忆不该被规则分静默归档、无感知无豁免。
1197
- */
1198
- function applyQualityDisposition(memory, quality, qf) {
1199
- if (!quality || qf?.enabled !== true) return memory;
1200
- const archiveThreshold = qf.archiveThreshold ?? 30;
1201
- // Signal tags (meta / repetitive / duplicate / short_content / low_quality)
1202
- // are merged onto the stored row in every assessed band so the verdict is
1203
- // observable, not just the numeric score. Below the archive threshold the
1204
- // memory is additionally archived (still explicitly searchable) — unless
1205
- // its importance reaches the exemption floor (kept active, demoted only).
1206
- const tags = [...new Set([...(memory.tags ?? []), ...(quality.tags ?? [])])];
1207
- const exemptImportance = qf.exemptImportance ?? 4;
1208
- const importanceExempt = Number.isInteger(memory.importance) && memory.importance >= exemptImportance;
1209
- if (tags.length === (memory.tags?.length ?? 0) && (quality.score >= archiveThreshold || importanceExempt)) {
1210
- return memory; // no tag drift and not archived → nothing extra to write
1211
- }
1212
- try {
1213
- store.update(memory.id, { tags, quality_score: quality.score });
1214
- if (quality.score < archiveThreshold && !importanceExempt) {
1215
- store.setArchived(memory.id, true);
1216
- } else if (quality.score < archiveThreshold) {
1217
- logger?.info?.(`[dsh-mneme] quality filter: memory ${memory.id} scored ${quality.score} < ${archiveThreshold} but importance ${memory.importance} >= exemptImportance ${exemptImportance}; demoted, not archived`);
1218
- }
1219
- return store.getById(memory.id);
1220
- } catch {
1221
- return memory;
1222
- }
1223
- }
1224
-
1225
- /**
1226
- * Candidate memories for automatic context injection:
1227
- * summaries first, then all preferences, then non-forgotten items with
1228
- * importance >= threshold. History is never auto-injected. Archived entries
1229
- * are excluded (store.list already filters them by default; the extra
1230
- * !m.archived check is kept as double insurance).
1231
- *
1232
- * Bug4 (hybridInject): when a non-empty `query` is available and a matching
1233
- * semantic recall was cached by the last searchMemories, the vector hits
1234
- * lead the selection (up to maxItems*2 candidates) and the rule-based pick
1235
- * fills + dedupes the remaining slots. Empty query / no cached recall /
1236
- * hybridInject off → pure legacy rule-based selection.
1237
- */
1238
- function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector, scope = null } = {}) {
1239
- const q = String(query ?? "").trim();
1240
- // codingRetrospect 读取侧门控:编码记忆(rejected_solution / pitfall /
1241
- // constraint)只在编码任务时注入,防噪声污染其他业务;编码任务时按
1242
- // codingBoostFactor 加权,让编码记忆在编码场景更靠前。
1243
- const isCoding = isCodingTask(q, config.codingKeywords ?? []);
1244
- const codingGate = (m) => isCoding || !CODING_MEMORY_TYPES.has(m.type);
1245
- // Bug7: quality-weighted importance in the rule-based tier. Unassessed rows
1246
- // (quality_score null) count as 100 (weight 1), so legacy stores keep their
1247
- // exact summary>preference>importance ordering.
1248
- const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
1249
- const items = store.list({ limit: 200, includeForgotten: false })
1250
- .filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1251
- codingGate(m) &&
1252
- (m.type === "summary" || m.type === "preference" || m.importance >= threshold))
1253
- .sort((a, b) => {
1254
- // 编码记忆在编码任务时优先于普通 decision(与 preference 同级),
1255
- // importance 乘 codingBoostFactor 加权(封顶 5,保持 importance 语义)。
1256
- const priority = (m) => {
1257
- if (m.type === "summary") return 0;
1258
- if (m.type === "preference") return 1;
1259
- if (isCoding && CODING_MEMORY_TYPES.has(m.type)) return 1;
1260
- return 2;
1261
- };
1262
- const effImportance = (m) =>
1263
- (isCoding && CODING_MEMORY_TYPES.has(m.type))
1264
- ? Math.min(5, m.importance * (config.codingBoostFactor ?? 2))
1265
- : m.importance;
1266
- const pa = priority(a);
1267
- const pb = priority(b);
1268
- return pa - pb || (effImportance(b) * qualityWeight(b)) - (effImportance(a) * qualityWeight(a));
1269
- });
1270
- let candidates = items;
1271
- if (config.hybridInject !== false && q) {
1272
- // Bug4: semantic-first recall. Vector hits (queryVector, cached by the
1273
- // injector's async prefetch) lead when present; otherwise the last
1274
- // searchMemories recall for the exact same query is reused. Rule-based
1275
- // items fill + dedupe the remaining slots. Empty query / no vector /
1276
- // no cached recall → pure legacy rule-based selection.
1277
- const semanticItems = [];
1278
- if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
1279
- try {
1280
- const hits = vectorIndex.search(queryVector, { limit: maxItems * 2, threshold: 0 });
1281
- for (const m of hits) {
1282
- if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1283
- codingGate(m) &&
1284
- (m.type === "summary" || m.type === "preference" || m.importance >= threshold)) {
1285
- semanticItems.push(m);
1286
- }
1287
- }
1288
- } catch { /* vector unavailable: fall through to the recall cache */ }
1289
- }
1290
- if (!semanticItems.length && lastSemanticRecall?.query === q && lastSemanticRecall.items?.length) {
1291
- for (const m of lastSemanticRecall.items) {
1292
- if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten && codingGate(m)) semanticItems.push(m);
1293
- }
1294
- }
1295
- // Issue #198:首轮(无向量、无缓存召回)的同步兜底——BM25 词法召回领位。
1296
- // 注入渲染是同步的(宿主 systemPrompt 的 contexts 不支持异步 text),
1297
- // 查询向量只能异步 prefetch 给下一轮,首轮必 miss;此时纯静态排序会让
1298
- // 老的高重要性 summary/preference 占满槽位,当前话题的 decision/project
1299
- // 进不来。查询文本本身就在手上,BM25 是纯进程内同步计算,词法相关性
1300
- // 足以把当前话题顶到前排;门控与向量路径一致(含 importance 阈值)。
1301
- // 语义向量命中时本分支不参与,行为不变。
1302
- if (!semanticItems.length) {
1303
- for (const hit of bm25Recall(q, maxItems * 2)) {
1304
- if (hit && !hit.archived && INJECT_TYPES.has(hit.type) && !hit.forgotten &&
1305
- codingGate(hit) &&
1306
- (hit.type === "summary" || hit.type === "preference" || hit.importance >= threshold)) {
1307
- semanticItems.push(hit);
1308
- }
1309
- }
1310
- }
1311
- if (semanticItems.length) {
1312
- const seen = new Set();
1313
- const merged = [];
1314
- const push = (m) => {
1315
- if (seen.has(m.id)) return;
1316
- seen.add(m.id);
1317
- merged.push(m);
1318
- };
1319
- for (const m of semanticItems) {
1320
- push(m);
1321
- if (merged.length >= maxItems * 2) break;
1322
- }
1323
- for (const m of items) {
1324
- if (merged.length >= maxItems * 2) break;
1325
- push(m);
1326
- }
1327
- candidates = merged;
1328
- }
1329
- }
1330
- // Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
1331
- // available the whole candidate list is re-ordered by similarity to that
1332
- // vector, so the injected slots go to memories on the current topic
1333
- // rather than to the rule-based order. Rows the index did not return
1334
- // keep their relative order after the scored ones.
1335
- if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
1336
- try {
1337
- const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
1338
- const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
1339
- if (sim.size) {
1340
- candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
1341
- }
1342
- } catch { /* topic re-rank unavailable: keep rule-based order */ }
1343
- }
1344
- // v0.8.0 A3(issue #17):strictScope 硬过滤同样作用于自动注入——scoped 记忆
1345
- // 泄进无关注入上下文是最典型的越权通道,检索侧过滤挡不住这里。
1346
- if (config?.strictScope === true && scope) {
1347
- candidates = candidates.filter((m) => isVisibleInScope(m, scope));
1348
- }
1349
- const selected = candidates.slice(0, maxItems);
1350
- touchRecalled(selected);
1351
- return selected;
1352
- }
1353
-
1354
- /**
1355
- * Merge human edits parsed from a mirror file back into the store.
1356
- * Only content/title are taken; structure fields stay machine-owned.
1357
- */
1358
- function mergeHumanEdits(type, edits) {
1359
- let applied = 0;
1360
- for (const edit of edits) {
1361
- if (!edit.id) continue; // corrupt/malformed edit: skip it, keep merging the rest
1362
- const existing = store.getById(edit.id);
1363
- if (!existing || existing.type !== type) continue;
1364
- const patch = {};
1365
- if (typeof edit.title === "string" && edit.title.trim()) patch.title = edit.title.trim();
1366
- if (typeof edit.content === "string" && edit.content.trim()) patch.content = edit.content.trim();
1367
- if (Object.keys(patch).length) {
1368
- // 启动回灌(F-NEW-01):digest 存在且匹配 = 文件自渲染后无人触碰(旧机器
1369
- // 镜像),机器 wins,DB 的 New 必须保留,静默改回 Old 是 bug。
1370
- const digestMatches = typeof edit.digest === "string"
1371
- && typeof edit.title === "string"
1372
- && typeof edit.content === "string"
1373
- && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1374
- if (digestMatches) continue;
1375
- // 文件 == store(无实际变化)时不覆盖,也不计入 applied。
1376
- const hasDiff = (patch.title !== undefined && existing.title !== patch.title)
1377
- || (patch.content !== undefined && existing.content !== patch.content);
1378
- if (!hasDiff) continue;
1379
- // 人工编辑回灌后触发 re-embed(issue #3 残留修复):向量必须与
1380
- // 新 title/content 一致。scheduleEmbed 为 fire-and-forget,
1381
- // 内部 try/catch 吞错,失败不影响主流程。
1382
- // Bug5: human edits overwrite directly, but the machine version is
1383
- // archived into content_history (source: human_override) before being
1384
- // replaced, so a manual correction never silently destroys the old value.
1385
- const merged = store.update(edit.id, {
1386
- ...patch,
1387
- content_history: patch.content !== undefined && existing.content !== patch.content
1388
- ? pushContentHistory(existing, "human_override")
1389
- : existing.content_history
1390
- });
1391
- applied++;
1392
- scheduleEmbed(merged);
1393
- }
1394
- }
1395
- if (applied) {
1396
- afterSync("write");
1397
- notifyWrite();
1398
- }
1399
- return applied;
1400
- }
1401
-
1402
- /**
1403
- * v0.8.0 冲突集中处理(issue 反馈:冻结冲突没有人工出口——store 的
1404
- * resolveConflictPending 此前无任何 API/UI 调用)。人工确认一条待审冲突:
1405
- * 盖章 resolved_at/resolved_winner(审计),可选按 dream 非冻结 conflict
1406
- * 路径**同款**处置落地——复用 applyDecisions 的 conflict 分支,CAS 快照 +
1407
- * 事务 + 胜者追加已否决注记 + 败者归档 + 幂等全部同源,不另写第二份裁决。
1408
- *
1409
- * @param {string} id conflict_pending 行 id
1410
- * @param {{winner?: "a"|"b"|null, apply?: boolean}} opts
1411
- * winner: 选哪一方保留(a = memory_a,冻结时 LLM 的建议胜者;b = memory_b);
1412
- * null = 仅盖章标记已读、不落地处置。人工选择是权威裁决:传入
1413
- * applyDecisions 的 config 关掉 trustEpistemicWeighting——可信度自动换位
1414
- * 只应作用于 LLM 提议对,不能推翻人工选择。
1415
- * @returns {object|undefined} 盖章后的冲突行 + disposition 摘要;未知 id 返回 undefined
1416
- */
1417
- function resolveConflictPending(id, { winner = null, apply = true } = {}) {
1418
- const rows = store.listConflictPending({ includeResolved: true, limit: 500 });
1419
- const row = rows.find((r) => r.id === id);
1420
- if (!row) return undefined;
1421
- const winnerId = winner === "a" ? row.memory_a : winner === "b" ? row.memory_b : null;
1422
- const loserId = winner === "a" ? row.memory_b : winner === "b" ? row.memory_a : null;
1423
- let disposition = null;
1424
- if (apply && winnerId && loserId) {
1425
- const snapshot = new Map();
1426
- for (const m of [store.getById(row.memory_a), store.getById(row.memory_b)]) {
1427
- if (m) snapshot.set(m.id, { updated_at: m.updated_at, content: m.content, title: m.title });
1428
- }
1429
- // applyDecisions 需要一个 service 形状的参数(getById/update/setArchived/
1430
- // transaction)——委托给闭包内的同名实现,mirror/通知/嵌入与主写路径同源。
1431
- const applyService = {
1432
- getById: (mid) => store.getById(mid),
1433
- update: (mid, patch) => updateMemory(mid, patch),
1434
- setArchived: (mid, v) => archiveMemory(mid, v),
1435
- transaction: (fn) => transaction(fn)
1436
- };
1437
- const { committed, failures } = applyDecisions(
1438
- [{ action: "conflict", winner: winnerId, loser: loserId, reason: row.reason ?? "" }],
1439
- applyService,
1440
- logger,
1441
- snapshot,
1442
- { ...config, trustEpistemicWeighting: false }
1443
- );
1444
- // Review 发现:处置必须**先于**盖章。原实现先 resolveConflictPending 盖章、
1445
- // 再 applyDecisions——若 CAS 拒掉(确认前双方被并发更新),行已 resolved 从
1446
- // 队列消失、前端仍显示成功,审计却记了"已确认"且无法重试。现在失败时不盖章
1447
- // 直接返回:行留在队列待重试,审计不被污染。
1448
- if (failures.length) {
1449
- return { ...row, disposition: { ok: false, failures } };
1450
- }
1451
- disposition = { ok: true, committed };
1452
- }
1453
- // 处置成功(或纯标记)后才盖章。幂等重放(败者已归档 → skipped)也走这里:
1454
- // 处置本就存在,标记已审即可。
1455
- const stamped = store.resolveConflictPending(id, { winner: winnerId });
1456
- if (!stamped) return undefined;
1457
- return { ...stamped, disposition };
1458
- }
1459
-
1460
- /**
1461
- * v0.8.0 冲突队列视图数据源:未解决冲突行,联表带出双方的当前状态(标题/
1462
- * 内容/类型/重要性/归档标记),面板一处即可集中审阅,不必按徽章逐条找。
1463
- * 参与记忆被删除/失联时该侧返回 {missing: true}(队列不因此丢行)。
1464
- */
1465
- function listConflictQueue({ limit = 50, offset = 0 } = {}) {
1466
- const rows = store.listConflictPending({ limit, offset, includeResolved: false });
1467
- const side = (id) => {
1468
- const m = store.getById(id);
1469
- if (!m) return { id, missing: true };
1470
- return {
1471
- id,
1472
- title: m.title,
1473
- type: m.type,
1474
- importance: m.importance,
1475
- content: m.content,
1476
- archived: m.archived === true,
1477
- forgotten: m.forgotten === true
1478
- };
1479
- };
1480
- return rows.map((r) => ({
1481
- id: r.id,
1482
- run_id: r.run_id ?? null,
1483
- reason: r.reason ?? null,
1484
- created_at: r.created_at,
1485
- memory_a: side(r.memory_a),
1486
- memory_b: side(r.memory_b)
1487
- }));
1488
- }
1489
-
1490
- function toApiList(rows) {
1491
- return rows.map((m) => ({
1492
- id: m.id,
1493
- type: m.type,
1494
- title: m.title,
1495
- content: m.content,
1496
- tags: m.tags,
1497
- importance: m.importance,
1498
- source: m.source,
1499
- created_at: m.created_at,
1500
- updated_at: m.updated_at,
1501
- // v0.8.0 A2:scope 标注与事件发生时间透出——条件展开(未标注行不带键,
1502
- // DTO 与 A2 前逐字节同形;带 undefined 键会被 in-process schema 校验
1503
- // 判违规,JSON 序列化虽会丢弃但形状不稳定)。
1504
- // v0.8.1 底座:scope 来源与决策时间随行透出(同样条件展开)。
1505
- ...(m.agent_scope !== undefined ? { agent_scope: m.agent_scope } : {}),
1506
- ...(m.workspace_scope !== undefined ? { workspace_scope: m.workspace_scope } : {}),
1507
- ...(m.agent_scope_source !== undefined ? { agent_scope_source: m.agent_scope_source } : {}),
1508
- ...(m.workspace_scope_source !== undefined ? { workspace_scope_source: m.workspace_scope_source } : {}),
1509
- ...(m.scope_decided_at !== undefined ? { scope_decided_at: m.scope_decided_at } : {}),
1510
- ...(m.sensitivity !== undefined ? { sensitivity: m.sensitivity } : {}),
1511
- ...(m.occurred_at !== undefined ? { occurred_at: m.occurred_at } : {})
1512
- }));
1513
- }
1514
-
1515
- /**
1516
- * Three-way merge of in-flight human mirror edits before a re-render.
1517
- * Runs on every syncMirror, so a human edit made between two store writes is
1518
- * never silently overwritten by the next sync (human priority is not limited
1519
- * to startup). Per edited entry:
1520
- * - file changed only → human wins; the edit is merged back into the store.
1521
- * - file AND store changed → real three-way conflict: keep the human edit
1522
- * and append a marker preserving the store's concurrent version, so no
1523
- * side is dropped.
1524
- * - store changed only → store wins (the file is simply re-rendered).
1525
- * Only title/content are taken (structure fields stay machine-owned, matching
1526
- * mergeHumanEdits). Returns the memory list to render.
1527
- */
1528
- function reconcileHumanEdits(memories) {
1529
- if (!mirror) return memories;
1530
- const byType = new Map();
1531
- for (const m of memories) {
1532
- if (!byType.has(m.type)) byType.set(m.type, []);
1533
- byType.get(m.type).push(m);
1534
- }
1535
- const result = [];
1536
- for (const type of Object.keys(TYPE_FILE)) {
1537
- const list = byType.get(type) ?? [];
1538
- if (list.length === 0) continue;
1539
- const editsById = new Map(mirror.readHumanEdits(type).map((e) => [e.id, e]));
1540
- for (const m of list) {
1541
- const edit = editsById.get(m.id);
1542
- if (!edit) { result.push(m); continue; }
1543
- const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
1544
- || (typeof edit.content === "string" && edit.content !== m.content);
1545
- if (!humanChanged) { result.push(m); continue; }
1546
- // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
1547
- // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
1548
- // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
1549
- // 并发人工编辑导致机器写丢失 + 伪冲突标记。
1550
- const digestMatches = typeof edit.digest === "string"
1551
- && typeof edit.title === "string"
1552
- && typeof edit.content === "string"
1553
- && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1554
- if (digestMatches) {
1555
- // 无人触碰,机器 wins,走原样
1556
- result.push(m);
1557
- continue;
1558
- }
1559
- // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
1560
- // (保留现有 storeChanged 逻辑)
1561
- const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
1562
- if (storeChanged) {
1563
- // 三方合并保留双方时的冲突批注:随实例语言,写进记忆正文。
1564
- const marker = STR.serviceConflictMarker[language](m.updated_at, m.content);
1565
- store.update(m.id, { title: edit.title, content: `${edit.content}${marker}` });
1566
- } else {
1567
- store.update(m.id, { title: edit.title, content: edit.content });
1568
- }
1569
- const merged = store.getById(m.id);
1570
- scheduleEmbed(merged);
1571
- result.push(merged);
1572
- }
1573
- }
1574
- return result;
1575
- }
1576
-
1577
- /**
1578
- * Re-render the human-editable mirror after any store mutation, merging any
1579
- * in-flight human edits first (never silently overwriting them). Only
1580
- * non-forgotten memories are mirrored: forgotten entries must not reach the
1581
- * human-editable file (a human "edit" could otherwise resurrect them).
1582
- */
1583
- // syncMirror: 同步 mirror,并在失败/成功时持久记录 dirty 状态;保证自身不抛出。
1584
- // v0.3.6(audit peer 4 阻断):
1585
- // - 开始时 incrementGeneration 绑定本次期望轮次 gen;成功用
1586
- // markMirrorCleanForGeneration(gen, now) CAS/fence 清 dirty——旧 worker
1587
- // (gen 已过期)不会误清另一 worker 未恢复的故障债务;
1588
- // - 失败写 markMirrorDirty(递增 desired 绑定新债务),下次 recover 恢复;
1589
- // - 逐 type 用 setTypeStatus 记录部分成功/失败(type_status JSON);
1590
- // - 所有 store 状态写入各自 try/catch,失败只 warn,绝不向外抛(F-NEW-03)。
1591
- function syncMirror() {
1592
- if (txDepth > 0 || !mirror) return { success: true, deferred: true }; // deferred to the transaction's commit
1593
- const now = new Date().toISOString();
1594
- let gen;
1595
- try {
1596
- // desired generation 已在业务写事务中原子递增(peer blocker 1);这里
1597
- // 直接读当前值作为本次同步的目标轮次,不再自行 incrementGeneration。
1598
- const state = store.getMirrorState();
1599
- gen = state?.generation ?? 0;
1600
- } catch (stateError) {
1601
- logger?.warn?.("syncMirror: getMirrorState failed:", stateError);
1602
- return { success: false, error: stateError?.message ?? String(stateError) };
1603
- }
1604
- // coveredTypes 提到 try 外初始化:即使 store.list 先抛错,catch 分支也有
1605
- // 合法的空 Set 可迭代,保证 syncMirror 自身绝不抛(fail-safe)。
1606
- const coveredTypes = new Set();
1607
- try {
1608
- // 预先获取本次要覆盖的 type 集合(只调一次 store.list)
1609
- const list = store.list({ limit: 500, includeForgotten: false });
1610
- for (const memory of list) {
1611
- if (memory?.type && TYPE_FILE[memory.type]) {
1612
- coveredTypes.add(memory.type);
1613
- }
1614
- }
1615
-
1616
- // Per-type physical outcome (audit peer D): mirror.sync writes each type
1617
- // file independently and reports per-type success/failure. A type whose
1618
- // file was physically committed must be marked committed even when a
1619
- // sibling type errors — the old code batch-failed every type on any error,
1620
- // leaving committed files mislabeled as failed and masking partial state.
1621
- // Absent entries (a type with no memories) count as success: sync prunes
1622
- // the stale file, which is itself a completed physical state.
1623
- let allOk = true;
1624
- const results = mirror.sync(reconcileHumanEdits(list)) ?? {};
1625
- for (const type of Object.keys(TYPE_FILE)) {
1626
- const r = results[type];
1627
- const ok = !r || r.ok === true;
1628
- if (!ok) allOk = false;
1629
- try {
1630
- if (ok) {
1631
- store.setTypeStatus(type, { status: "committed", applied_gen: gen, last_error: null });
1632
- } else {
1633
- store.setTypeStatus(type, { status: "failed", last_error: r.error ?? "mirror sync failed" });
1634
- }
1635
- } catch (stateError) {
1636
- logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1637
- }
1638
- }
1639
-
1640
- // 全部 type 物理收敛:CAS/fence 绑定到本地 gen,旧 worker(gen 已过期)会被
1641
- // 拦截。此步失败说明核心 clean 状态没写成功,向上层报失败(不再静默)。
1642
- if (allOk) {
1643
- try {
1644
- store.markMirrorCleanForGeneration(gen, now);
1645
- } catch (stateError) {
1646
- logger?.warn?.("syncMirror: markMirrorCleanForGeneration failed:", stateError);
1647
- return { success: false, error: stateError?.message ?? String(stateError) };
1648
- }
1649
- return { success: true };
1650
- }
1651
-
1652
- // 部分 type 失败:持久 dirty(债务绑定到新轮次),下次 recover 只补未收敛
1653
- // 的 type。committed 的 type 已应用本轮 gen,不因兄弟失败被回滚。
1654
- const failedTypes = Object.entries(results)
1655
- .filter(([, r]) => r && r.ok === false)
1656
- .map(([t]) => t);
1657
- try {
1658
- store.markMirrorDirty(`mirror sync failed for: ${failedTypes.join(", ")}`, now);
1659
- } catch (stateError) {
1660
- logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1661
- }
1662
- return { success: false, error: `mirror sync failed for: ${failedTypes.join(", ")}` };
1663
- } catch (error) {
1664
- const errMsg = error?.message ?? String(error);
1665
- logger?.warn?.("syncMirror failed:", error);
1666
- try {
1667
- // 债务绑定到新的一轮(desired generation 原子递增;即便 dirty 写失败,
1668
- // generation 已推进,recoverMirror 仍能捕获,不产生 false-clean)。
1669
- store.markMirrorDirty(errMsg, now);
1670
- } catch (stateError) {
1671
- logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1672
- }
1673
- // 逐 type 标记为 failed(applied_gen 不动)
1674
- for (const type of coveredTypes) {
1675
- try {
1676
- store.setTypeStatus(type, { status: "failed", last_error: errMsg });
1677
- } catch (stateError) {
1678
- logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1679
- }
1680
- }
1681
- return { success: false, error: errMsg };
1682
- }
1683
- }
1684
-
1685
- // afterSync: run syncMirror and surface a failure to the operator instead of
1686
- // swallowing it (peer blocker 2 + audit peer B). The mirror debt has already
1687
- // been persisted by markMirrorDirty inside syncMirror, so a restart recovers —
1688
- // but the calling write path must not report clean while the mirror is
1689
- // known-stale. Returns the sync result so the caller can attach an explicit
1690
- // degraded/pending receipt to its return value instead of faking success.
1691
- function afterSync(label) {
1692
- const r = syncMirror();
1693
- if (!r?.success && !r?.deferred) {
1694
- logger?.warn?.(`${label}: mirror sync failed (will recover on restart):`, r?.error);
1695
- }
1696
- return r;
1697
- }
1698
-
1699
- // recoverMirror: 启动/手动 reconcile 时根据持久 dirty 状态决定是否恢复同步
1700
- // (F-NEW-03 + v0.3.6)。触发条件不只是 dirty——还检查
1701
- // generation > applied_generation(有未应用的债务),这样 COMMIT→dirty 崩溃
1702
- // 窗口(DB 提交后、markMirrorDirty/clean 前进程退出 → dirty=false 但
1703
- // generation 不一致)也能被捕获。有界重试(最多 3 次)重跑 syncMirror 收敛;
1704
- // 某次成功后 dirty=false 且无更新债务(generation <= applied_generation)
1705
- // 立即停止。返回 { recovered, error } 供 index.js 启动 / api.js health 判断。
1706
- // 一切 fail-safe,绝不向外抛。
1707
- function recoverMirror() {
1708
- const MAX_ATTEMPTS = 3;
1709
- let lastError = null;
1710
- let recovered = false;
1711
-
1712
- try {
1713
- const state = store.getMirrorState();
1714
- // 崩溃窗口检测:dirty 或 generation > applied_generation(COMMIT→dirty 窗口)
1715
- if (!state?.dirty && !(state.generation > state.applied_generation)) {
1716
- // 本来就干净:无需恢复,视为成功
1717
- return { recovered: true, error: null };
1718
- }
1719
-
1720
- // 有 dirty 或有未应用债务:最多尝试 3 次 sync
1721
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
1722
- try {
1723
- syncMirror(); // syncMirror 内部已 catch,不会向外抛
1724
- const currentState = store.getMirrorState();
1725
- // 成功条件:dirty 为 false 且没有更新一轮的债务
1726
- // (generation <= applied_generation,恢复后由 syncMirror 里
1727
- // markMirrorCleanForGeneration 自动把 applied 跟上)
1728
- if (!currentState?.dirty && currentState.generation <= currentState.applied_generation) {
1729
- recovered = true;
1730
- lastError = null;
1731
- break;
1732
- }
1733
- // 仍 dirty 或仍有更新债务:记录最后一次错误供重试耗尽后上报。
1734
- // 注意:若别的 worker 又失败产生新债务(dirty 仍 true),这是"新债务"
1735
- // 不是本次失败,继续重试直到耗尽次数。
1736
- lastError = currentState.last_error || `Sync attempt ${attempt + 1} left mirror dirty or has pending debt`;
1737
- } catch (syncError) {
1738
- // syncMirror 理论不抛,fail-safe 兜底
1739
- const errMsg = syncError?.message ?? String(syncError);
1740
- logger?.warn?.("recoverMirror: sync attempt failed:", errMsg);
1741
- lastError = errMsg;
1742
- }
1743
- }
1744
-
1745
- if (!recovered) {
1746
- logger?.warn?.("dsh-mneme mirror: recover failed after", MAX_ATTEMPTS, "attempts");
1747
- } else {
1748
- logger?.warn?.("dsh-mneme mirror: recovered from dirty/pending state");
1749
- }
1750
- } catch (error) {
1751
- // fail-safe:任何意外异常不向外抛
1752
- lastError = error?.message ?? String(error);
1753
- logger?.warn?.("dsh-mneme mirror: recover failed with unexpected error:", error);
1754
- }
1755
-
1756
- return { recovered, error: recovered ? null : lastError };
1757
- }
1758
-
1759
- // getMirrorHealth: 暴露 mirror 同步健康状态,供 api.js /health 使用
1760
- // (F-NEW-03)。把 DB 的 dirty 0/1 转成 boolean;fail-safe,绝不向外抛。
1761
- function getMirrorHealth() {
1762
- try {
1763
- const state = store.getMirrorState();
1764
- if (!state) {
1765
- // 无状态行:返回安全默认值
1766
- return {
1767
- dirty: false,
1768
- last_error: null,
1769
- last_attempt: null,
1770
- success_at: null
1771
- };
1772
- }
1773
- return {
1774
- dirty: Boolean(state.dirty),
1775
- last_error: state.last_error ?? null,
1776
- last_attempt: state.last_attempt ?? null,
1777
- success_at: state.success_at ?? null
1778
- };
1779
- } catch (error) {
1780
- // fail-safe:状态读取失败也不向外抛,但必须显式表达"未知"而非伪装成
1781
- // 干净(peer blocker 5:真实读取失败要显式 unknown,不得归一为 dirty:false)。
1782
- logger?.warn?.("getMirrorHealth failed:", error);
1783
- return {
1784
- dirty: null,
1785
- last_error: error?.message ?? String(error),
1786
- last_attempt: null,
1787
- success_at: null
1788
- };
1789
- }
1790
- }
1791
-
1792
- // 返回字面量与内部裁决器(resolveConflictPending → applyDecisions 的 conflict
1793
- // 处置)共用的写路径:mirror 同步、写通知、嵌入调度全部同源,不能各写一份。
1794
- function updateMemory(id, p, ctx = {}) {
1795
- const old = store.getById(id);
1796
- // Issue #135 附属发现 2:质量过滤器把「为什么被降权/归档」写在系统信号标签
1797
- // 上(SIGNAL_TAGS,applyQualityDisposition 以并集写入),而这里整组替换
1798
- // tags——任何带 tags 的更新都会抹掉这条唯一的审计线索(报告实测 150 条低分
1799
- // 记忆里恰好缺的 2 条就是被 update 过的,并因此误判过归档来源)。把 existing
1800
- // 的系统信号标签并集保留;用户自传的标签照常生效。
1801
- let patch = (p && Array.isArray(p.tags) && old && Array.isArray(old.tags))
1802
- ? { ...p, tags: [...new Set([...p.tags, ...old.tags.filter((t) => SIGNAL_TAGS.includes(t))])] }
1803
- : p;
1804
- // v0.8.1 底座(issue #170):显式 scope 修正。patch 携带 agent_scope /
1805
- // workspace_scope 键(undefined=该维不动)时归一化并盖 explicit 章 +
1806
- // scope_decided_at,随后写 scope_changes 审计行(actor:tool=模型侧 /
1807
- // panel=人工侧)。审计失败只 warn,不反噬主写入。
1808
- const nextAgentScope = p && p.agent_scope !== undefined ? normalizeExplicitScope(p.agent_scope) : undefined;
1809
- const nextWorkspaceScope = p && p.workspace_scope !== undefined ? normalizeExplicitScope(p.workspace_scope) : undefined;
1810
- const scopeChanged = nextAgentScope !== undefined || nextWorkspaceScope !== undefined;
1811
- if (scopeChanged) {
1812
- const decidedAt = new Date().toISOString();
1813
- patch = { ...patch };
1814
- if (nextAgentScope !== undefined) {
1815
- patch.agent_scope = nextAgentScope;
1816
- patch.agent_scope_source = "explicit";
1817
- }
1818
- if (nextWorkspaceScope !== undefined) {
1819
- patch.workspace_scope = nextWorkspaceScope;
1820
- patch.workspace_scope_source = "explicit";
1821
- }
1822
- patch.scope_decided_at = decidedAt;
1823
- }
1824
- const updated = store.update(id, patch);
1825
- if (scopeChanged && old && updated) {
1826
- try {
1827
- store.saveScopeChange({
1828
- memory_id: id,
1829
- actor: ctx.actor === "panel" ? "panel" : "tool",
1830
- prev_agent_scope: old.agent_scope ?? null,
1831
- prev_workspace_scope: old.workspace_scope ?? null,
1832
- next_agent_scope: updated.agent_scope ?? null,
1833
- next_workspace_scope: updated.workspace_scope ?? null,
1834
- agent_scope_source: updated.agent_scope_source ?? null,
1835
- workspace_scope_source: updated.workspace_scope_source ?? null,
1836
- decided_at: patch.scope_decided_at
1837
- });
1838
- } catch (e) {
1839
- try { ctx.logger?.warn?.(`[dsh-mneme] scope change audit failed: ${String(e)}`); } catch { /* 同样不反噬 */ }
1840
- }
1841
- }
1842
- // Record a user correction when any meaningful field changed and the
1843
- // reflection failure tracker is enabled. expected = what it became,
1844
- // actual = what it was before; query (when provided) captures the
1845
- // user's original intent so later reflection can reason about recall.
1846
- const hasMeaningfulChange = old && updated && (
1847
- old.content !== updated.content ||
1848
- old.title !== updated.title ||
1849
- old.importance !== updated.importance
1850
- );
1851
- if (hasMeaningfulChange && config.reflectionFailureTracking) {
1852
- store.saveFailure({
1853
- id: randomUUID(),
1854
- query: ctx.query ?? null,
1855
- expected: updated.content,
1856
- actual: old.content,
1857
- before: { title: old.title, content: old.content, importance: old.importance },
1858
- failure_type: "user_correction",
1859
- memory_id: id
1860
- });
1861
- }
1862
- const sync = afterSync("write");
1863
- notifyWrite();
1864
- scheduleEmbed(updated);
1865
- // Audit peer B: when the mirror sync failed, the store write landed but
1866
- // the mirror did not converge — return an explicit degraded receipt rather
1867
- // than a plain success. Non-enumerable so existing deepEqual assertions on
1868
- // the memory shape keep passing.
1869
- if (!sync?.success && !sync?.deferred) {
1870
- Object.defineProperty(updated, "_mirror", {
1871
- value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1872
- enumerable: false,
1873
- configurable: true
1874
- });
1875
- }
1876
- return updated;
1877
- }
1878
-
1879
- function archiveMemory(id, f) {
1880
- const updated = store.setArchived(id, f);
1881
- afterSync("write");
1882
- return updated;
1883
- }
1884
-
1885
- return {
1886
- saveWithDedupe,
1887
- recoverMirror,
1888
- getMirrorHealth,
1889
- getMirrorState: () => store.getMirrorState(),
1890
- injectCandidates,
1891
- mergeHumanEdits,
1892
- toApiList,
1893
- isVisibleInScope,
1894
- transaction,
1895
- enqueue,
1896
- setDreamHook(fn) { dreamHook = fn; },
1897
- setSleepHook(fn) { sleepHook = fn; },
1898
- setEmbedder(emb) {
1899
- embedder = emb;
1900
- if (!emb) {
1901
- // embedder removed (init failed in index.js): stop polling and drop
1902
- // queued re-embeds — search just degrades to keyword.
1903
- stopEmbedReadyPolling();
1904
- embedPending = [];
1905
- return;
1906
- }
1907
- if (emb.ready === true) {
1908
- flushEmbedPending();
1909
- return;
1910
- }
1911
- // Async-initializing embedder: poll `ready` until it flips, then flush.
1912
- if ("ready" in emb && embedReadyTimer === null) {
1913
- let attempts = 0;
1914
- embedReadyTimer = setInterval(() => {
1915
- attempts++;
1916
- if (emb.ready === true || attempts >= EMBED_READY_POLL_LIMIT) {
1917
- stopEmbedReadyPolling();
1918
- if (emb.ready === true) flushEmbedPending();
1919
- else embedPending = []; // init never landed: drop the queue
1920
- }
1921
- }, EMBED_READY_POLL_MS);
1922
- }
1923
- },
1924
- setEntityExtractor(fn) { entityExtractor = fn; },
1925
- setVectorIndex(vi) { vectorIndex = vi; },
1926
- setReranker(rn) { reranker = rn; },
1927
- setRecallRecorder(fn) { recallRecorder = fn; },
1928
- searchMemories,
1929
- embedQuery,
1930
- findSessionDuplicate,
1931
- evaluateRetrieval,
1932
- computeRetrievalMetrics,
1933
- // passthroughs used by tools and api layers; mutations keep the mirror in sync
1934
- search: (q, o) => store.search(q, o),
1935
- searchVector: (v, o) => store.searchVector(v, o),
1936
- embeddedCount: () => store.embeddedCount(),
1937
- list: (o) => store.list(o),
1938
- all: () => store.all(),
1939
- count: (type, opts) => store.count(type, opts),
1940
- getById: (id) => store.getById(id),
1941
- remove: (id) => {
1942
- store.remove(id);
1943
- afterSync("write");
1944
- notifyWrite();
1945
- },
1946
- update: updateMemory,
1947
- // v0.8.1 底座:scope 归属修正审计(单条记忆,新→旧)。
1948
- listScopeChanges: (memoryId, opts) => store.listScopeChanges(memoryId, opts),
1949
- // Compare-and-set update: applies the patch only when the row still carries
1950
- // `expectedUpdatedAt`. Returns undefined on a miss (no write) so the caller
1951
- // can re-read and retry — the primitive that prevents lost updates across
1952
- // concurrent read-modify-write (see scripts/stress-dsh.js axis 3).
1953
- compareAndUpdate: (id, expectedUpdatedAt, patch, ctx = {}) => {
1954
- const old = store.getById(id);
1955
- const updated = store.compareAndUpdate(id, expectedUpdatedAt, patch);
1956
- if (updated === undefined) return undefined; // CAS miss: no write, no side effects
1957
- const hasMeaningfulChange = old && updated && (
1958
- old.content !== updated.content ||
1959
- old.title !== updated.title ||
1960
- old.importance !== updated.importance
1961
- );
1962
- if (hasMeaningfulChange && config.reflectionFailureTracking) {
1963
- store.saveFailure({
1964
- id: randomUUID(),
1965
- query: ctx.query ?? null,
1966
- expected: updated.content,
1967
- actual: old.content,
1968
- before: { title: old.title, content: old.content, importance: old.importance },
1969
- failure_type: "user_correction",
1970
- memory_id: id
1971
- });
1972
- }
1973
- const sync = afterSync("write");
1974
- notifyWrite();
1975
- scheduleEmbed(updated);
1976
- // Audit peer B: mirror sync failure on a CAS write must surface too.
1977
- if (!sync?.success && !sync?.deferred) {
1978
- Object.defineProperty(updated, "_mirror", {
1979
- value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1980
- enumerable: false,
1981
- configurable: true
1982
- });
1983
- }
1984
- return updated;
1985
- },
1986
- setForget: (id, f) => {
1987
- const updated = store.setForget(id, f);
1988
- afterSync("write");
1989
- return updated;
1990
- },
1991
- setArchived: archiveMemory,
1992
- // sleep-mode storage (v0.4.0). demoteToSummary / restoreContent mutate
1993
- // content so they ride the normal write-hook path (mirror re-renders).
1994
- // touchLastAccess is a read-stamp — deliberately NO write hook (a recall
1995
- // must not dirty the mirror). getUnrecalledSince is a pure read.
1996
- demoteToSummary: (id, summary, opts) => {
1997
- const updated = store.demoteToSummary(id, summary, opts);
1998
- afterSync("write");
1999
- return updated;
2000
- },
2001
- restoreContent: (id) => {
2002
- const updated = store.restoreContent(id);
2003
- afterSync("write");
2004
- return updated;
2005
- },
2006
- touchLastAccess: (id, at) => store.touchLastAccess(id, at),
2007
- getUnrecalledSince: (cutMs, opts) => store.getUnrecalledSince(cutMs, opts),
2008
- // autoDream audit trail: passthroughs deliberately bypass write hooks —
2009
- // an audit write is bookkeeping, and notifyWrite would loop back into the
2010
- // dream scheduler that just recorded the run.
2011
- saveDreamRun: (run) => store.saveDreamRun(run),
2012
- getDreamRun: (id) => store.getDreamRun(id),
2013
- listDreamRuns: (opts) => store.listDreamRuns(opts),
2014
- // Per-record receipt chain (same bookkeeping semantics as saveDreamRun: an
2015
- // audit write, never a write-hook-triggering memory mutation).
2016
- saveReceipt: (r) => store.saveReceipt(r),
2017
- getReceipt: (id) => store.getReceipt(id),
2018
- listReceipts: (opts) => store.listReceipts(opts),
2019
- // Conflict freeze bookkeeping (same semantics as the audit passthroughs
2020
- // above: an audit write, never a write-hook-triggering memory mutation).
2021
- saveConflictPending: (r) => store.saveConflictPending(r),
2022
- listConflictPending: (opts) => store.listConflictPending(opts),
2023
- listConflictQueue,
2024
- resolveConflictPending,
2025
- countConflictPending: () => store.countConflictPending(),
2026
- // Recall evaluation trail (方案 B): audit-bookkeeping semantics like the
2027
- // dream/recall passthroughs above — a recall_evals write is a snapshot, not
2028
- // a memory mutation, so it never triggers write hooks.
2029
- saveRecallEval: (r) => store.saveRecallEval(r),
2030
- getRecallEval: (id) => store.getRecallEval(id),
2031
- listRecallEvals: (opts) => store.listRecallEvals(opts),
2032
- // LLM audit trail (Bug8): bookkeeping semantics like the recall/dream
2033
- // passthroughs — a saveLlmAudit write never triggers write hooks.
2034
- saveLlmAudit: (entry) => store.saveLlmAudit(entry),
2035
- listLlmAudits: (opts) => store.listLlmAudits(opts),
2036
- countLlmAudits: (opts) => store.countLlmAudits(opts),
2037
- getLlmAuditStats: (opts) => store.getLlmAuditStats(opts),
2038
- deleteOldLlmAudits: (before) => store.deleteOldLlmAudits(before),
2039
- // Entity gene (v0.3.0) passthroughs for the autoDream apply path
2040
- // (applyDecisions): records supersedes relations after an update and
2041
- // migrates entity_attrs on merge. Bookkeeping writes like the audit
2042
- // passthroughs above — never write-hook-triggering memory mutations.
2043
- saveRelation: (r) => store.saveRelation(r),
2044
- listEntities: (o) => store.listEntities(o),
2045
- getRelations: (id) => store.getRelations(id),
2046
- // v0.7.0 实体热投影:实体热 = 关联记忆 heat 聚合(取 max)。无关联记忆
2047
- // 或 heatEnabled=false 时返回 null;前端据此决定图谱节点大小/明暗。
2048
- entityHeat: (entityId) => {
2049
- if (config.heatEnabled === false) return null;
2050
- const rels = store.getRelations(entityId) ?? [];
2051
- let max = -Infinity;
2052
- for (const rel of rels) {
2053
- if (!rel.memory_id) continue;
2054
- const mem = store.getById(rel.memory_id);
2055
- if (!mem) continue;
2056
- const h = computeHeat(mem, Date.now(), config);
2057
- if (h > max) max = h;
2058
- }
2059
- return max === -Infinity ? null : max;
2060
- },
2061
- saveAttr: (r) => store.saveAttr(r),
2062
- createEntity: (r) => store.createEntity(r),
2063
- findEntityByName: (n) => store.findEntityByName(n),
2064
- findEntityById: (id) => store.findEntityById(id),
2065
- getAttrsByMemory: (id) => store.getAttrsByMemory(id),
2066
- // 记忆详情侧栏:一条记忆关联到的实体(entity_attrs.memory_id 反查,纯读)。
2067
- entitiesForMemory: (id) => store.entitiesForMemory(id),
2068
- getCurrentAttrs: (id) => store.getCurrentAttrs(id),
2069
- migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
2070
- };
2071
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { TYPE_FILE } from "./mirror.js";
3
+ import { updatedAtBounds } from "./store.js";
4
+ import { normalizeExplicitScope, scopeKeyOf } from "./scope.js";
5
+ import { STR, langOf } from "./lang.js";
6
+ import { computeHeat } from "./heat.js";
7
+ import { recallStats } from "./recall-stats.js";
8
+ import { evaluateMemoryQuality } from "./quality-filter.js";
9
+ import { applyDecisions } from "./dream/decisions.js";
10
+ import { createBM25Index } from "./search/bm25.js";
11
+ import { adaptiveThreshold } from "./search/adaptive.js";
12
+
13
+ const INJECT_TYPES = new Set(["preference", "project", "decision", "summary", "rejected_solution", "pitfall", "constraint"]);
14
+
15
+ // 编码记忆类型(codingRetrospect):rejected_solution / pitfall / constraint
16
+ // 只在编码任务时注入(防噪声污染其他业务),且编码场景下按 codingBoostFactor
17
+ // 加权排序提前。
18
+ const CODING_MEMORY_TYPES = new Set(["rejected_solution", "pitfall", "constraint"]);
19
+
20
+ /**
21
+ * 判断一段文本是否编码类任务(关键词匹配,codingRetrospect 读取侧门控)。
22
+ * 纯函数,无副作用,便于单测。
23
+ */
24
+ export function isCodingTask(text, keywords = []) {
25
+ const t = String(text ?? "").toLowerCase();
26
+ return keywords.some((kw) => t.includes(String(kw).toLowerCase()));
27
+ }
28
+
29
+ // Epistemic trust weights (v0.4.5): when config.trustEpistemicWeighting is on,
30
+ // each recall candidate's existing score is multiplied by the weight of its
31
+ // epistemic_status before ranking — measured facts outrank guesses. Missing /
32
+ // unknown statuses are unscaled (×1). Off by default, so nothing changes.
33
+ const EPISTEMIC_WEIGHTS = { observation: 1.0, inferred: 0.85, subjective: 0.7 };
34
+
35
+ // Bug5: content version history cap (FIFO — the newest 20 versions are kept,
36
+ // older ones dropped). Entries are {content, source, updated_at}; source marks
37
+ // how the version was superseded (auto_merge | human_override | overwrite).
38
+ const CONTENT_HISTORY_MAX = 20;
39
+
40
+ // Issue #135 附属发现 2:质量过滤器写下的系统信号标签(「为什么被降权/归档」的
41
+ // 唯一审计线索)。更新路径整组替换 tags 会把它们抹掉——更新时按此清单并集保留。
42
+ // 清单必须与 quality-filter.js 的写入端对齐(6 个,含 type 自指的 self_referential)。
43
+ const SIGNAL_TAGS = ["low_quality", "duplicate", "meta", "repetitive", "short_content", "self_referential"];
44
+
45
+ // scopeKeyOf 已上提到 ./scope.js(v0.8.1,issue #170 第 2 步):与 sleep 的跨
46
+ // scope 配对共用同一把比较钥匙,避免两处定义漂移。
47
+
48
+ // v0.8.0 A2(issue #17)scope 检索加权系数:两维都无法确立 foreign 的候选
49
+ // (命中行、未标注行、当前侧维度解析不到的行)→ 加成;只有确立了 foreign
50
+ // (记忆带标注 + 当前维度可解析 + 值不等)→ 降权但保留可见(硬过滤是 A3
51
+ // strictScope)。即未标注行与命中行同列、不吃惩罚,但注意它们吃的是 BOOST
52
+ // 而非 ×1 中性。系数是模块常量而非配置项:A2 只定性行为,数值要等线上检索
53
+ // 质量反馈再调(加配置面=提前优化)。
54
+ const SCOPE_MATCH_BOOST = 1.25;
55
+ const SCOPE_FOREIGN_PENALTY = 0.5;
56
+
57
+ /**
58
+ * 单条候选的 scope 乘数。匹配语义与去重键一致(scopeKeyOf):记忆侧未标注视同
59
+ * 该维度命中(全局记忆对谁都可见);当前会话侧某维度解析不到则该维度不参与
60
+ * 比较(无法比较 ≠ 不匹配)。
61
+ */
62
+ function scopeMultiplier(m, current) {
63
+ const agentForeign = scopeKeyOf(m.agent_scope) !== null
64
+ && current.agent_scope !== null
65
+ && scopeKeyOf(m.agent_scope) !== current.agent_scope;
66
+ const workspaceForeign = scopeKeyOf(m.workspace_scope) !== null
67
+ && current.workspace_scope !== null
68
+ && scopeKeyOf(m.workspace_scope) !== current.workspace_scope;
69
+ return (agentForeign || workspaceForeign) ? SCOPE_FOREIGN_PENALTY : SCOPE_MATCH_BOOST;
70
+ }
71
+
72
+ /**
73
+ * v0.8.0 A2:occurred_at 后置过滤谓词(搜索融合池用)。行侧取
74
+ * COALESCE(occurred_at, created_at)——与 store.list 的 SQL 过滤同口径,未标注
75
+ * 行回退创建时间;时间戳损坏的行保留(宁可放宽也不误杀,同 summarize inWindow)。
76
+ */
77
+ function inOccurredBounds(m, bounds) {
78
+ const t = Date.parse(String(m.occurred_at ?? m.created_at ?? ""));
79
+ if (!Number.isFinite(t)) return true;
80
+ if (bounds.from && t < Date.parse(bounds.from)) return false;
81
+ if (bounds.to && t > Date.parse(bounds.to)) return false;
82
+ return true;
83
+ }
84
+
85
+ /**
86
+ * v0.8.0 A3(issue #17)strictScope 可见性谓词:issue 的四象限可见性公式
87
+ * (agent 不对称可见性)——记忆对当前会话可见 ⇔ (agent 维:未标注 或 命中当前
88
+ * agent) AND (workspace 维:未标注 或 命中当前 workspace)。NULL=未标注=全局;
89
+ * 当前会话某维度解析不到时,该维度带标注的记忆一律不可见(fail-closed:身份
90
+ * 不明的会话只见全局,不冒认)。sensitivity 是标签不参与可见性判定(其语义
91
+ * 留给后续批次)。store.list 的 SQL 过滤与此谓词同口径(见 store.js visibility)。
92
+ */
93
+ function isVisibleInScope(m, current) {
94
+ // v0.8.1 第 3 步(issue #170 4.3,作者已确认):硬过滤只认显式声明。某维
95
+ // 仅当「该维有标注且来源为 explicit」才构成硬墙;auto(含 v0.8.0 存量的
96
+ // NULL 来源行)只吃 A2 软加权(foreign ×0.5 保留可见),不进硬过滤。
97
+ // 显式全局(值 NULL + source explicit)与未标注同形,天然恒可见。
98
+ if (m.agent_scope_source === "explicit") {
99
+ const agent = scopeKeyOf(m.agent_scope);
100
+ if (agent !== null && (current.agent_scope === null || agent !== current.agent_scope)) return false;
101
+ }
102
+ if (m.workspace_scope_source === "explicit") {
103
+ const ws = scopeKeyOf(m.workspace_scope);
104
+ if (ws !== null && (current.workspace_scope === null || ws !== current.workspace_scope)) return false;
105
+ }
106
+ return true;
107
+ }
108
+
109
+ /** Prepend the previous content to a memory's content_history (FIFO capped). */
110
+ function pushContentHistory(existing, source) {
111
+ const history = Array.isArray(existing?.content_history) ? existing.content_history : [];
112
+ return [
113
+ { content: existing?.content ?? "", source, updated_at: new Date().toISOString() },
114
+ ...history
115
+ ].slice(0, CONTENT_HISTORY_MAX);
116
+ }
117
+
118
+ /** Bug5: same-title merge appends the new content under a timestamped `---`
119
+ * separator instead of overwriting, so a re-noted memory never loses history.
120
+ * The `---` line is compatible with the mirror's readHumanEdits (which strips
121
+ * only the LAST structural `---` when parsing the human-editable file). */
122
+ function appendContent(oldContent, newContent) {
123
+ const ts = new Date().toISOString();
124
+ return `${oldContent}\n\n---\n[${ts}] ${newContent}`;
125
+ }
126
+
127
+ /**
128
+ * Standard retrieval-quality metrics over the ordered candidate ids actually
129
+ * returned vs the ids the evaluator marked relevant (方案 B). Pure + total, so
130
+ * callers (and tests) get deterministic numbers without touching a store:
131
+ * precision = |relevant ∩ retrieved| / |retrieved|
132
+ * recall = |relevant ∩ retrieved| / |expected|
133
+ * mrr = 1 / rank of the first relevant doc (0 when none retrieved)
134
+ * hit_count is the raw intersection size. Values are rounded to 4 decimals so
135
+ * repeated divisions (e.g. 1/3) never surface binary-float noise.
136
+ */
137
+ export function computeRetrievalMetrics(actualIds, expectedIds) {
138
+ const expected = new Set(Array.isArray(expectedIds) ? expectedIds : []);
139
+ const actual = Array.isArray(actualIds) ? actualIds : [];
140
+ const relevant = actual.filter((id) => expected.has(id)).length;
141
+ const round4 = (x) => Math.round(x * 10000) / 10000;
142
+ let mrr = 0;
143
+ for (let i = 0; i < actual.length; i++) {
144
+ if (expected.has(actual[i])) { mrr = 1 / (i + 1); break; }
145
+ }
146
+ return {
147
+ precision: round4(actual.length ? relevant / actual.length : 0),
148
+ recall: round4(expected.size ? relevant / expected.size : 0),
149
+ mrr: round4(mrr),
150
+ hit_count: relevant
151
+ };
152
+ }
153
+
154
+ export function createService({ store, mirror, config, onWrite, logger }) {
155
+ const language = langOf(config);
156
+ // Optional dream scheduler hook, installed via setDreamHook after creation
157
+ // (the scheduler holds a reference back to the service, so it cannot be
158
+ // passed in the constructor). Fired on the same write events as onWrite.
159
+ let dreamHook = null;
160
+
161
+ // Optional sleep scheduler hook (v0.4.0), installed via setSleepHook after
162
+ // creation. Fired on the same write events as onWrite: it tells the sleep
163
+ // scheduler the store just changed so the idle-detection clock resets.
164
+ let sleepHook = null;
165
+
166
+ // Optional vector embedder, installed via setEmbedder after creation. After
167
+ // any content write it fire-and-forgets a re-embed of the row so vector
168
+ // search stays in sync; failures are swallowed inside the embedder.
169
+ let embedder = null;
170
+
171
+ // Optional entity extractor, installed via setEntityExtractor after creation
172
+ // (index.js injects it so the service never depends on the LLM directly).
173
+ // After a new memory is saved it fire-and-forgets an extraction pass for the
174
+ // entity gene (v0.3.0); failures are swallowed so a broken extraction never
175
+ // surfaces as a write failure. Extraction only runs when
176
+ // config.entityExtractionEnabled is true.
177
+ let entityExtractor = null;
178
+ let vectorIndex = null;
179
+ let reranker = null;
180
+
181
+ // Optional recall recorder, installed via setRecallRecorder after creation.
182
+ // When searchMemories is called with recordRecall=true it receives the
183
+ // actual merged recall scene (candidates + scores + source + threshold) so
184
+ // the retrieval layer can be audited/replayed — the sibling of the dream
185
+ // judgment-layer audit trail (dream_runs).
186
+ let recallRecorder = null;
187
+
188
+ // Bug4: semantic recall cache for the injection path. The system-prompt
189
+ // interpolator renders context synchronously, so injectCandidates cannot
190
+ // fire a fresh async embed. The most recent searchMemories recall is cached
191
+ // here (query + ordered candidates) and reused when the injection query
192
+ // matches, giving semantic-first injection without breaking the sync render.
193
+ let lastSemanticRecall = null;
194
+
195
+ // Transaction nesting depth. Inside service.transaction the per-mutation side
196
+ // effects (mirror render, write notify, re-embed) are deferred so a ROLLBACK
197
+ // never leaves the mirror file diverged from the database; transaction()
198
+ // replays them exactly once against the committed state.
199
+ let txDepth = 0;
200
+
201
+ // Serial task queue (sleep v0.4.0). Long-running background passes — dream
202
+ // consolidation, sleep cycles — must never overlap: two sleep runs racing
203
+ // would double-demote or double-mint patterns. enqueue chains the task onto
204
+ // a promise tail so N callers can queue work that runs strictly one at a
205
+ // time. A task that rejects doesn't poison the queue (the tail swallows the
206
+ // rejection) but the rejection still propagates to that caller.
207
+ let queueTail = Promise.resolve();
208
+ function enqueue(fn) {
209
+ const next = queueTail.then(fn, fn);
210
+ queueTail = next.catch(() => {});
211
+ return next;
212
+ }
213
+
214
+ // issue #6 (part 2): startup race defense. A local embedder (LocalEmbedder /
215
+ // Ollama) exposes an async init(), so between `setEmbedder` and init()
216
+ // resolving there is a window where embedSingle would throw "not initialized"
217
+ // and the re-embed would be silently dropped. When the embedder carries a
218
+ // `ready` flag we queue writes in embedPending until init sets ready=true,
219
+ // then flush them through the embedder's real interface. Embedders without a
220
+ // `ready` flag (legacy OpenAI, instantly usable) keep their old behavior.
221
+ let embedPending = [];
222
+ let embedReadyTimer = null;
223
+ const EMBED_PENDING_MAX = 100; // bound the queue; drop oldest beyond this
224
+ const EMBED_READY_POLL_MS = 100;
225
+ const EMBED_READY_POLL_LIMIT = 30; // ~3s ceiling; never poll forever
226
+
227
+ /** Flush the queued re-embeds once the embedder is ready. Fail-safe. */
228
+ function flushEmbedPending() {
229
+ if (!embedder || embedPending.length === 0) return;
230
+ const batch = embedPending.splice(0, embedPending.length);
231
+ for (const memory of batch) {
232
+ try {
233
+ if (!memory?.id) continue;
234
+ if (typeof embedder.schedule === "function") {
235
+ embedder.schedule(memory);
236
+ } else if (typeof embedder.embedSingle === "function") {
237
+ const text = [memory.title, memory.content].filter(Boolean).join("\n");
238
+ if (!text) continue;
239
+ embedder
240
+ .embedSingle(text)
241
+ .then((vec) => {
242
+ if (Array.isArray(vec) && vec.length) {
243
+ store.setEmbedding(memory.id, vec);
244
+ }
245
+ })
246
+ .catch((err) => {
247
+ logger?.warn?.("flushEmbedPending embedSingle failed:", err);
248
+ });
249
+ }
250
+ } catch (err) {
251
+ logger?.warn?.("flushEmbedPending failed:", err);
252
+ }
253
+ }
254
+ }
255
+
256
+ function stopEmbedReadyPolling() {
257
+ if (embedReadyTimer) {
258
+ clearInterval(embedReadyTimer);
259
+ embedReadyTimer = null;
260
+ }
261
+ }
262
+
263
+ function scheduleEmbed(memory) {
264
+ try {
265
+ if (txDepth > 0) return; // deferred to the transaction's commit
266
+ if (!embedder || !memory?.id) return;
267
+
268
+ // Readiness gate: embedder exposes `ready` (async init) and is not ready
269
+ // yet — queue instead of firing embedSingle into a half-built extractor.
270
+ const hasReady = "ready" in embedder;
271
+ if (hasReady && embedder.ready !== true) {
272
+ if (embedPending.length >= EMBED_PENDING_MAX) embedPending.shift();
273
+ embedPending.push(memory);
274
+ return;
275
+ }
276
+
277
+ if (typeof embedder.schedule === "function") {
278
+ embedder.schedule(memory);
279
+ return;
280
+ }
281
+
282
+ if (typeof embedder.embedSingle === "function") {
283
+ const text = [memory.title, memory.content].filter(Boolean).join("\n");
284
+ if (!text) return;
285
+
286
+ embedder
287
+ .embedSingle(text)
288
+ .then((vec) => {
289
+ if (Array.isArray(vec) && vec.length) {
290
+ store.setEmbedding(memory.id, vec);
291
+ }
292
+ })
293
+ .catch((err) => {
294
+ logger?.warn?.("scheduleEmbed embedSingle failed:", err);
295
+ });
296
+ }
297
+ } catch (err) {
298
+ logger?.warn?.("scheduleEmbed failed:", err);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Fire-and-forget entity extraction for a freshly saved memory (entity gene
304
+ * v0.3.0). Opt-in via config.entityExtractionEnabled; the extractor is
305
+ * injected as a hook so the service never needs a direct LLM reference.
306
+ * The hook itself is expected to resolve to { ok:boolean } and never throw;
307
+ * a thrown rejection is swallowed here as a final fail-safe.
308
+ */
309
+ function scheduleEntityExtraction(memory) {
310
+ if (txDepth > 0) return; // deferred to the transaction's commit
311
+ if (!config.entityExtractionEnabled || !entityExtractor) return;
312
+ try {
313
+ entityExtractor(memory).catch((err) => {
314
+ logger?.warn?.("entity extraction failed:", err);
315
+ });
316
+ } catch (err) {
317
+ logger?.warn?.("entity extraction failed:", err);
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Cross-encoder rerank over a candidate list (best effort). Reranker
323
+ * failures degrade to the original candidate order — reranking is an
324
+ * accuracy upgrade, never a correctness gate.
325
+ */
326
+ async function rerankCandidates(query, candidates, topK) {
327
+ if (!reranker || !candidates.length) return candidates.slice(0, topK);
328
+ try {
329
+ const scored = await reranker.rerank(query, candidates.map((c) => ({ id: c.id, title: c.title, content: c.content })));
330
+ if (!Array.isArray(scored)) return candidates.slice(0, topK);
331
+ const byId = new Map(candidates.map((c) => [c.id, c]));
332
+ const out = [];
333
+ for (const s of scored) {
334
+ const c = byId.get(s.id);
335
+ if (c) { out.push({ ...c, score: s.score, source: "rerank" }); if (out.length >= topK) break; }
336
+ }
337
+ return out.length ? out : candidates.slice(0, topK);
338
+ } catch {
339
+ return candidates.slice(0, topK);
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Search for memories attached to a named entity (v0.3.0 Phase 3).
345
+ * 合并优先级:entity_attrs.memory_id 精确关联 = 1.0 > 关键词提及 = 0.7;
346
+ * attr 命中不覆盖,keyword 只补充召回,最后按 _score 降序取 topK。
347
+ * @param {string} entityName
348
+ * @param {object} [options]
349
+ * @param {number} [options.topK=20]
350
+ * @returns {any[]}
351
+ */
352
+ function searchByEntity(entityName, { topK = 20 } = {}) {
353
+ const entity = store.findEntityByName(entityName);
354
+ if (!entity) return [];
355
+ const attrs = store.getCurrentAttrs(entity.id);
356
+ const memoryIds = [...new Set(attrs.map((a) => a.memory_id).filter(Boolean))];
357
+ const attrHits = memoryIds.map((id) => store.getById(id)).filter(Boolean);
358
+ const keywordHits = store.search(entityName, { limit: topK });
359
+ const merged = new Map();
360
+ for (const mem of attrHits) merged.set(mem.id, { ...mem, _source: "entity_attr", _score: 1.0 });
361
+ for (const mem of keywordHits) {
362
+ if (!merged.has(mem.id)) merged.set(mem.id, { ...mem, _source: "keyword", _score: 0.7 });
363
+ }
364
+ const hits = Array.from(merged.values()).sort((a, b) => b._score - a._score).slice(0, topK);
365
+ touchRecalled(hits);
366
+ return hits;
367
+ }
368
+
369
+ /**
370
+ * Search for memories by attribute key/value (v0.3.0 Phase 3).
371
+ * value 为空时由 store.findMemoriesByAttr 返回该 key 的全部有效记忆。
372
+ * @param {string} key
373
+ * @param {string | undefined} value
374
+ * @param {object} [options]
375
+ * @param {number} [options.topK=20]
376
+ * @returns {any[]}
377
+ */
378
+ function searchByAttr(key, value, { topK = 20 } = {}) {
379
+ if (!key) return [];
380
+ // value 可能为 undefined(attr:key 无 = 值):归一为空串后交给
381
+ // store.findMemoriesByAttr —— 空 value 契约 = 返回该 attr_key 的全部
382
+ // 当前有效记忆(v0.3.0,store.js 已实现)。
383
+ const rows = store.findMemoriesByAttr(key, value ?? "");
384
+ const hits = rows.slice(0, topK);
385
+ touchRecalled(hits);
386
+ return hits;
387
+ }
388
+
389
+ /**
390
+ * Semantic-aware memory search: keyword recall (store.search) plus optional
391
+ * vector recall + rerank. mode:
392
+ * auto (default) keyword first, vector fills remaining slots (legacy)
393
+ * hybrid vector first, keyword fills remaining slots
394
+ * vector vector only, falls back to keyword when unavailable
395
+ * keyword text only, never touches the embedder
396
+ * useRerank runs the cross-encoder over the merged list when a reranker is
397
+ * installed; results carry an extra `score` when reranked.
398
+ */
399
+ // Weighted blend factor for hybrid search; exposed so callers can tune it.
400
+ const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
401
+
402
+ // Cosine over two plain arrays (shared by the search-time semantic dedup).
403
+ function cosineVec(a, b) {
404
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
405
+ let dot = 0, na = 0, nb = 0;
406
+ for (let i = 0; i < a.length; i++) {
407
+ dot += a[i] * b[i];
408
+ na += a[i] * a[i];
409
+ nb += b[i] * b[i];
410
+ }
411
+ if (na === 0 || nb === 0) return 0;
412
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
413
+ }
414
+
415
+ /**
416
+ * BM25 third recall path (v0.5.0 1.1). Scores the query tokens against the
417
+ * live non-archived rows and returns the top `limit` hits with scores
418
+ * normalized to [0,1]. Failures degrade to [] — BM25 is a recall booster,
419
+ * never a correctness gate.
420
+ */
421
+ function bm25Recall(q, limit) {
422
+ if (config?.bm25SearchEnabled === false) return [];
423
+ try {
424
+ const docs = store.list({ limit: 500, includeForgotten: false }).filter((m) => !m.archived);
425
+ if (!docs.length) return [];
426
+ return createBM25Index(docs).search(q, { limit });
427
+ } catch {
428
+ return [];
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Graph fourth recall path (issue #219). When the query text mentions a
434
+ * known entity name, memories linked to that entity (attrs + relations)
435
+ * join the fusion pool as a confirm/backfill signal — same standing as
436
+ * BM25, never dominating the semantic ranking. Tier scores: attr-linked
437
+ * 1.0 (direct evidence, same source searchByEntity trusts) > relation
438
+ * edge 0.9. Archived/forgotten rows never participate. Failures degrade
439
+ * to [] — a recall booster, never a correctness gate (same contract as
440
+ * bm25Recall).
441
+ */
442
+ function entityRecall(q, limit) {
443
+ if (config?.entityRecallEnabled !== true) return [];
444
+ try {
445
+ const entities = store.findEntitiesMentionedIn(q);
446
+ if (!entities.length) return [];
447
+ const linked = store.getLinkedMemoryIds(entities.map((e) => e.id));
448
+ if (!linked.size) return [];
449
+ const hits = [];
450
+ for (const [id, tier] of linked) {
451
+ const row = store.getById(id);
452
+ if (!row || row.archived || row.forgotten) continue;
453
+ hits.push({ ...row, score: tier === "attr" ? 1.0 : 0.9, source: "entity" });
454
+ if (hits.length >= limit * 2) break;
455
+ }
456
+ return hits;
457
+ } catch {
458
+ return [];
459
+ }
460
+ }
461
+
462
+ /**
463
+ * Search-time semantic dedup (v0.5.0 2.3): greedy pass dropping candidates
464
+ * whose embedding similarity to an already-kept row exceeds the threshold.
465
+ * Rows without a stored embedding are always kept (no signal = no drop).
466
+ */
467
+ function semanticDeduplicate(candidates) {
468
+ // Opt-in aggressive mode (default off): collapsing near-duplicates can
469
+ // drop legitimately distinct rows on small embedding models, so it ships
470
+ // behind searchSemanticDedup=true.
471
+ if (config?.searchSemanticDedup !== true || candidates.length < 2) return candidates;
472
+ const threshold = config?.searchSemanticDedupThreshold ?? 0.95;
473
+ try {
474
+ const vecs = store.getEmbeddings(candidates.map((c) => c.id));
475
+ if (vecs.size < 2) return candidates;
476
+ const kept = [];
477
+ for (const c of candidates) {
478
+ const v = vecs.get(c.id);
479
+ if (!v) { kept.push(c); continue; }
480
+ const dup = kept.some((k) => {
481
+ const kv = vecs.get(k.id);
482
+ return kv && cosineVec(v, kv) > threshold;
483
+ });
484
+ if (!dup) kept.push(c);
485
+ }
486
+ return kept;
487
+ } catch {
488
+ return candidates;
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Give a keyword-hit row a relevance score in [0,1]: title hits score
494
+ * higher than content hits, then scaled by importance (1-5). This lets
495
+ * keyword results participate in weighted hybrid blends.
496
+ */
497
+ function scoreKeyword(row, q) {
498
+ const ql = q.toLowerCase();
499
+ const title = (row.title ?? "").toLowerCase();
500
+ const content = (row.content ?? "").toLowerCase();
501
+ const titleHit = title.includes(ql);
502
+ const base = titleHit ? 1 : content.includes(ql) ? 0.6 : 0.3;
503
+ return base * (0.5 + (row.importance ?? 3) / 10);
504
+ }
505
+
506
+ /**
507
+ * Recall touch (v0.4.0 sleep; v0.7.0 heat gating): any memory surfaced by
508
+ * recall or auto-injection gets its last_accessed_at bumped, so the "unrecalled
509
+ * N days → demote/archive" tiering counts real access — and the heat clock
510
+ * resets (heat ref = last_accessed_at). Best-effort and gated on
511
+ * config.heatEnabled — when heat is off this is a complete no-op (no writes
512
+ * on the hot recall path). A touch failure must never break search/inject.
513
+ */
514
+ function touchRecalled(memories) {
515
+ if (config?.heatEnabled === false || !Array.isArray(memories) || memories.length === 0) return;
516
+ for (const m of memories) {
517
+ if (!m?.id) continue;
518
+ try {
519
+ store.touchLastAccess(m.id);
520
+ } catch { /* touch is best effort */ }
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Recall fusion (plan #1). Turns the three ranked signal lists (keyword,
526
+ * vector, BM25) into a single merged list. Three recipes, selected by
527
+ * config.recallFusion:
528
+ * - blend (default): legacy behavior — weighted sum for vector/hybrid, union
529
+ * backfill for auto. Byte-identical to pre-fusion code, so enabling the
530
+ * config never regresses anybody.
531
+ * - rrf: Reciprocal Rank Fusion — Σ 1/(k + rank + 1) over each list a row
532
+ * appears in. Rank-based, so the unit mismatch (raw cosine vs keyword
533
+ * score vs normalized IDF) is irrelevant.
534
+ * - minmax: min-max normalize each source list's scores to [0,1] then take
535
+ * the weighted sum — a scale-aware version of `blend`.
536
+ * Returns { merged, signals }, where signals is Map<id, {keyword, vector,
537
+ * bm25}> so searchMemories can decorate rows when signalTransparency is on.
538
+ */
539
+ function fuseRecall({ keyword, vector, bm25, entity, lim, mode, wv, wk, wb, we }) {
540
+ const recipe = config?.recallFusion ?? "blend";
541
+
542
+ // Per-source scores are recorded for every recipe so signalTransparency
543
+ // works regardless of how the ranking was produced.
544
+ const signals = new Map();
545
+ const addSig = (id, field, sc) => {
546
+ const cur = signals.get(id) ?? {};
547
+ cur[field] = sc;
548
+ signals.set(id, cur);
549
+ };
550
+ for (const m of keyword) addSig(m.id, "keyword", m.score ?? 0);
551
+ for (const m of vector) addSig(m.id, "vector", m.score ?? 0);
552
+ for (const m of bm25) addSig(m.id, "bm25", m.score ?? 0);
553
+ for (const m of entity) addSig(m.id, "entity", m.score ?? 0);
554
+
555
+ const vectorIds = new Set(vector.map((m) => m.id));
556
+ const keywordIds = new Set(keyword.map((m) => m.id));
557
+
558
+ // Mode contract (aligns rrf/minmax with blend): keyword-only searches must
559
+ // stay keyword-only regardless of recipe, so enabling an opt-in recipe can
560
+ // never pull vector/BM25 rows into a mode="keyword" request. This mirrors
561
+ // the blend branch's `mode === "keyword"` short-circuit (byte-for-byte).
562
+ if (mode === "keyword") {
563
+ return { merged: keyword.slice(0, lim), signals };
564
+ }
565
+
566
+ let merged;
567
+ if (recipe === "rrf") {
568
+ // Rank-based: only the position of a row inside each surviving source
569
+ // list matters, so no cross-signal scale calibration is needed.
570
+ const k = 60; // standard RRF constant (plan #1 documents k=60)
571
+ const rows = new Map();
572
+ const addList = (list) => list.forEach((m, idx) => {
573
+ const s = 1 / (k + idx + 1);
574
+ const cur = rows.get(m.id);
575
+ if (cur) cur.score += s;
576
+ else rows.set(m.id, { ...m, score: s });
577
+ });
578
+ addList(keyword);
579
+ addList(vector);
580
+ addList(bm25);
581
+ addList(entity);
582
+ merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
583
+ } else if (recipe === "minmax") {
584
+ // Scale-aware weighted sum: each source list is min-max normalized to
585
+ // [0,1] before blending, so raw cosine and keyword score live on the
586
+ // same footing.
587
+ const norm = (list) => {
588
+ if (!list.length) return new Map();
589
+ let min = Infinity, max = -Infinity;
590
+ for (const m of list) { const s = m.score ?? 0; if (s < min) min = s; if (s > max) max = s; }
591
+ const range = max - min;
592
+ const out = new Map();
593
+ for (const m of list) out.set(m.id, range > 0 ? ((m.score ?? 0) - min) / range : 0.5);
594
+ return out;
595
+ };
596
+ const kw = norm(keyword), ve = norm(vector), bm = norm(bm25), en = norm(entity);
597
+ const rows = new Map();
598
+ const seed = (m) => { if (!rows.has(m.id)) rows.set(m.id, { ...m, score: 0 }); };
599
+ for (const m of keyword) seed(m);
600
+ for (const m of vector) seed(m);
601
+ for (const m of bm25) seed(m);
602
+ for (const m of entity) seed(m);
603
+ for (const [id, row] of rows) {
604
+ const k = kw.get(id) ?? 0;
605
+ const v = ve.get(id) ?? 0;
606
+ const b = bm.get(id) ?? 0;
607
+ const e = en.get(id) ?? 0;
608
+ row.score = v * wv + k * wk + b * wb + e * we;
609
+ }
610
+ merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
611
+ } else {
612
+ // blend — the pre-existing per-mode behavior, extracted verbatim.
613
+ if (mode === "keyword") {
614
+ merged = keyword;
615
+ } else if (mode === "vector" || mode === "hybrid") {
616
+ const byId = new Map();
617
+ for (const m of vector) {
618
+ const rec = byId.get(m.id);
619
+ byId.set(m.id, rec ? { ...rec, score: Math.max(rec.score ?? 0, m.score ?? 0) } : m);
620
+ }
621
+ for (const m of keyword) {
622
+ const rec = byId.get(m.id);
623
+ if (rec) {
624
+ byId.set(m.id, { ...rec, score: (rec.score ?? 0) * wv + (m.score ?? 0) * wk });
625
+ } else {
626
+ byId.set(m.id, m);
627
+ }
628
+ }
629
+ for (const m of bm25) {
630
+ const rec = byId.get(m.id);
631
+ if (rec) {
632
+ if (keywordIds.has(m.id)) continue;
633
+ byId.set(m.id, { ...rec, score: (rec.score ?? 0) + wb * (m.score ?? 0) });
634
+ } else {
635
+ byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
636
+ }
637
+ }
638
+ // Entity axis (#219): same confirm/backfill contract as BM25 —
639
+ // seen rows get a weighted bonus, unseen ids backfill at we·score.
640
+ for (const m of entity) {
641
+ const rec = byId.get(m.id);
642
+ if (rec) {
643
+ byId.set(m.id, { ...rec, score: (rec.score ?? 0) + we * (m.score ?? 0) });
644
+ } else {
645
+ byId.set(m.id, { ...m, score: we * (m.score ?? 0) });
646
+ }
647
+ }
648
+ const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
649
+ merged = ranked.slice(0, lim);
650
+ if (merged.length < lim && !merged.length) {
651
+ merged = keyword.slice(0, lim);
652
+ }
653
+ } else {
654
+ // auto: keyword leads, vector + BM25 + entity fill remaining slots.
655
+ merged = keyword.slice(0, lim);
656
+ const seen = new Set(merged.map((m) => m.id));
657
+ for (const m of vector) {
658
+ if (merged.length >= lim) break;
659
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
660
+ }
661
+ for (const m of bm25) {
662
+ if (merged.length >= lim) break;
663
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
664
+ }
665
+ for (const m of entity) {
666
+ if (merged.length >= lim) break;
667
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
668
+ }
669
+ }
670
+ }
671
+
672
+ // Mode contract, auto (aligns rrf/minmax with blend): keyword leads, the
673
+ // recipe fills the remaining slots. blend.auto already front-loads keyword;
674
+ // rrf/minmax rank across sources, so re-apply the same "keyword first"
675
+ // ordering here to preserve the pre-fusion auto contract — the keyword
676
+ // hit list keeps its power, and only slots it couldn't fill go to the
677
+ // recipe's ranking.
678
+ if (recipe !== "blend" && mode === "auto" && keyword.length) {
679
+ const head = keyword.slice(0, lim);
680
+ const seen = new Set(head.map((m) => m.id));
681
+ const tail = merged.filter((m) => !seen.has(m.id)).slice(0, Math.max(0, lim - head.length));
682
+ merged = head.concat(tail);
683
+ }
684
+
685
+ return { merged, signals };
686
+ }
687
+
688
+ /**
689
+ * Search memories for a query. Merges up to four recall sources (keyword,
690
+ * vector, BM25, and — when config.entityRecallEnabled is on — entity-linked
691
+ * memories whose entity names the query mentions; see fuseRecall) according
692
+ * to config.recallFusion (blend/rrf/minmax — see
693
+ * fuseRecall), then optionally decorates rows with per-source signals
694
+ * (config.signalTransparency), applies semantic dedup (non-keyword modes),
695
+ * reranking, and epistemic trust re-weighting, and finally hands the merged
696
+ * list to the recall-layer recorder.
697
+ *
698
+ * options:
699
+ * mode — 'auto' (default) | 'keyword' | 'vector' | 'hybrid'
700
+ * topK — max rows (default 20)
701
+ * threshold — explicit vector score floor (overrides adaptive)
702
+ * useRerank — apply the reranker if available (default true)
703
+ * recordRecall — write a recall_runs audit row (default from config)
704
+ *
705
+ * Returns an array of memory rows { id, title, content, score, source, ... },
706
+ * with `signals` added when config.signalTransparency is on. Never throws:
707
+ * a vector/rerank failure degrades to keyword results.
708
+ */
709
+ async function searchMemories(query, options = {}) {
710
+ const {
711
+ mode = "auto",
712
+ topK = 20,
713
+ threshold,
714
+ useRerank = true,
715
+ // v0.8.0 A2(issue #17):当前会话 scope(工具层从 exec 解析后传入)与
716
+ // occurred_at 时间窗。两者都只在显式传入时生效,既有调用方(注入/梦/评测)
717
+ // 不传 → 行为与 A2 前一致。
718
+ scope = null,
719
+ occurredFrom = null,
720
+ occurredTo = null,
721
+ recordRecall = options.recordRecall ?? (config?.recallRecordDefault ?? true)
722
+ } = options;
723
+ const q = String(query ?? "").trim();
724
+ if (!q) return [];
725
+
726
+ // entity:/attr: 前缀路由(v0.3.0 Phase 3)。entitySearchEnabled 关闭时走原逻辑。
727
+ if (config?.entitySearchEnabled) {
728
+ if (q.startsWith("entity:")) {
729
+ return searchByEntity(q.slice(7).trim(), options);
730
+ }
731
+ if (q.startsWith("attr:")) {
732
+ const [key, value] = q.slice(5).split("=");
733
+ return searchByAttr(key, value, options);
734
+ }
735
+ }
736
+
737
+ const lim = topK > 0 ? topK : 20;
738
+
739
+ // Keyword results, decorated with a score so they can be weight-blended
740
+ // with vector results and reported uniformly. source tracks where each
741
+ // candidate came from for the recall layer receipt.
742
+ const rawKeyword = store.search(q, { limit: lim });
743
+ const keyword = rawKeyword.map((m) => ({ ...m, score: scoreKeyword(m, q), source: "keyword" }));
744
+ const wantVector = mode === "vector" || mode === "hybrid" || (mode === "auto" && !!embedder);
745
+ let vector = [];
746
+ if (wantVector && embedder) {
747
+ try {
748
+ // Legacy embedders expose embed(query); local ones expose embedSingle.
749
+ const embedSingle = typeof embedder.embedSingle === "function"
750
+ ? embedder.embedSingle.bind(embedder)
751
+ : embedder.embed.bind(embedder);
752
+ const qv = await embedSingle(q);
753
+ if (qv?.length) {
754
+ // Adaptive threshold (v0.5.0 1.2): the fetch runs at the loosest
755
+ // branch floor so the head-gap rule can still re-admit the tail;
756
+ // the final cutoff is computed against the fetched score
757
+ // distribution. Explicit `threshold` wins; disabled → legacy 0.
758
+ const adaptive = config?.adaptiveThresholdEnabled !== false;
759
+ const fetchThreshold = adaptive && threshold === undefined
760
+ ? Math.min(0.5, adaptiveThreshold(q))
761
+ : (threshold ?? 0);
762
+ const search = vectorIndex
763
+ ? vectorIndex.search(qv, { limit: lim * 2, threshold: fetchThreshold })
764
+ : store.searchVector(qv, { limit: lim * 2, threshold: fetchThreshold });
765
+ const finalThreshold = adaptive && threshold === undefined
766
+ ? adaptiveThreshold(q, search)
767
+ : (threshold ?? 0);
768
+ vector = search
769
+ .filter((m) => (m.score ?? 1) >= finalThreshold)
770
+ .map((m) => ({ ...m, vector: true, source: "vector" }));
771
+ }
772
+ } catch { /* vector unavailable: keep keyword results */ }
773
+ }
774
+
775
+ // BM25 third path (v0.5.0 1.1): IDF-weighted token overlap recalls rows
776
+ // whose query terms are scattered — the gap LIKE substring matching
777
+ // cannot close. Scores are already normalized to [0,1].
778
+ const bm25 = bm25Recall(q, lim).map((m) => ({ ...m, source: "bm25" }));
779
+ // Loose blend weight: BM25 confirms and backfills, never dominates the
780
+ // semantic signal. Same-memory overlap boosts, unseen ids backfill.
781
+ const wb = 0.3;
782
+
783
+ // Graph fourth path (issue #219, opt-in entityRecallEnabled): query-
784
+ // mentioned entities pull their linked memories into the pool. Keyword
785
+ // mode stays text-only per the mode contract, so the axis is skipped
786
+ // there even when enabled.
787
+ const entity = mode === "keyword" ? [] : entityRecall(q, lim);
788
+ // Entity axis shares BM25's backfill weight (we = wb) until #217 recall
789
+ // data justifies a distinct entity weight.
790
+
791
+ // Hybrid blending weights from config when provided.
792
+ const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
793
+ const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
794
+
795
+ const { merged: fusedMerged, signals } = fuseRecall({ keyword, vector, bm25, entity, lim, mode, wv, wk, wb, we: wb });
796
+ let merged = fusedMerged;
797
+ // v0.8.0 A3(issue #17):strictScope 硬过滤——他 scope 的候选直接出局
798
+ // (区别于 A2 的降权保留可见);未标注行与命中行保留。strict 与 A2 加权
799
+ // 叠加:过滤后剩下的命中行仍吃加成。scope 未传(flag 关)或完全解析不到
800
+ // 时跳过——identity 为空的对象({null,null})按 fail-closed 过滤。
801
+ if (config.strictScope === true && scope) {
802
+ merged = merged.filter((m) => isVisibleInScope(m, scope));
803
+ }
804
+ // v0.8.0 A2:occurred_at 时间过滤——在融合池上先滤再 dedup/slice,rerank
805
+ // 只看窗内候选,topK 槽位不被窗外行占用。
806
+ const occurredBounds = updatedAtBounds(occurredFrom, occurredTo);
807
+ if (occurredBounds.from || occurredBounds.to) {
808
+ merged = merged.filter((m) => inOccurredBounds(m, occurredBounds));
809
+ }
810
+ // Signal transparency (#2): decorate each returned row with its per-source
811
+ // scores and the final fused score. Purely additive — never changes rank.
812
+ if (config?.signalTransparency === true) {
813
+ merged = merged.map((m) => ({ ...m, signals: { ...(signals.get(m.id) ?? {}), final: m.score ?? 0 } }));
814
+ }
815
+
816
+ // Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
817
+ // dropped before the reranker sees them, so topK slots carry distinct
818
+ // information instead of the same memory twice. Keyword mode is exempt —
819
+ // it is the documented text-only path and must not be altered by
820
+ // embedding state.
821
+ merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
822
+ merged = merged.slice(0, lim);
823
+ let result = useRerank && reranker && merged.length
824
+ ? await rerankCandidates(q, merged, lim)
825
+ : merged;
826
+ // Epistemic trust (v0.4.5): opt-in re-weighting of the final candidate
827
+ // scores by source credibility. When off (default) `result` is returned
828
+ // untouched — exactly the legacy behavior.
829
+ if (config.trustEpistemicWeighting === true) {
830
+ result = result
831
+ .map((m) => ({
832
+ ...m,
833
+ score: (m.score ?? 0) * (EPISTEMIC_WEIGHTS[m.epistemic_status] ?? 1)
834
+ }))
835
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
836
+ .slice(0, lim);
837
+ }
838
+
839
+ // v0.8.0 A2(issue #17):scope 检索加权——两维都无法确立 foreign 的候选
840
+ // (命中/未标注/当前侧解析不到)加成,确立 foreign 的候选降权但保留可见
841
+ // (硬过滤是 A3 strictScope);未标注行与命中行同列吃 BOOST、不被压制。
842
+ // flag 关或调用方未传 scope 时不动分,排序与 A2 前逐字节一致。与
843
+ // epistemic 加权同款收尾:乘分 → 降序 → 截 topK。
844
+ if (config.scopeEnabled === true && scope && (scope.agent_scope || scope.workspace_scope)) {
845
+ result = result
846
+ .map((m) => ({ ...m, score: (m.score ?? 0) * scopeMultiplier(m, scope) }))
847
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
848
+ .slice(0, lim);
849
+ }
850
+
851
+ // Recall layer receipt: with recordRecall on, hand the actual merged
852
+ // candidate list (id/title/content/score/source) to the injected recorder
853
+ // before returning, making the retrieval scene replayable — the sibling of
854
+ // the dream judgment-layer audit trail. Recorder failures must never break
855
+ // the search itself.
856
+ if (recordRecall && recallRecorder) {
857
+ try {
858
+ recallRecorder({
859
+ query: q,
860
+ mode,
861
+ topK: lim,
862
+ threshold: threshold ?? null,
863
+ candidates: result.map((m) => ({
864
+ id: m.id,
865
+ title: m.title,
866
+ content: m.content,
867
+ score: m.score ?? null,
868
+ source: m.source ?? "keyword"
869
+ })),
870
+ createdAt: new Date().toISOString()
871
+ });
872
+ } catch { /* recall receipt is best effort */ }
873
+ }
874
+ // Bug4: cache the latest semantic recall so the sync injection path can
875
+ // reuse it when the injection query matches (no async embed available).
876
+ lastSemanticRecall = { query: q, items: result };
877
+ touchRecalled(result);
878
+ return result;
879
+ }
880
+
881
+ /**
882
+ * Retrieval evaluation (方案 B): run one search for `query`, compare the ids
883
+ * it actually returned against `expectedIds`, and return the computed
884
+ * metrics. When persistence is on (config.evalPersistTestResults, or an
885
+ * explicit `persist` override per call) the snapshot is written to the
886
+ * recall_evals table — a SEPARATE store from the recall_runs production audit,
887
+ * so test/eval data never inflates the production trail.
888
+ *
889
+ * options:
890
+ * mode/topK/threshold/useRerank — passed through to searchMemories
891
+ * evalType — label for the snapshot (default 'manual')
892
+ * recordRecall — also write a recall_runs audit row for the
893
+ * same scene and link it via recall_run_id
894
+ * (default false: eval stays unlinked)
895
+ * recallRunId — explicit link to an existing recall_runs id
896
+ * persist — override the config gate for this call
897
+ *
898
+ * Returns { metrics, actualIds, expectedIds, recallRunId, persisted }.
899
+ * Never throws on persistence failures: a broken eval write must not break
900
+ * the retrieval quality measurement.
901
+ */
902
+ async function evaluateRetrieval(query, expectedIds, options = {}) {
903
+ const q = String(query ?? "").trim();
904
+ const expected = Array.isArray(expectedIds) ? expectedIds : [];
905
+ const {
906
+ mode = "auto",
907
+ topK = 20,
908
+ threshold,
909
+ useRerank = true,
910
+ evalType = "manual",
911
+ recordRecall = false,
912
+ recallRunId = null,
913
+ persist = config.evalPersistTestResults === true
914
+ } = options;
915
+ if (!q) {
916
+ const empty = computeRetrievalMetrics([], expected);
917
+ return { metrics: empty, actualIds: [], expectedIds: expected, recallRunId: null, persisted: false };
918
+ }
919
+
920
+ const rows = await searchMemories(q, { mode, topK, threshold, useRerank, recordRecall: false });
921
+ const actualIds = rows.map((m) => m.id);
922
+ const metrics = computeRetrievalMetrics(actualIds, expected);
923
+
924
+ // Optional recall_runs audit for the same scene; the eval row then links to
925
+ // it. Kept separate from the production recorder (which fires only on
926
+ // recordRecall=true inside searchMemories) — eval never double-records.
927
+ // An explicit recallRunId wins; recordRecall only mints a NEW audit run when
928
+ // the caller did not already link one (never clobber an existing link).
929
+ let runId = recallRunId ?? null;
930
+ if (recordRecall && runId === null) {
931
+ try {
932
+ const run = store.saveRecallRun({
933
+ query: q,
934
+ mode,
935
+ topK,
936
+ threshold: threshold ?? null,
937
+ candidates: rows.map((m) => ({
938
+ id: m.id,
939
+ title: m.title,
940
+ content: m.content,
941
+ score: m.score ?? null,
942
+ source: m.source ?? "keyword"
943
+ })),
944
+ created_at: new Date().toISOString()
945
+ });
946
+ runId = run.id;
947
+ } catch { /* non-fatal: the eval itself still succeeds */ }
948
+ }
949
+
950
+ let persisted = false;
951
+ if (persist) {
952
+ try {
953
+ store.saveRecallEval({
954
+ recall_run_id: runId,
955
+ query: q,
956
+ expected_ids: expected,
957
+ actual_ids: actualIds,
958
+ metrics,
959
+ eval_type: evalType,
960
+ created_at: new Date().toISOString()
961
+ });
962
+ persisted = true;
963
+ } catch { /* non-fatal: measurement survives a failed eval write */ }
964
+ }
965
+ return { metrics, actualIds, expectedIds: expected, recallRunId: runId, persisted };
966
+ }
967
+
968
+ /**
969
+ * Fire-and-forget write notification; errors are swallowed to keep write
970
+ * paths clean. The store mutation has already committed, so a throwing
971
+ * subscriber must not surface as a write failure. Archive/forget flags are
972
+ * state toggles, not content writes, so they never notify.
973
+ */
974
+ function notifyWrite() {
975
+ if (txDepth > 0) return; // deferred to the transaction's commit
976
+ if (onWrite) {
977
+ try { onWrite(); } catch { /* ignore */ }
978
+ }
979
+ if (dreamHook) {
980
+ try { dreamHook(); } catch { /* ignore */ }
981
+ }
982
+ if (sleepHook) {
983
+ try { sleepHook(); } catch { /* ignore */ }
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Run several store mutations atomically (SQLite BEGIN/COMMIT/ROLLBACK) and
989
+ * fire the deferred side effects once against the committed state. A throwing
990
+ * body rolls the whole batch back — no partial writes, no diverged mirror.
991
+ * Errors propagate to the caller. NOTE: the commit path re-renders the mirror
992
+ * and notifies subscribers, but re-embedding is left to the caller (the dream
993
+ * flow re-embeds through maintainIndexAfterDream).
994
+ */
995
+ function transaction(fn) {
996
+ store.db.exec("BEGIN");
997
+ txDepth++;
998
+ try {
999
+ const result = fn();
1000
+ store.db.exec("COMMIT");
1001
+ return result;
1002
+ } catch (error) {
1003
+ try { store.db.exec("ROLLBACK"); } catch { /* store may be closed */ }
1004
+ throw error;
1005
+ } finally {
1006
+ txDepth--;
1007
+ // Sync failures are surfaced, not swallowed (peer blocker 2): the mirror
1008
+ // debt was already recorded by markMirrorDirty inside syncMirror, so a
1009
+ // restart recovers — but the operator must see it now, not after restart.
1010
+ const syncResult = syncMirror();
1011
+ if (!syncResult?.success && !syncResult?.deferred) {
1012
+ logger?.warn?.("mirror sync failed after transaction:", syncResult?.error);
1013
+ }
1014
+ notifyWrite();
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * Embed an arbitrary query text and return its vector (null on failure / no
1020
+ * embedder). Used by the injector to prefetch the semantic-first recall
1021
+ * vector for the current user message — the system-prompt render is
1022
+ * synchronous, so the vector must be cached in advance (Bug4).
1023
+ */
1024
+ async function embedQuery(query) {
1025
+ const q = String(query ?? "").trim();
1026
+ if (!q || !embedder) return null;
1027
+ try {
1028
+ const embedSingle = typeof embedder.embedSingle === "function"
1029
+ ? embedder.embedSingle.bind(embedder)
1030
+ : embedder.embed.bind(embedder);
1031
+ const vector = await embedSingle(q);
1032
+ return Array.isArray(vector) && vector.length ? vector : null;
1033
+ } catch {
1034
+ return null;
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * 写入端同会话语义去重(Issue #127,opt-in,默认 off):落库前把新条目与
1040
+ * 「同会话 + 时间窗」内已落库的记忆比对,命中即并入既有条目,不再新造一行。
1041
+ *
1042
+ * 分层:title 档走零成本的标题归一化;vector 档复用已有 embedding 列做近邻,
1043
+ * 新条目的向量由 embedder 现算(embedQuery),全程无 LLM 调用。embedder 不可用
1044
+ * 或向量缺失一律返回 undefined 回落正常写入——去重是增强,绝不能成为写入依赖。
1045
+ *
1046
+ * 作用域刻意限定「同会话」:跨会话的同类事实仍交给 autoDream / sleep 的批量裁决。
1047
+ * 比对逻辑与并入动作分别复用 cosineVec 与 saveWithDedupe 的 _mergeInto 分支。
1048
+ *
1049
+ * @returns {{action: "merged", memory: object, sim: number}|undefined} 命中则返回
1050
+ * 并入目标与相似度;未命中(含任何异常)返回 undefined。
1051
+ */
1052
+ async function findSessionDuplicate(memory, { mode = "off", minSim = 0.92, windowHours = 24, source } = {}) {
1053
+ if (mode === "off" || !source || !memory?.title) return undefined;
1054
+ try {
1055
+ const sinceMs = windowHours > 0 ? Date.now() - windowHours * 3600000 : 0;
1056
+ const inWindow = (m) => {
1057
+ if (sinceMs <= 0) return true;
1058
+ const t = Date.parse(m.created_at ?? "");
1059
+ return !Number.isFinite(t) || t >= sinceMs; // 时间戳损坏时不误杀
1060
+ };
1061
+ const candidates = store
1062
+ .list({ type: memory.type, source, limit: 200 })
1063
+ .filter((m) => !m.archived && inWindow(m));
1064
+ if (!candidates.length) return undefined;
1065
+
1066
+ if (mode === "title") {
1067
+ const norm = (s) => String(s ?? "").toLowerCase().replace(/[\s\p{P}]+/gu, "");
1068
+ const key = norm(memory.title);
1069
+ if (!key) return undefined;
1070
+ const hit = candidates.find((m) => norm(m.title) === key);
1071
+ return hit ? { action: "merged", memory: hit, sim: 1 } : undefined;
1072
+ }
1073
+ if (mode !== "vector") return undefined;
1074
+
1075
+ const vecs = store.getEmbeddings(candidates.map((m) => m.id));
1076
+ if (!vecs.size) return undefined;
1077
+ const probe = await embedQuery([memory.title, memory.content].filter(Boolean).join("\n"));
1078
+ if (!probe) return undefined;
1079
+ let best;
1080
+ for (const m of candidates) {
1081
+ const v = vecs.get(m.id);
1082
+ if (!v) continue; // 无向量的既有行不参与比对(无信号 = 不判定)
1083
+ const sim = cosineVec(probe, v);
1084
+ if (sim >= minSim && (!best || sim > best.sim)) best = { action: "merged", memory: m, sim };
1085
+ }
1086
+ return best;
1087
+ } catch {
1088
+ return undefined; // 去重失败绝不阻塞写入
1089
+ }
1090
+ }
1091
+
1092
+ /**
1093
+ * Save a memory, merging into an existing one when title matches within the same type.
1094
+ *
1095
+ * Bug5: a same-title merge no longer overwrites — the new content is appended
1096
+ * under a timestamped `---` separator (`旧内容\n\n---\n[时间戳] 新内容`) and the
1097
+ * previous content is archived into content_history (source: auto_merge, FIFO
1098
+ * capped at 20). importance takes the max of both (capped at 5). Callers that
1099
+ * truly replace a row (dream summary regeneration) pass `_overwrite: true` to
1100
+ * overwrite directly while still archiving the old version (source: overwrite).
1101
+ * mergeHumanEdits entry points pass `_humanEdited: true` — same direct
1102
+ * overwrite semantics, source: human_override.
1103
+ *
1104
+ * Bug7 (memory quality filter): when config.memoryQualityFilter.enabled, the
1105
+ * memory is scored after dedupe, before write:
1106
+ * score >= degradeThreshold → stored normally (score persisted)
1107
+ * archiveThreshold <= score < 60 → persisted + ranked degraded
1108
+ * score < archiveThreshold → archived + tagged low_quality (still
1109
+ * explicitly searchable via includeArchived)
1110
+ * @returns {{action: "created"|"merged", memory: object}}
1111
+ */
1112
+ function saveWithDedupe(memory) {
1113
+ // Bug7: score quality once (after dedupe lookup, before write). Failures
1114
+ // inside the evaluator are impossible (pure function), but the write that
1115
+ // records the score must never fail the save — wrap defensively.
1116
+ const qf = config.memoryQualityFilter;
1117
+ let quality = null;
1118
+ if (qf?.enabled === true) {
1119
+ try {
1120
+ const recentContents = store.all().slice(0, 20).map((m) => m.content ?? "");
1121
+ quality = evaluateMemoryQuality(memory, {
1122
+ minContentLength: qf.minContentLength ?? 10,
1123
+ recentContents
1124
+ });
1125
+ } catch { /* quality scoring is best-effort */ }
1126
+ }
1127
+ // dream 总览按 source 身份去重,而非本地化标题:memory.language 切换后
1128
+ // 标题变化,若仍按 (type, title) 匹配会出现两个活跃的 summary 同时注入。
1129
+ // 其余类型维持 (type, title) 匹配不变。
1130
+ const candidates = store.list({ type: memory.type, limit: 100 });
1131
+ // v0.8.0 A1(issue #17):去重键由 (type, title) 扩展为
1132
+ // (type, title, agent_scope, workspace_scope, sensitivity)——不同作用域的同
1133
+ // 标题记忆绝不互相物理合并(旧逻辑跨 agent/workspace 并行,事后无法拆分)。
1134
+ // NULL 归一为「未标注」:未标注行之间互相匹配(含存量行),与已标注行不
1135
+ // 匹配。
1136
+ // v0.8.1(issue #170 复核项 1):比较不再受 scopeEnabled 门控——显式声明
1137
+ // flag 关也生效(工具层明写「读了自动标注也生效」,去重必须同口径),否则
1138
+ // 关自动标注后同标题不同 scope 的行会物理合并进第一行的归属。存量全 NULL
1139
+ // 行互相匹配,A1 前行为不变。
1140
+ const scopeMatches = (m) =>
1141
+ scopeKeyOf(m.agent_scope) === scopeKeyOf(memory.agent_scope) &&
1142
+ scopeKeyOf(m.workspace_scope) === scopeKeyOf(memory.workspace_scope) &&
1143
+ scopeKeyOf(m.sensitivity) === scopeKeyOf(memory.sensitivity);
1144
+ // Issue #127:写入端语义去重命中时,调用方用 _mergeInto 指定并入目标——复用
1145
+ // 下面这段并入逻辑(appendContent + content_history + 质量处置),不另写第二份
1146
+ // 实现。目标已被并发删除时回落到常规匹配。显式目标同样过 scope 门:跨作用域
1147
+ // 的语义相似不并入(防泄漏),回落为独立新行。
1148
+ const explicitTarget = memory._mergeInto ? store.getById(memory._mergeInto) : undefined;
1149
+ const existing = explicitTarget
1150
+ ? (scopeMatches(explicitTarget) ? explicitTarget : undefined)
1151
+ : (memory.type === "summary" && memory.source === "dream")
1152
+ ? (candidates.find((m) => m.source === "dream" && scopeMatches(m))
1153
+ ?? candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim()))
1154
+ : (memory.type === "summary" && memory.source === "narrative")
1155
+ // 叙述条(#164)按主题键去重而非本地化标题:标题随语言变
1156
+ // (叙述:X / Narrative: X),title 匹配在语言切换后会残留同 tag 双行。
1157
+ // tag 存于 tags[0](generateNarratives 落库),跨语言稳定 → 原地刷新。
1158
+ ? (candidates.find((m) => m.source === "narrative" && m.tags?.[0] === memory.tags?.[0] && scopeMatches(m))
1159
+ ?? candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim()))
1160
+ : candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim());
1161
+ if (existing) {
1162
+ const newContent = String(memory.content ?? "");
1163
+ if (!newContent.trim()) {
1164
+ // Nothing to merge: the row stays untouched.
1165
+ return { action: "merged", memory: existing };
1166
+ }
1167
+ const direct = memory._overwrite === true || memory._humanEdited === true;
1168
+ const content = direct
1169
+ ? newContent
1170
+ : appendContent(existing.content, newContent);
1171
+ const importance = Math.min(5, Math.max(existing.importance, memory.importance ?? existing.importance));
1172
+ // v0.8.1 底座(issue #170):去重命中=scope 值完全同键,此时显式写入把
1173
+ // 被并入行的同维来源升级为 explicit(用户刚刚显式声明了同一归属),
1174
+ // 并刷新 scope_decided_at。仅升级来源、不改值——值改变会走新行。
1175
+ const scopeUpgrade = {};
1176
+ if (memory.agent_scope_source === "explicit" && existing.agent_scope_source !== "explicit") {
1177
+ scopeUpgrade.agent_scope_source = "explicit";
1178
+ }
1179
+ if (memory.workspace_scope_source === "explicit" && existing.workspace_scope_source !== "explicit") {
1180
+ scopeUpgrade.workspace_scope_source = "explicit";
1181
+ }
1182
+ if (Object.keys(scopeUpgrade).length) scopeUpgrade.scope_decided_at = new Date().toISOString();
1183
+ const merged = store.update(existing.id, {
1184
+ content,
1185
+ importance,
1186
+ tags: memory.tags ?? existing.tags,
1187
+ title: memory.title ?? existing.title,
1188
+ ...(memory.evidence !== undefined ? { evidence: memory.evidence } : {}),
1189
+ content_history: pushContentHistory(existing, direct
1190
+ ? (memory._humanEdited === true ? "human_override" : "overwrite")
1191
+ : "auto_merge"),
1192
+ ...scopeUpgrade,
1193
+ ...(quality ? { quality_score: quality.score } : {})
1194
+ });
1195
+ // v0.8.1(issue #170 review 3):来源升级也是归属性质改变——与
1196
+ // updateMemory 的显式修正同等待遇,落一行 scope_changes(actor=tool:
1197
+ // 只有 memory_save 的显式参数会带 explicit 来源走到这里)。审计失败只
1198
+ // warn 不反噬合并。升级只在来源首次变化时触发,不会每次并入都写。
1199
+ if (Object.keys(scopeUpgrade).length) {
1200
+ try {
1201
+ store.saveScopeChange({
1202
+ memory_id: existing.id,
1203
+ actor: "tool",
1204
+ prev_agent_scope: existing.agent_scope ?? null,
1205
+ prev_workspace_scope: existing.workspace_scope ?? null,
1206
+ next_agent_scope: merged.agent_scope ?? null,
1207
+ next_workspace_scope: merged.workspace_scope ?? null,
1208
+ agent_scope_source: merged.agent_scope_source ?? null,
1209
+ workspace_scope_source: merged.workspace_scope_source ?? null,
1210
+ decided_at: scopeUpgrade.scope_decided_at
1211
+ });
1212
+ } catch (e) {
1213
+ try { logger?.warn?.(`[dsh-mneme] scope upgrade audit failed: ${String(e)}`); } catch { /* 不反噬 */ }
1214
+ }
1215
+ }
1216
+ // Bug7: a degraded/archived result is applied on top of the merged row.
1217
+ const result = applyQualityDisposition(merged, quality, qf);
1218
+ afterSync("write");
1219
+ notifyWrite();
1220
+ scheduleEmbed(result);
1221
+ return { action: "merged", memory: result };
1222
+ }
1223
+ const created = store.save({
1224
+ type: memory.type,
1225
+ title: memory.title,
1226
+ content: memory.content,
1227
+ tags: memory.tags ?? [],
1228
+ importance: memory.importance ?? 3,
1229
+ source: memory.source ?? "manual",
1230
+ ...(memory.evidence !== undefined ? { evidence: memory.evidence } : {}),
1231
+ // v0.8.0 A1:scope 标注透传(store 端归一化,未标注落 NULL)。
1232
+ // v0.8.1 底座:来源(auto/explicit)与决策时间随行透传。
1233
+ agent_scope: memory.agent_scope,
1234
+ workspace_scope: memory.workspace_scope,
1235
+ agent_scope_source: memory.agent_scope_source,
1236
+ workspace_scope_source: memory.workspace_scope_source,
1237
+ scope_decided_at: memory.scope_decided_at,
1238
+ sensitivity: memory.sensitivity,
1239
+ occurred_at: memory.occurred_at,
1240
+ ...(quality ? { quality_score: quality.score } : {})
1241
+ });
1242
+ const result = applyQualityDisposition(created, quality, qf);
1243
+ afterSync("write");
1244
+ notifyWrite();
1245
+ scheduleEmbed(result);
1246
+ scheduleEntityExtraction(result);
1247
+ return { action: "created", memory: result };
1248
+ }
1249
+
1250
+ /**
1251
+ * Bug7: apply the quality verdict to a freshly written row. Below the archive
1252
+ * threshold the memory is archived + tagged low_quality (still searchable
1253
+ * explicitly via includeArchived); between archive and degrade thresholds the
1254
+ * score is already persisted and only the injection ranking is affected
1255
+ * (importance × score/100). Best-effort: a disposition write failure must
1256
+ * never fail the save. Returns the (possibly refreshed) memory row so callers
1257
+ * see the archived/tagged state, not the pre-disposition snapshot.
1258
+ *
1259
+ * Issue #135 附属发现 1:importance ≥ memoryQualityFilter.exemptImportance
1260
+ * (默认 4)的记忆不参与静默自动归档——评分与信号标签照常写入(可观测),
1261
+ * 注入排序照常按 importance × score/100 降权,但 setArchived 跳过。报告实测
1262
+ * 150 条低分归档里 128 条 importance ≥ 4(51 条 = 5):一条被显式标为重要的
1263
+ * 记忆不该被规则分静默归档、无感知无豁免。
1264
+ */
1265
+ function applyQualityDisposition(memory, quality, qf) {
1266
+ if (!quality || qf?.enabled !== true) return memory;
1267
+ const archiveThreshold = qf.archiveThreshold ?? 30;
1268
+ // Signal tags (meta / repetitive / duplicate / short_content / low_quality)
1269
+ // are merged onto the stored row in every assessed band so the verdict is
1270
+ // observable, not just the numeric score. Below the archive threshold the
1271
+ // memory is additionally archived (still explicitly searchable) — unless
1272
+ // its importance reaches the exemption floor (kept active, demoted only).
1273
+ const tags = [...new Set([...(memory.tags ?? []), ...(quality.tags ?? [])])];
1274
+ const exemptImportance = qf.exemptImportance ?? 4;
1275
+ const importanceExempt = Number.isInteger(memory.importance) && memory.importance >= exemptImportance;
1276
+ if (tags.length === (memory.tags?.length ?? 0) && (quality.score >= archiveThreshold || importanceExempt)) {
1277
+ return memory; // no tag drift and not archived → nothing extra to write
1278
+ }
1279
+ try {
1280
+ store.update(memory.id, { tags, quality_score: quality.score });
1281
+ if (quality.score < archiveThreshold && !importanceExempt) {
1282
+ store.setArchived(memory.id, true);
1283
+ } else if (quality.score < archiveThreshold) {
1284
+ logger?.info?.(`[dsh-mneme] quality filter: memory ${memory.id} scored ${quality.score} < ${archiveThreshold} but importance ${memory.importance} >= exemptImportance ${exemptImportance}; demoted, not archived`);
1285
+ }
1286
+ return store.getById(memory.id);
1287
+ } catch {
1288
+ return memory;
1289
+ }
1290
+ }
1291
+
1292
+ /**
1293
+ * Candidate memories for automatic context injection:
1294
+ * summaries first, then all preferences, then non-forgotten items with
1295
+ * importance >= threshold. History is never auto-injected. Archived entries
1296
+ * are excluded (store.list already filters them by default; the extra
1297
+ * !m.archived check is kept as double insurance).
1298
+ *
1299
+ * Bug4 (hybridInject): when a non-empty `query` is available and a matching
1300
+ * semantic recall was cached by the last searchMemories, the vector hits
1301
+ * lead the selection (up to maxItems*2 candidates) and the rule-based pick
1302
+ * fills + dedupes the remaining slots. Empty query / no cached recall /
1303
+ * hybridInject off → pure legacy rule-based selection.
1304
+ */
1305
+ function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector, scope = null, rotate = null, rotateWindow = 0 } = {}) {
1306
+ const q = String(query ?? "").trim();
1307
+ // codingRetrospect 读取侧门控:编码记忆(rejected_solution / pitfall /
1308
+ // constraint)只在编码任务时注入,防噪声污染其他业务;编码任务时按
1309
+ // codingBoostFactor 加权,让编码记忆在编码场景更靠前。
1310
+ const isCoding = isCodingTask(q, config.codingKeywords ?? []);
1311
+ const codingGate = (m) => isCoding || !CODING_MEMORY_TYPES.has(m.type);
1312
+ // Bug7: quality-weighted importance in the rule-based tier. Unassessed rows
1313
+ // (quality_score null) count as 100 (weight 1), so legacy stores keep their
1314
+ // exact summary>preference>importance ordering.
1315
+ const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
1316
+ // Issue #205 补测:候选池必须比轮换窗口大——窗口 N 需要 maxItems×(N+1) 张
1317
+ // 不同的牌,池子只有 maxItems×2 时窗口一开就被吃光、只剩回填(重复率的
1318
+ // 结构性下限由池子大小决定)。无轮换时保持既有 maxItems×2 不变;规则路
1319
+ // 的 200 条上限同样给轮换让路(上限翻倍也只是多读一次 SQL LIMIT)。
1320
+ const rotateWindowN = Number.isInteger(rotateWindow) && rotateWindow > 0 ? rotateWindow : 0;
1321
+ const poolSize = rotateWindowN > 0
1322
+ ? Math.max(maxItems * 2, maxItems * (rotateWindowN + 1))
1323
+ : maxItems * 2;
1324
+ const filtered = store.list({ limit: Math.max(200, poolSize), includeForgotten: false })
1325
+ .filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1326
+ // 叙述条(#164 对齐)按需检索:source=narrative 的 per-topic 叙述不进
1327
+ // 注入候选——常驻位只留给 dream 总览(source=dream)。
1328
+ m.source !== "narrative" &&
1329
+ codingGate(m) &&
1330
+ (m.type === "summary" || m.type === "preference" || m.importance >= threshold));
1331
+ // #218 v1: heat 乘数——heatEnabled 时在优先级层内给 importance×quality 乘
1332
+ // heat(同级内的乘数;priority 分层、store 的 order=chrono 分页序与召回融
1333
+ // 合序都不动)。heat 关闭时不建表、不算 heat,权重恒 1,排序与改动前一致。
1334
+ // selectiveInject 相似度重排(下方)开启且向量可用时相似度优先——heat 只
1335
+ // 生效于规则路排序与语义路回填序。
1336
+ const heatMap = config?.heatEnabled === true
1337
+ ? new Map(filtered.map((m) => [m.id, computeHeat(m, Date.now(), config)]))
1338
+ : null;
1339
+ const heatOf = (m) => (heatMap ? heatMap.get(m.id) ?? 1 : 1);
1340
+ const items = filtered.sort((a, b) => {
1341
+ // 编码记忆在编码任务时优先于普通 decision(与 preference 同级),
1342
+ // importance 乘 codingBoostFactor 加权(封顶 5,保持 importance 语义)。
1343
+ const priority = (m) => {
1344
+ if (m.type === "summary") return 0;
1345
+ if (m.type === "preference") return 1;
1346
+ if (isCoding && CODING_MEMORY_TYPES.has(m.type)) return 1;
1347
+ return 2;
1348
+ };
1349
+ const effImportance = (m) =>
1350
+ (isCoding && CODING_MEMORY_TYPES.has(m.type))
1351
+ ? Math.min(5, m.importance * (config.codingBoostFactor ?? 2))
1352
+ : m.importance;
1353
+ const pa = priority(a);
1354
+ const pb = priority(b);
1355
+ return pa - pb ||
1356
+ (effImportance(b) * qualityWeight(b) * heatOf(b)) - (effImportance(a) * qualityWeight(a) * heatOf(a));
1357
+ });
1358
+ let candidates = items;
1359
+ if (config.hybridInject !== false && q) {
1360
+ // Bug4: semantic-first recall. Vector hits (queryVector, cached by the
1361
+ // injector's async prefetch) lead when present; otherwise the last
1362
+ // searchMemories recall for the exact same query is reused. Rule-based
1363
+ // items fill + dedupe the remaining slots. Empty query / no vector /
1364
+ // no cached recall → pure legacy rule-based selection.
1365
+ const semanticItems = [];
1366
+ if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
1367
+ try {
1368
+ const hits = vectorIndex.search(queryVector, { limit: poolSize, threshold: 0 });
1369
+ for (const m of hits) {
1370
+ if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
1371
+ codingGate(m) &&
1372
+ (m.type === "summary" || m.type === "preference" || m.importance >= threshold)) {
1373
+ semanticItems.push(m);
1374
+ }
1375
+ }
1376
+ } catch { /* vector unavailable: fall through to the recall cache */ }
1377
+ }
1378
+ if (!semanticItems.length && lastSemanticRecall?.query === q && lastSemanticRecall.items?.length) {
1379
+ for (const m of lastSemanticRecall.items) {
1380
+ if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten && codingGate(m)) semanticItems.push(m);
1381
+ }
1382
+ }
1383
+ // Issue #198:首轮(无向量、无缓存召回)的同步兜底——BM25 词法召回领位。
1384
+ // 注入渲染是同步的(宿主 systemPrompt 的 contexts 不支持异步 text),
1385
+ // 查询向量只能异步 prefetch 给下一轮,首轮必 miss;此时纯静态排序会让
1386
+ // 老的高重要性 summary/preference 占满槽位,当前话题的 decision/project
1387
+ // 进不来。查询文本本身就在手上,BM25 是纯进程内同步计算,词法相关性
1388
+ // 足以把当前话题顶到前排;门控与向量路径一致(含 importance 阈值)。
1389
+ // 语义向量命中时本分支不参与,行为不变。
1390
+ if (!semanticItems.length) {
1391
+ for (const hit of bm25Recall(q, poolSize)) {
1392
+ if (hit && !hit.archived && INJECT_TYPES.has(hit.type) && !hit.forgotten &&
1393
+ codingGate(hit) &&
1394
+ (hit.type === "summary" || hit.type === "preference" || hit.importance >= threshold)) {
1395
+ semanticItems.push(hit);
1396
+ }
1397
+ }
1398
+ }
1399
+ if (semanticItems.length) {
1400
+ const seen = new Set();
1401
+ const merged = [];
1402
+ const push = (m) => {
1403
+ if (seen.has(m.id)) return;
1404
+ seen.add(m.id);
1405
+ merged.push(m);
1406
+ };
1407
+ for (const m of semanticItems) {
1408
+ push(m);
1409
+ if (merged.length >= poolSize) break;
1410
+ }
1411
+ for (const m of items) {
1412
+ if (merged.length >= poolSize) break;
1413
+ push(m);
1414
+ }
1415
+ candidates = merged;
1416
+ }
1417
+ }
1418
+ // Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
1419
+ // available the whole candidate list is re-ordered by similarity to that
1420
+ // vector, so the injected slots go to memories on the current topic
1421
+ // rather than to the rule-based order. Rows the index did not return
1422
+ // keep their relative order after the scored ones.
1423
+ if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
1424
+ try {
1425
+ const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
1426
+ const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
1427
+ if (sim.size) {
1428
+ candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
1429
+ }
1430
+ } catch { /* topic re-rank unavailable: keep rule-based order */ }
1431
+ }
1432
+ // v0.8.0 A3(issue #17):strictScope 硬过滤同样作用于自动注入——scoped 记忆
1433
+ // 泄进无关注入上下文是最典型的越权通道,检索侧过滤挡不住这里。
1434
+ if (config?.strictScope === true && scope) {
1435
+ candidates = candidates.filter((m) => isVisibleInScope(m, scope));
1436
+ }
1437
+ // Issue #205:注入位跨轮轮换。rotate = 最近 N 轮注入过的 id 集合(由注入层
1438
+ // 按会话维护并传入):这些条目本轮不再优先——新鲜者前置(各自内部相对次序
1439
+ // 保持),不足时按原序回填,槽位数与 touchRecall 语义均不变。rotate 为空时
1440
+ // 行为与既有排序完全一致。
1441
+ if (rotate && rotate.size > 0 && candidates.length > 0) {
1442
+ const fresh = candidates.filter((m) => !rotate.has(m.id));
1443
+ if (fresh.length > 0) candidates = [...fresh, ...candidates.filter((m) => rotate.has(m.id))];
1444
+ }
1445
+ const selected = candidates.slice(0, maxItems);
1446
+ touchRecalled(selected);
1447
+ return selected;
1448
+ }
1449
+
1450
+ /**
1451
+ * Merge human edits parsed from a mirror file back into the store.
1452
+ * Only content/title are taken; structure fields stay machine-owned.
1453
+ */
1454
+ function mergeHumanEdits(type, edits) {
1455
+ let applied = 0;
1456
+ for (const edit of edits) {
1457
+ if (!edit.id) continue; // corrupt/malformed edit: skip it, keep merging the rest
1458
+ const existing = store.getById(edit.id);
1459
+ if (!existing || existing.type !== type) continue;
1460
+ const patch = {};
1461
+ if (typeof edit.title === "string" && edit.title.trim()) patch.title = edit.title.trim();
1462
+ if (typeof edit.content === "string" && edit.content.trim()) patch.content = edit.content.trim();
1463
+ if (Object.keys(patch).length) {
1464
+ // 启动回灌(F-NEW-01):digest 存在且匹配 = 文件自渲染后无人触碰(旧机器
1465
+ // 镜像),机器 wins,DB 的 New 必须保留,静默改回 Old 是 bug。
1466
+ const digestMatches = typeof edit.digest === "string"
1467
+ && typeof edit.title === "string"
1468
+ && typeof edit.content === "string"
1469
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1470
+ if (digestMatches) continue;
1471
+ // 文件 == store(无实际变化)时不覆盖,也不计入 applied。
1472
+ const hasDiff = (patch.title !== undefined && existing.title !== patch.title)
1473
+ || (patch.content !== undefined && existing.content !== patch.content);
1474
+ if (!hasDiff) continue;
1475
+ // 人工编辑回灌后触发 re-embed(issue #3 残留修复):向量必须与
1476
+ // 新 title/content 一致。scheduleEmbed 为 fire-and-forget,
1477
+ // 内部 try/catch 吞错,失败不影响主流程。
1478
+ // Bug5: human edits overwrite directly, but the machine version is
1479
+ // archived into content_history (source: human_override) before being
1480
+ // replaced, so a manual correction never silently destroys the old value.
1481
+ const merged = store.update(edit.id, {
1482
+ ...patch,
1483
+ content_history: patch.content !== undefined && existing.content !== patch.content
1484
+ ? pushContentHistory(existing, "human_override")
1485
+ : existing.content_history
1486
+ });
1487
+ applied++;
1488
+ scheduleEmbed(merged);
1489
+ }
1490
+ }
1491
+ if (applied) {
1492
+ afterSync("write");
1493
+ notifyWrite();
1494
+ }
1495
+ return applied;
1496
+ }
1497
+
1498
+ /**
1499
+ * v0.8.0 冲突集中处理(issue 反馈:冻结冲突没有人工出口——store 的
1500
+ * resolveConflictPending 此前无任何 API/UI 调用)。人工确认一条待审冲突:
1501
+ * 盖章 resolved_at/resolved_winner(审计),可选按 dream 非冻结 conflict
1502
+ * 路径**同款**处置落地——复用 applyDecisions 的 conflict 分支,CAS 快照 +
1503
+ * 事务 + 胜者追加已否决注记 + 败者归档 + 幂等全部同源,不另写第二份裁决。
1504
+ *
1505
+ * @param {string} id conflict_pending 行 id
1506
+ * @param {{winner?: "a"|"b"|null, apply?: boolean}} opts
1507
+ * winner: 选哪一方保留(a = memory_a,冻结时 LLM 的建议胜者;b = memory_b);
1508
+ * null = 仅盖章标记已读、不落地处置。人工选择是权威裁决:传入
1509
+ * applyDecisions 的 config 关掉 trustEpistemicWeighting——可信度自动换位
1510
+ * 只应作用于 LLM 提议对,不能推翻人工选择。
1511
+ * @returns {object|undefined} 盖章后的冲突行 + disposition 摘要;未知 id 返回 undefined
1512
+ */
1513
+ function resolveConflictPending(id, { winner = null, apply = true } = {}) {
1514
+ const rows = store.listConflictPending({ includeResolved: true, limit: 500 });
1515
+ const row = rows.find((r) => r.id === id);
1516
+ if (!row) return undefined;
1517
+ const winnerId = winner === "a" ? row.memory_a : winner === "b" ? row.memory_b : null;
1518
+ const loserId = winner === "a" ? row.memory_b : winner === "b" ? row.memory_a : null;
1519
+ let disposition = null;
1520
+ if (apply && winnerId && loserId) {
1521
+ const snapshot = new Map();
1522
+ for (const m of [store.getById(row.memory_a), store.getById(row.memory_b)]) {
1523
+ if (m) snapshot.set(m.id, { updated_at: m.updated_at, content: m.content, title: m.title });
1524
+ }
1525
+ // applyDecisions 需要一个 service 形状的参数(getById/update/setArchived/
1526
+ // transaction)——委托给闭包内的同名实现,mirror/通知/嵌入与主写路径同源。
1527
+ const applyService = {
1528
+ getById: (mid) => store.getById(mid),
1529
+ update: (mid, patch) => updateMemory(mid, patch),
1530
+ setArchived: (mid, v) => archiveMemory(mid, v),
1531
+ transaction: (fn) => transaction(fn)
1532
+ };
1533
+ const { committed, failures } = applyDecisions(
1534
+ [{ action: "conflict", winner: winnerId, loser: loserId, reason: row.reason ?? "" }],
1535
+ applyService,
1536
+ logger,
1537
+ snapshot,
1538
+ { ...config, trustEpistemicWeighting: false }
1539
+ );
1540
+ // Review 发现:处置必须**先于**盖章。原实现先 resolveConflictPending 盖章、
1541
+ // 再 applyDecisions——若 CAS 拒掉(确认前双方被并发更新),行已 resolved 从
1542
+ // 队列消失、前端仍显示成功,审计却记了"已确认"且无法重试。现在失败时不盖章
1543
+ // 直接返回:行留在队列待重试,审计不被污染。
1544
+ if (failures.length) {
1545
+ return { ...row, disposition: { ok: false, failures } };
1546
+ }
1547
+ disposition = { ok: true, committed };
1548
+ }
1549
+ // 处置成功(或纯标记)后才盖章。幂等重放(败者已归档 → skipped)也走这里:
1550
+ // 处置本就存在,标记已审即可。
1551
+ const stamped = store.resolveConflictPending(id, { winner: winnerId });
1552
+ if (!stamped) return undefined;
1553
+ return { ...stamped, disposition };
1554
+ }
1555
+
1556
+ /**
1557
+ * v0.8.0 冲突队列视图数据源:未解决冲突行,联表带出双方的当前状态(标题/
1558
+ * 内容/类型/重要性/归档标记),面板一处即可集中审阅,不必按徽章逐条找。
1559
+ * 参与记忆被删除/失联时该侧返回 {missing: true}(队列不因此丢行)。
1560
+ */
1561
+ function listConflictQueue({ limit = 50, offset = 0 } = {}) {
1562
+ const rows = store.listConflictPending({ limit, offset, includeResolved: false });
1563
+ const side = (id) => {
1564
+ const m = store.getById(id);
1565
+ if (!m) return { id, missing: true };
1566
+ return {
1567
+ id,
1568
+ title: m.title,
1569
+ type: m.type,
1570
+ importance: m.importance,
1571
+ content: m.content,
1572
+ archived: m.archived === true,
1573
+ forgotten: m.forgotten === true
1574
+ };
1575
+ };
1576
+ return rows.map((r) => ({
1577
+ id: r.id,
1578
+ run_id: r.run_id ?? null,
1579
+ reason: r.reason ?? null,
1580
+ created_at: r.created_at,
1581
+ memory_a: side(r.memory_a),
1582
+ memory_b: side(r.memory_b)
1583
+ }));
1584
+ }
1585
+
1586
+ function toApiList(rows) {
1587
+ return rows.map((m) => ({
1588
+ id: m.id,
1589
+ type: m.type,
1590
+ title: m.title,
1591
+ content: m.content,
1592
+ tags: m.tags,
1593
+ importance: m.importance,
1594
+ source: m.source,
1595
+ created_at: m.created_at,
1596
+ updated_at: m.updated_at,
1597
+ // v0.8.0 A2:scope 标注与事件发生时间透出——条件展开(未标注行不带键,
1598
+ // DTO 与 A2 前逐字节同形;带 undefined 键会被 in-process schema 校验
1599
+ // 判违规,JSON 序列化虽会丢弃但形状不稳定)。
1600
+ // v0.8.1 底座:scope 来源与决策时间随行透出(同样条件展开)。
1601
+ ...(m.agent_scope !== undefined ? { agent_scope: m.agent_scope } : {}),
1602
+ ...(m.workspace_scope !== undefined ? { workspace_scope: m.workspace_scope } : {}),
1603
+ ...(m.agent_scope_source !== undefined ? { agent_scope_source: m.agent_scope_source } : {}),
1604
+ ...(m.workspace_scope_source !== undefined ? { workspace_scope_source: m.workspace_scope_source } : {}),
1605
+ ...(m.scope_decided_at !== undefined ? { scope_decided_at: m.scope_decided_at } : {}),
1606
+ ...(m.sensitivity !== undefined ? { sensitivity: m.sensitivity } : {}),
1607
+ ...(m.occurred_at !== undefined ? { occurred_at: m.occurred_at } : {})
1608
+ }));
1609
+ }
1610
+
1611
+ /**
1612
+ * Three-way merge of in-flight human mirror edits before a re-render.
1613
+ * Runs on every syncMirror, so a human edit made between two store writes is
1614
+ * never silently overwritten by the next sync (human priority is not limited
1615
+ * to startup). Per edited entry:
1616
+ * - file changed only → human wins; the edit is merged back into the store.
1617
+ * - file AND store changed → real three-way conflict: keep the human edit
1618
+ * and append a marker preserving the store's concurrent version, so no
1619
+ * side is dropped.
1620
+ * - store changed only → store wins (the file is simply re-rendered).
1621
+ * Only title/content are taken (structure fields stay machine-owned, matching
1622
+ * mergeHumanEdits). Returns the memory list to render.
1623
+ */
1624
+ function reconcileHumanEdits(memories) {
1625
+ if (!mirror) return memories;
1626
+ const byType = new Map();
1627
+ for (const m of memories) {
1628
+ if (!byType.has(m.type)) byType.set(m.type, []);
1629
+ byType.get(m.type).push(m);
1630
+ }
1631
+ const result = [];
1632
+ for (const type of Object.keys(TYPE_FILE)) {
1633
+ const list = byType.get(type) ?? [];
1634
+ if (list.length === 0) continue;
1635
+ const editsById = new Map(mirror.readHumanEdits(type).map((e) => [e.id, e]));
1636
+ for (const m of list) {
1637
+ const edit = editsById.get(m.id);
1638
+ if (!edit) { result.push(m); continue; }
1639
+ const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
1640
+ || (typeof edit.content === "string" && edit.content !== m.content);
1641
+ if (!humanChanged) { result.push(m); continue; }
1642
+ // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
1643
+ // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
1644
+ // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
1645
+ // 并发人工编辑导致机器写丢失 + 伪冲突标记。
1646
+ const digestMatches = typeof edit.digest === "string"
1647
+ && typeof edit.title === "string"
1648
+ && typeof edit.content === "string"
1649
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1650
+ if (digestMatches) {
1651
+ // 无人触碰,机器 wins,走原样
1652
+ result.push(m);
1653
+ continue;
1654
+ }
1655
+ // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
1656
+ // (保留现有 storeChanged 逻辑)
1657
+ const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
1658
+ if (storeChanged) {
1659
+ // 三方合并保留双方时的冲突批注:随实例语言,写进记忆正文。
1660
+ const marker = STR.serviceConflictMarker[language](m.updated_at, m.content);
1661
+ store.update(m.id, { title: edit.title, content: `${edit.content}${marker}` });
1662
+ } else {
1663
+ store.update(m.id, { title: edit.title, content: edit.content });
1664
+ }
1665
+ const merged = store.getById(m.id);
1666
+ scheduleEmbed(merged);
1667
+ result.push(merged);
1668
+ }
1669
+ }
1670
+ return result;
1671
+ }
1672
+
1673
+ /**
1674
+ * Re-render the human-editable mirror after any store mutation, merging any
1675
+ * in-flight human edits first (never silently overwriting them). Only
1676
+ * non-forgotten memories are mirrored: forgotten entries must not reach the
1677
+ * human-editable file (a human "edit" could otherwise resurrect them).
1678
+ */
1679
+ // syncMirror: 同步 mirror,并在失败/成功时持久记录 dirty 状态;保证自身不抛出。
1680
+ // v0.3.6(audit peer 4 阻断):
1681
+ // - 开始时 incrementGeneration 绑定本次期望轮次 gen;成功用
1682
+ // markMirrorCleanForGeneration(gen, now) CAS/fence 清 dirty——旧 worker
1683
+ // (gen 已过期)不会误清另一 worker 未恢复的故障债务;
1684
+ // - 失败写 markMirrorDirty(递增 desired 绑定新债务),下次 recover 恢复;
1685
+ // - 逐 type 用 setTypeStatus 记录部分成功/失败(type_status JSON);
1686
+ // - 所有 store 状态写入各自 try/catch,失败只 warn,绝不向外抛(F-NEW-03)。
1687
+ function syncMirror() {
1688
+ if (txDepth > 0 || !mirror) return { success: true, deferred: true }; // deferred to the transaction's commit
1689
+ const now = new Date().toISOString();
1690
+ let gen;
1691
+ try {
1692
+ // desired generation 已在业务写事务中原子递增(peer blocker 1);这里
1693
+ // 直接读当前值作为本次同步的目标轮次,不再自行 incrementGeneration。
1694
+ const state = store.getMirrorState();
1695
+ gen = state?.generation ?? 0;
1696
+ } catch (stateError) {
1697
+ logger?.warn?.("syncMirror: getMirrorState failed:", stateError);
1698
+ return { success: false, error: stateError?.message ?? String(stateError) };
1699
+ }
1700
+ // coveredTypes 提到 try 外初始化:即使 store.list 先抛错,catch 分支也有
1701
+ // 合法的空 Set 可迭代,保证 syncMirror 自身绝不抛(fail-safe)。
1702
+ const coveredTypes = new Set();
1703
+ try {
1704
+ // 预先获取本次要覆盖的 type 集合(只调一次 store.list)
1705
+ const list = store.list({ limit: 500, includeForgotten: false });
1706
+ for (const memory of list) {
1707
+ if (memory?.type && TYPE_FILE[memory.type]) {
1708
+ coveredTypes.add(memory.type);
1709
+ }
1710
+ }
1711
+
1712
+ // Per-type physical outcome (audit peer D): mirror.sync writes each type
1713
+ // file independently and reports per-type success/failure. A type whose
1714
+ // file was physically committed must be marked committed even when a
1715
+ // sibling type errors — the old code batch-failed every type on any error,
1716
+ // leaving committed files mislabeled as failed and masking partial state.
1717
+ // Absent entries (a type with no memories) count as success: sync prunes
1718
+ // the stale file, which is itself a completed physical state.
1719
+ let allOk = true;
1720
+ const results = mirror.sync(reconcileHumanEdits(list)) ?? {};
1721
+ for (const type of Object.keys(TYPE_FILE)) {
1722
+ const r = results[type];
1723
+ const ok = !r || r.ok === true;
1724
+ if (!ok) allOk = false;
1725
+ try {
1726
+ if (ok) {
1727
+ store.setTypeStatus(type, { status: "committed", applied_gen: gen, last_error: null });
1728
+ } else {
1729
+ store.setTypeStatus(type, { status: "failed", last_error: r.error ?? "mirror sync failed" });
1730
+ }
1731
+ } catch (stateError) {
1732
+ logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1733
+ }
1734
+ }
1735
+
1736
+ // 全部 type 物理收敛:CAS/fence 绑定到本地 gen,旧 worker(gen 已过期)会被
1737
+ // 拦截。此步失败说明核心 clean 状态没写成功,向上层报失败(不再静默)。
1738
+ if (allOk) {
1739
+ try {
1740
+ store.markMirrorCleanForGeneration(gen, now);
1741
+ } catch (stateError) {
1742
+ logger?.warn?.("syncMirror: markMirrorCleanForGeneration failed:", stateError);
1743
+ return { success: false, error: stateError?.message ?? String(stateError) };
1744
+ }
1745
+ return { success: true };
1746
+ }
1747
+
1748
+ // 部分 type 失败:持久 dirty(债务绑定到新轮次),下次 recover 只补未收敛
1749
+ // 的 type。committed 的 type 已应用本轮 gen,不因兄弟失败被回滚。
1750
+ const failedTypes = Object.entries(results)
1751
+ .filter(([, r]) => r && r.ok === false)
1752
+ .map(([t]) => t);
1753
+ try {
1754
+ store.markMirrorDirty(`mirror sync failed for: ${failedTypes.join(", ")}`, now);
1755
+ } catch (stateError) {
1756
+ logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1757
+ }
1758
+ return { success: false, error: `mirror sync failed for: ${failedTypes.join(", ")}` };
1759
+ } catch (error) {
1760
+ const errMsg = error?.message ?? String(error);
1761
+ logger?.warn?.("syncMirror failed:", error);
1762
+ try {
1763
+ // 债务绑定到新的一轮(desired generation 原子递增;即便 dirty 写失败,
1764
+ // generation 已推进,recoverMirror 仍能捕获,不产生 false-clean)。
1765
+ store.markMirrorDirty(errMsg, now);
1766
+ } catch (stateError) {
1767
+ logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1768
+ }
1769
+ // 逐 type 标记为 failed(applied_gen 不动)
1770
+ for (const type of coveredTypes) {
1771
+ try {
1772
+ store.setTypeStatus(type, { status: "failed", last_error: errMsg });
1773
+ } catch (stateError) {
1774
+ logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1775
+ }
1776
+ }
1777
+ return { success: false, error: errMsg };
1778
+ }
1779
+ }
1780
+
1781
+ // afterSync: run syncMirror and surface a failure to the operator instead of
1782
+ // swallowing it (peer blocker 2 + audit peer B). The mirror debt has already
1783
+ // been persisted by markMirrorDirty inside syncMirror, so a restart recovers —
1784
+ // but the calling write path must not report clean while the mirror is
1785
+ // known-stale. Returns the sync result so the caller can attach an explicit
1786
+ // degraded/pending receipt to its return value instead of faking success.
1787
+ function afterSync(label) {
1788
+ const r = syncMirror();
1789
+ if (!r?.success && !r?.deferred) {
1790
+ logger?.warn?.(`${label}: mirror sync failed (will recover on restart):`, r?.error);
1791
+ }
1792
+ return r;
1793
+ }
1794
+
1795
+ // recoverMirror: 启动/手动 reconcile 时根据持久 dirty 状态决定是否恢复同步
1796
+ // (F-NEW-03 + v0.3.6)。触发条件不只是 dirty——还检查
1797
+ // generation > applied_generation(有未应用的债务),这样 COMMIT→dirty 崩溃
1798
+ // 窗口(DB 提交后、markMirrorDirty/clean 前进程退出 → dirty=false 但
1799
+ // generation 不一致)也能被捕获。有界重试(最多 3 次)重跑 syncMirror 收敛;
1800
+ // 某次成功后 dirty=false 且无更新债务(generation <= applied_generation)
1801
+ // 立即停止。返回 { recovered, error } 供 index.js 启动 / api.js health 判断。
1802
+ // 一切 fail-safe,绝不向外抛。
1803
+ function recoverMirror() {
1804
+ const MAX_ATTEMPTS = 3;
1805
+ let lastError = null;
1806
+ let recovered = false;
1807
+
1808
+ try {
1809
+ const state = store.getMirrorState();
1810
+ // 崩溃窗口检测:dirty 或 generation > applied_generation(COMMIT→dirty 窗口)
1811
+ if (!state?.dirty && !(state.generation > state.applied_generation)) {
1812
+ // 本来就干净:无需恢复,视为成功
1813
+ return { recovered: true, error: null };
1814
+ }
1815
+
1816
+ // 有 dirty 或有未应用债务:最多尝试 3 次 sync
1817
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
1818
+ try {
1819
+ syncMirror(); // syncMirror 内部已 catch,不会向外抛
1820
+ const currentState = store.getMirrorState();
1821
+ // 成功条件:dirty 为 false 且没有更新一轮的债务
1822
+ // (generation <= applied_generation,恢复后由 syncMirror 里
1823
+ // markMirrorCleanForGeneration 自动把 applied 跟上)
1824
+ if (!currentState?.dirty && currentState.generation <= currentState.applied_generation) {
1825
+ recovered = true;
1826
+ lastError = null;
1827
+ break;
1828
+ }
1829
+ // 仍 dirty 或仍有更新债务:记录最后一次错误供重试耗尽后上报。
1830
+ // 注意:若别的 worker 又失败产生新债务(dirty 仍 true),这是"新债务"
1831
+ // 不是本次失败,继续重试直到耗尽次数。
1832
+ lastError = currentState.last_error || `Sync attempt ${attempt + 1} left mirror dirty or has pending debt`;
1833
+ } catch (syncError) {
1834
+ // syncMirror 理论不抛,fail-safe 兜底
1835
+ const errMsg = syncError?.message ?? String(syncError);
1836
+ logger?.warn?.("recoverMirror: sync attempt failed:", errMsg);
1837
+ lastError = errMsg;
1838
+ }
1839
+ }
1840
+
1841
+ if (!recovered) {
1842
+ logger?.warn?.("dsh-mneme mirror: recover failed after", MAX_ATTEMPTS, "attempts");
1843
+ } else {
1844
+ logger?.warn?.("dsh-mneme mirror: recovered from dirty/pending state");
1845
+ }
1846
+ } catch (error) {
1847
+ // fail-safe:任何意外异常不向外抛
1848
+ lastError = error?.message ?? String(error);
1849
+ logger?.warn?.("dsh-mneme mirror: recover failed with unexpected error:", error);
1850
+ }
1851
+
1852
+ return { recovered, error: recovered ? null : lastError };
1853
+ }
1854
+
1855
+ // getMirrorHealth: 暴露 mirror 同步健康状态,供 api.js /health 使用
1856
+ // (F-NEW-03)。把 DB 的 dirty 0/1 转成 boolean;fail-safe,绝不向外抛。
1857
+ function getMirrorHealth() {
1858
+ try {
1859
+ const state = store.getMirrorState();
1860
+ if (!state) {
1861
+ // 无状态行:返回安全默认值
1862
+ return {
1863
+ dirty: false,
1864
+ last_error: null,
1865
+ last_attempt: null,
1866
+ success_at: null
1867
+ };
1868
+ }
1869
+ return {
1870
+ dirty: Boolean(state.dirty),
1871
+ last_error: state.last_error ?? null,
1872
+ last_attempt: state.last_attempt ?? null,
1873
+ success_at: state.success_at ?? null
1874
+ };
1875
+ } catch (error) {
1876
+ // fail-safe:状态读取失败也不向外抛,但必须显式表达"未知"而非伪装成
1877
+ // 干净(peer blocker 5:真实读取失败要显式 unknown,不得归一为 dirty:false)。
1878
+ logger?.warn?.("getMirrorHealth failed:", error);
1879
+ return {
1880
+ dirty: null,
1881
+ last_error: error?.message ?? String(error),
1882
+ last_attempt: null,
1883
+ success_at: null
1884
+ };
1885
+ }
1886
+ }
1887
+
1888
+ // 返回字面量与内部裁决器(resolveConflictPending → applyDecisions 的 conflict
1889
+ // 处置)共用的写路径:mirror 同步、写通知、嵌入调度全部同源,不能各写一份。
1890
+ function updateMemory(id, p, ctx = {}) {
1891
+ const old = store.getById(id);
1892
+ // Issue #135 附属发现 2:质量过滤器把「为什么被降权/归档」写在系统信号标签
1893
+ // 上(SIGNAL_TAGS,applyQualityDisposition 以并集写入),而这里整组替换
1894
+ // tags——任何带 tags 的更新都会抹掉这条唯一的审计线索(报告实测 150 条低分
1895
+ // 记忆里恰好缺的 2 条就是被 update 过的,并因此误判过归档来源)。把 existing
1896
+ // 的系统信号标签并集保留;用户自传的标签照常生效。
1897
+ let patch = (p && Array.isArray(p.tags) && old && Array.isArray(old.tags))
1898
+ ? { ...p, tags: [...new Set([...p.tags, ...old.tags.filter((t) => SIGNAL_TAGS.includes(t))])] }
1899
+ : p;
1900
+ // v0.8.1 底座(issue #170):显式 scope 修正。patch 携带 agent_scope /
1901
+ // workspace_scope 键(undefined=该维不动)时归一化并盖 explicit 章 +
1902
+ // scope_decided_at,随后写 scope_changes 审计行(actor:tool=模型侧 /
1903
+ // panel=人工侧)。审计失败只 warn,不反噬主写入。
1904
+ const nextAgentScope = p && p.agent_scope !== undefined ? normalizeExplicitScope(p.agent_scope) : undefined;
1905
+ const nextWorkspaceScope = p && p.workspace_scope !== undefined ? normalizeExplicitScope(p.workspace_scope) : undefined;
1906
+ const scopeChanged = nextAgentScope !== undefined || nextWorkspaceScope !== undefined;
1907
+ if (scopeChanged) {
1908
+ const decidedAt = new Date().toISOString();
1909
+ patch = { ...patch };
1910
+ if (nextAgentScope !== undefined) {
1911
+ patch.agent_scope = nextAgentScope;
1912
+ patch.agent_scope_source = "explicit";
1913
+ }
1914
+ if (nextWorkspaceScope !== undefined) {
1915
+ patch.workspace_scope = nextWorkspaceScope;
1916
+ patch.workspace_scope_source = "explicit";
1917
+ }
1918
+ patch.scope_decided_at = decidedAt;
1919
+ }
1920
+ const updated = store.update(id, patch);
1921
+ if (scopeChanged && old && updated) {
1922
+ try {
1923
+ store.saveScopeChange({
1924
+ memory_id: id,
1925
+ actor: ctx.actor === "panel" ? "panel" : "tool",
1926
+ prev_agent_scope: old.agent_scope ?? null,
1927
+ prev_workspace_scope: old.workspace_scope ?? null,
1928
+ next_agent_scope: updated.agent_scope ?? null,
1929
+ next_workspace_scope: updated.workspace_scope ?? null,
1930
+ agent_scope_source: updated.agent_scope_source ?? null,
1931
+ workspace_scope_source: updated.workspace_scope_source ?? null,
1932
+ decided_at: patch.scope_decided_at
1933
+ });
1934
+ } catch (e) {
1935
+ try { ctx.logger?.warn?.(`[dsh-mneme] scope change audit failed: ${String(e)}`); } catch { /* 同样不反噬 */ }
1936
+ }
1937
+ }
1938
+ // Record a user correction when any meaningful field changed and the
1939
+ // reflection failure tracker is enabled. expected = what it became,
1940
+ // actual = what it was before; query (when provided) captures the
1941
+ // user's original intent so later reflection can reason about recall.
1942
+ const hasMeaningfulChange = old && updated && (
1943
+ old.content !== updated.content ||
1944
+ old.title !== updated.title ||
1945
+ old.importance !== updated.importance
1946
+ );
1947
+ if (hasMeaningfulChange && config.reflectionFailureTracking) {
1948
+ store.saveFailure({
1949
+ id: randomUUID(),
1950
+ query: ctx.query ?? null,
1951
+ expected: updated.content,
1952
+ actual: old.content,
1953
+ before: { title: old.title, content: old.content, importance: old.importance },
1954
+ failure_type: "user_correction",
1955
+ memory_id: id
1956
+ });
1957
+ }
1958
+ const sync = afterSync("write");
1959
+ notifyWrite();
1960
+ scheduleEmbed(updated);
1961
+ // Audit peer B: when the mirror sync failed, the store write landed but
1962
+ // the mirror did not converge — return an explicit degraded receipt rather
1963
+ // than a plain success. Non-enumerable so existing deepEqual assertions on
1964
+ // the memory shape keep passing.
1965
+ if (!sync?.success && !sync?.deferred) {
1966
+ Object.defineProperty(updated, "_mirror", {
1967
+ value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1968
+ enumerable: false,
1969
+ configurable: true
1970
+ });
1971
+ }
1972
+ return updated;
1973
+ }
1974
+
1975
+ function archiveMemory(id, f) {
1976
+ const updated = store.setArchived(id, f);
1977
+ afterSync("write");
1978
+ return updated;
1979
+ }
1980
+
1981
+ return {
1982
+ saveWithDedupe,
1983
+ recoverMirror,
1984
+ getMirrorHealth,
1985
+ getMirrorState: () => store.getMirrorState(),
1986
+ injectCandidates,
1987
+ mergeHumanEdits,
1988
+ toApiList,
1989
+ isVisibleInScope,
1990
+ transaction,
1991
+ enqueue,
1992
+ setDreamHook(fn) { dreamHook = fn; },
1993
+ setSleepHook(fn) { sleepHook = fn; },
1994
+ setEmbedder(emb) {
1995
+ embedder = emb;
1996
+ if (!emb) {
1997
+ // embedder removed (init failed in index.js): stop polling and drop
1998
+ // queued re-embeds — search just degrades to keyword.
1999
+ stopEmbedReadyPolling();
2000
+ embedPending = [];
2001
+ return;
2002
+ }
2003
+ if (emb.ready === true) {
2004
+ flushEmbedPending();
2005
+ return;
2006
+ }
2007
+ // Async-initializing embedder: poll `ready` until it flips, then flush.
2008
+ if ("ready" in emb && embedReadyTimer === null) {
2009
+ let attempts = 0;
2010
+ embedReadyTimer = setInterval(() => {
2011
+ attempts++;
2012
+ if (emb.ready === true || attempts >= EMBED_READY_POLL_LIMIT) {
2013
+ stopEmbedReadyPolling();
2014
+ if (emb.ready === true) flushEmbedPending();
2015
+ else embedPending = []; // init never landed: drop the queue
2016
+ }
2017
+ }, EMBED_READY_POLL_MS);
2018
+ }
2019
+ },
2020
+ setEntityExtractor(fn) { entityExtractor = fn; },
2021
+ setVectorIndex(vi) { vectorIndex = vi; },
2022
+ setReranker(rn) { reranker = rn; },
2023
+ setRecallRecorder(fn) { recallRecorder = fn; },
2024
+ searchMemories,
2025
+ // recallStats(#217)实现在 src/recall-stats.js:service.js 过 2000 行参考线,
2026
+ // 新内聚块独立成模块(AGENTS.md 尺寸约定);这里只留 barrel 出口,调用方
2027
+ // (api 层)零改动。纯读聚合,见模块注释的口径说明。
2028
+ recallStats: (options) => recallStats(store, options),
2029
+ embedQuery,
2030
+ findSessionDuplicate,
2031
+ evaluateRetrieval,
2032
+ computeRetrievalMetrics,
2033
+ // passthroughs used by tools and api layers; mutations keep the mirror in sync
2034
+ search: (q, o) => store.search(q, o),
2035
+ searchVector: (v, o) => store.searchVector(v, o),
2036
+ embeddedCount: () => store.embeddedCount(),
2037
+ list: (o) => store.list(o),
2038
+ all: () => store.all(),
2039
+ count: (type, opts) => store.count(type, opts),
2040
+ getById: (id) => store.getById(id),
2041
+ remove: (id) => {
2042
+ store.remove(id);
2043
+ afterSync("write");
2044
+ notifyWrite();
2045
+ },
2046
+ update: updateMemory,
2047
+ // v0.8.1 底座:scope 归属修正审计(单条记忆,新→旧)。
2048
+ listScopeChanges: (memoryId, opts) => store.listScopeChanges(memoryId, opts),
2049
+ // Compare-and-set update: applies the patch only when the row still carries
2050
+ // `expectedUpdatedAt`. Returns undefined on a miss (no write) so the caller
2051
+ // can re-read and retry — the primitive that prevents lost updates across
2052
+ // concurrent read-modify-write (see scripts/stress-dsh.js axis 3).
2053
+ compareAndUpdate: (id, expectedUpdatedAt, patch, ctx = {}) => {
2054
+ const old = store.getById(id);
2055
+ const updated = store.compareAndUpdate(id, expectedUpdatedAt, patch);
2056
+ if (updated === undefined) return undefined; // CAS miss: no write, no side effects
2057
+ const hasMeaningfulChange = old && updated && (
2058
+ old.content !== updated.content ||
2059
+ old.title !== updated.title ||
2060
+ old.importance !== updated.importance
2061
+ );
2062
+ if (hasMeaningfulChange && config.reflectionFailureTracking) {
2063
+ store.saveFailure({
2064
+ id: randomUUID(),
2065
+ query: ctx.query ?? null,
2066
+ expected: updated.content,
2067
+ actual: old.content,
2068
+ before: { title: old.title, content: old.content, importance: old.importance },
2069
+ failure_type: "user_correction",
2070
+ memory_id: id
2071
+ });
2072
+ }
2073
+ const sync = afterSync("write");
2074
+ notifyWrite();
2075
+ scheduleEmbed(updated);
2076
+ // Audit peer B: mirror sync failure on a CAS write must surface too.
2077
+ if (!sync?.success && !sync?.deferred) {
2078
+ Object.defineProperty(updated, "_mirror", {
2079
+ value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
2080
+ enumerable: false,
2081
+ configurable: true
2082
+ });
2083
+ }
2084
+ return updated;
2085
+ },
2086
+ setForget: (id, f) => {
2087
+ const updated = store.setForget(id, f);
2088
+ afterSync("write");
2089
+ return updated;
2090
+ },
2091
+ setArchived: archiveMemory,
2092
+ // sleep-mode storage (v0.4.0). demoteToSummary / restoreContent mutate
2093
+ // content so they ride the normal write-hook path (mirror re-renders).
2094
+ // touchLastAccess is a read-stamp — deliberately NO write hook (a recall
2095
+ // must not dirty the mirror). getUnrecalledSince is a pure read.
2096
+ demoteToSummary: (id, summary, opts) => {
2097
+ const updated = store.demoteToSummary(id, summary, opts);
2098
+ afterSync("write");
2099
+ return updated;
2100
+ },
2101
+ restoreContent: (id) => {
2102
+ const updated = store.restoreContent(id);
2103
+ afterSync("write");
2104
+ return updated;
2105
+ },
2106
+ touchLastAccess: (id, at) => store.touchLastAccess(id, at),
2107
+ getUnrecalledSince: (cutMs, opts) => store.getUnrecalledSince(cutMs, opts),
2108
+ // autoDream audit trail: passthroughs deliberately bypass write hooks —
2109
+ // an audit write is bookkeeping, and notifyWrite would loop back into the
2110
+ // dream scheduler that just recorded the run.
2111
+ saveDreamRun: (run) => store.saveDreamRun(run),
2112
+ getDreamRun: (id) => store.getDreamRun(id),
2113
+ listDreamRuns: (opts) => store.listDreamRuns(opts),
2114
+ // Per-record receipt chain (same bookkeeping semantics as saveDreamRun: an
2115
+ // audit write, never a write-hook-triggering memory mutation).
2116
+ saveReceipt: (r) => store.saveReceipt(r),
2117
+ getReceipt: (id) => store.getReceipt(id),
2118
+ listReceipts: (opts) => store.listReceipts(opts),
2119
+ // Conflict freeze bookkeeping (same semantics as the audit passthroughs
2120
+ // above: an audit write, never a write-hook-triggering memory mutation).
2121
+ saveConflictPending: (r) => store.saveConflictPending(r),
2122
+ listConflictPending: (opts) => store.listConflictPending(opts),
2123
+ listConflictQueue,
2124
+ resolveConflictPending,
2125
+ countConflictPending: () => store.countConflictPending(),
2126
+ // Recall evaluation trail (方案 B): audit-bookkeeping semantics like the
2127
+ // dream/recall passthroughs above — a recall_evals write is a snapshot, not
2128
+ // a memory mutation, so it never triggers write hooks.
2129
+ saveRecallEval: (r) => store.saveRecallEval(r),
2130
+ getRecallEval: (id) => store.getRecallEval(id),
2131
+ listRecallEvals: (opts) => store.listRecallEvals(opts),
2132
+ // LLM audit trail (Bug8): bookkeeping semantics like the recall/dream
2133
+ // passthroughs — a saveLlmAudit write never triggers write hooks.
2134
+ saveLlmAudit: (entry) => store.saveLlmAudit(entry),
2135
+ listLlmAudits: (opts) => store.listLlmAudits(opts),
2136
+ countLlmAudits: (opts) => store.countLlmAudits(opts),
2137
+ getLlmAuditStats: (opts) => store.getLlmAuditStats(opts),
2138
+ deleteOldLlmAudits: (before) => store.deleteOldLlmAudits(before),
2139
+ // Entity gene (v0.3.0) passthroughs for the autoDream apply path
2140
+ // (applyDecisions): records supersedes relations after an update and
2141
+ // migrates entity_attrs on merge. Bookkeeping writes like the audit
2142
+ // passthroughs above — never write-hook-triggering memory mutations.
2143
+ saveRelation: (r) => store.saveRelation(r),
2144
+ listEntities: (o) => store.listEntities(o),
2145
+ getRelations: (id) => store.getRelations(id),
2146
+ // v0.7.0 实体热投影:实体热 = 关联记忆 heat 聚合(取 max)。无关联记忆
2147
+ // 或 heatEnabled=false 时返回 null;前端据此决定图谱节点大小/明暗。
2148
+ entityHeat: (entityId) => {
2149
+ if (config.heatEnabled === false) return null;
2150
+ const rels = store.getRelations(entityId) ?? [];
2151
+ let max = -Infinity;
2152
+ for (const rel of rels) {
2153
+ if (!rel.memory_id) continue;
2154
+ const mem = store.getById(rel.memory_id);
2155
+ if (!mem) continue;
2156
+ const h = computeHeat(mem, Date.now(), config);
2157
+ if (h > max) max = h;
2158
+ }
2159
+ return max === -Infinity ? null : max;
2160
+ },
2161
+ saveAttr: (r) => store.saveAttr(r),
2162
+ createEntity: (r) => store.createEntity(r),
2163
+ findEntityByName: (n) => store.findEntityByName(n),
2164
+ findEntityById: (id) => store.findEntityById(id),
2165
+ getAttrsByMemory: (id) => store.getAttrsByMemory(id),
2166
+ // 记忆详情侧栏:一条记忆关联到的实体(entity_attrs.memory_id 反查,纯读)。
2167
+ entitiesForMemory: (id) => store.entitiesForMemory(id),
2168
+ getCurrentAttrs: (id) => store.getCurrentAttrs(id),
2169
+ migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
2170
+ };
2171
+ }