@modusensus/dsh-mneme 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/service.js CHANGED
@@ -1,1489 +1,1489 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { TYPE_FILE } from "./mirror.js";
3
- import { evaluateMemoryQuality } from "./quality-filter.js";
4
- import { createBM25Index } from "./search/bm25.js";
5
- import { adaptiveThreshold } from "./search/adaptive.js";
6
-
7
- const INJECT_TYPES = new Set(["preference", "project", "decision", "summary"]);
8
-
9
- // Epistemic trust weights (v0.4.5): when config.trustEpistemicWeighting is on,
10
- // each recall candidate's existing score is multiplied by the weight of its
11
- // epistemic_status before ranking — measured facts outrank guesses. Missing /
12
- // unknown statuses are unscaled (×1). Off by default, so nothing changes.
13
- const EPISTEMIC_WEIGHTS = { observation: 1.0, inferred: 0.85, subjective: 0.7 };
14
-
15
- // Bug5: content version history cap (FIFO — the newest 20 versions are kept,
16
- // older ones dropped). Entries are {content, source, updated_at}; source marks
17
- // how the version was superseded (auto_merge | human_override | overwrite).
18
- const CONTENT_HISTORY_MAX = 20;
19
-
20
- /** Prepend the previous content to a memory's content_history (FIFO capped). */
21
- function pushContentHistory(existing, source) {
22
- const history = Array.isArray(existing?.content_history) ? existing.content_history : [];
23
- return [
24
- { content: existing?.content ?? "", source, updated_at: new Date().toISOString() },
25
- ...history
26
- ].slice(0, CONTENT_HISTORY_MAX);
27
- }
28
-
29
- /** Bug5: same-title merge appends the new content under a timestamped `---`
30
- * separator instead of overwriting, so a re-noted memory never loses history.
31
- * The `---` line is compatible with the mirror's readHumanEdits (which strips
32
- * only the LAST structural `---` when parsing the human-editable file). */
33
- function appendContent(oldContent, newContent) {
34
- const ts = new Date().toISOString();
35
- return `${oldContent}\n\n---\n[${ts}] ${newContent}`;
36
- }
37
-
38
- /**
39
- * Standard retrieval-quality metrics over the ordered candidate ids actually
40
- * returned vs the ids the evaluator marked relevant (方案 B). Pure + total, so
41
- * callers (and tests) get deterministic numbers without touching a store:
42
- * precision = |relevant ∩ retrieved| / |retrieved|
43
- * recall = |relevant ∩ retrieved| / |expected|
44
- * mrr = 1 / rank of the first relevant doc (0 when none retrieved)
45
- * hit_count is the raw intersection size. Values are rounded to 4 decimals so
46
- * repeated divisions (e.g. 1/3) never surface binary-float noise.
47
- */
48
- export function computeRetrievalMetrics(actualIds, expectedIds) {
49
- const expected = new Set(Array.isArray(expectedIds) ? expectedIds : []);
50
- const actual = Array.isArray(actualIds) ? actualIds : [];
51
- const relevant = actual.filter((id) => expected.has(id)).length;
52
- const round4 = (x) => Math.round(x * 10000) / 10000;
53
- let mrr = 0;
54
- for (let i = 0; i < actual.length; i++) {
55
- if (expected.has(actual[i])) { mrr = 1 / (i + 1); break; }
56
- }
57
- return {
58
- precision: round4(actual.length ? relevant / actual.length : 0),
59
- recall: round4(expected.size ? relevant / expected.size : 0),
60
- mrr: round4(mrr),
61
- hit_count: relevant
62
- };
63
- }
64
-
65
- export function createService({ store, mirror, config, onWrite, logger }) {
66
- // Optional dream scheduler hook, installed via setDreamHook after creation
67
- // (the scheduler holds a reference back to the service, so it cannot be
68
- // passed in the constructor). Fired on the same write events as onWrite.
69
- let dreamHook = null;
70
-
71
- // Optional sleep scheduler hook (v0.4.0), installed via setSleepHook after
72
- // creation. Fired on the same write events as onWrite: it tells the sleep
73
- // scheduler the store just changed so the idle-detection clock resets.
74
- let sleepHook = null;
75
-
76
- // Optional vector embedder, installed via setEmbedder after creation. After
77
- // any content write it fire-and-forgets a re-embed of the row so vector
78
- // search stays in sync; failures are swallowed inside the embedder.
79
- let embedder = null;
80
-
81
- // Optional entity extractor, installed via setEntityExtractor after creation
82
- // (index.js injects it so the service never depends on the LLM directly).
83
- // After a new memory is saved it fire-and-forgets an extraction pass for the
84
- // entity gene (v0.3.0); failures are swallowed so a broken extraction never
85
- // surfaces as a write failure. Extraction only runs when
86
- // config.entityExtractionEnabled is true.
87
- let entityExtractor = null;
88
- let vectorIndex = null;
89
- let reranker = null;
90
-
91
- // Optional recall recorder, installed via setRecallRecorder after creation.
92
- // When searchMemories is called with recordRecall=true it receives the
93
- // actual merged recall scene (candidates + scores + source + threshold) so
94
- // the retrieval layer can be audited/replayed — the sibling of the dream
95
- // judgment-layer audit trail (dream_runs).
96
- let recallRecorder = null;
97
-
98
- // Bug4: semantic recall cache for the injection path. The system-prompt
99
- // interpolator renders context synchronously, so injectCandidates cannot
100
- // fire a fresh async embed. The most recent searchMemories recall is cached
101
- // here (query + ordered candidates) and reused when the injection query
102
- // matches, giving semantic-first injection without breaking the sync render.
103
- let lastSemanticRecall = null;
104
-
105
- // Transaction nesting depth. Inside service.transaction the per-mutation side
106
- // effects (mirror render, write notify, re-embed) are deferred so a ROLLBACK
107
- // never leaves the mirror file diverged from the database; transaction()
108
- // replays them exactly once against the committed state.
109
- let txDepth = 0;
110
-
111
- // Serial task queue (sleep v0.4.0). Long-running background passes — dream
112
- // consolidation, sleep cycles — must never overlap: two sleep runs racing
113
- // would double-demote or double-mint patterns. enqueue chains the task onto
114
- // a promise tail so N callers can queue work that runs strictly one at a
115
- // time. A task that rejects doesn't poison the queue (the tail swallows the
116
- // rejection) but the rejection still propagates to that caller.
117
- let queueTail = Promise.resolve();
118
- function enqueue(fn) {
119
- const next = queueTail.then(fn, fn);
120
- queueTail = next.catch(() => {});
121
- return next;
122
- }
123
-
124
- // issue #6 (part 2): startup race defense. A local embedder (LocalEmbedder /
125
- // Ollama) exposes an async init(), so between `setEmbedder` and init()
126
- // resolving there is a window where embedSingle would throw "not initialized"
127
- // and the re-embed would be silently dropped. When the embedder carries a
128
- // `ready` flag we queue writes in embedPending until init sets ready=true,
129
- // then flush them through the embedder's real interface. Embedders without a
130
- // `ready` flag (legacy OpenAI, instantly usable) keep their old behavior.
131
- let embedPending = [];
132
- let embedReadyTimer = null;
133
- const EMBED_PENDING_MAX = 100; // bound the queue; drop oldest beyond this
134
- const EMBED_READY_POLL_MS = 100;
135
- const EMBED_READY_POLL_LIMIT = 30; // ~3s ceiling; never poll forever
136
-
137
- /** Flush the queued re-embeds once the embedder is ready. Fail-safe. */
138
- function flushEmbedPending() {
139
- if (!embedder || embedPending.length === 0) return;
140
- const batch = embedPending.splice(0, embedPending.length);
141
- for (const memory of batch) {
142
- try {
143
- if (!memory?.id) continue;
144
- if (typeof embedder.schedule === "function") {
145
- embedder.schedule(memory);
146
- } else if (typeof embedder.embedSingle === "function") {
147
- const text = [memory.title, memory.content].filter(Boolean).join("\n");
148
- if (!text) continue;
149
- embedder
150
- .embedSingle(text)
151
- .then((vec) => {
152
- if (Array.isArray(vec) && vec.length) {
153
- store.setEmbedding(memory.id, vec);
154
- }
155
- })
156
- .catch((err) => {
157
- logger?.warn?.("flushEmbedPending embedSingle failed:", err);
158
- });
159
- }
160
- } catch (err) {
161
- logger?.warn?.("flushEmbedPending failed:", err);
162
- }
163
- }
164
- }
165
-
166
- function stopEmbedReadyPolling() {
167
- if (embedReadyTimer) {
168
- clearInterval(embedReadyTimer);
169
- embedReadyTimer = null;
170
- }
171
- }
172
-
173
- function scheduleEmbed(memory) {
174
- try {
175
- if (txDepth > 0) return; // deferred to the transaction's commit
176
- if (!embedder || !memory?.id) return;
177
-
178
- // Readiness gate: embedder exposes `ready` (async init) and is not ready
179
- // yet — queue instead of firing embedSingle into a half-built extractor.
180
- const hasReady = "ready" in embedder;
181
- if (hasReady && embedder.ready !== true) {
182
- if (embedPending.length >= EMBED_PENDING_MAX) embedPending.shift();
183
- embedPending.push(memory);
184
- return;
185
- }
186
-
187
- if (typeof embedder.schedule === "function") {
188
- embedder.schedule(memory);
189
- return;
190
- }
191
-
192
- if (typeof embedder.embedSingle === "function") {
193
- const text = [memory.title, memory.content].filter(Boolean).join("\n");
194
- if (!text) return;
195
-
196
- embedder
197
- .embedSingle(text)
198
- .then((vec) => {
199
- if (Array.isArray(vec) && vec.length) {
200
- store.setEmbedding(memory.id, vec);
201
- }
202
- })
203
- .catch((err) => {
204
- logger?.warn?.("scheduleEmbed embedSingle failed:", err);
205
- });
206
- }
207
- } catch (err) {
208
- logger?.warn?.("scheduleEmbed failed:", err);
209
- }
210
- }
211
-
212
- /**
213
- * Fire-and-forget entity extraction for a freshly saved memory (entity gene
214
- * v0.3.0). Opt-in via config.entityExtractionEnabled; the extractor is
215
- * injected as a hook so the service never needs a direct LLM reference.
216
- * The hook itself is expected to resolve to { ok:boolean } and never throw;
217
- * a thrown rejection is swallowed here as a final fail-safe.
218
- */
219
- function scheduleEntityExtraction(memory) {
220
- if (txDepth > 0) return; // deferred to the transaction's commit
221
- if (!config.entityExtractionEnabled || !entityExtractor) return;
222
- try {
223
- entityExtractor(memory).catch((err) => {
224
- logger?.warn?.("entity extraction failed:", err);
225
- });
226
- } catch (err) {
227
- logger?.warn?.("entity extraction failed:", err);
228
- }
229
- }
230
-
231
- /**
232
- * Cross-encoder rerank over a candidate list (best effort). Reranker
233
- * failures degrade to the original candidate order — reranking is an
234
- * accuracy upgrade, never a correctness gate.
235
- */
236
- async function rerankCandidates(query, candidates, topK) {
237
- if (!reranker || !candidates.length) return candidates.slice(0, topK);
238
- try {
239
- const scored = await reranker.rerank(query, candidates.map((c) => ({ id: c.id, title: c.title, content: c.content })));
240
- if (!Array.isArray(scored)) return candidates.slice(0, topK);
241
- const byId = new Map(candidates.map((c) => [c.id, c]));
242
- const out = [];
243
- for (const s of scored) {
244
- const c = byId.get(s.id);
245
- if (c) { out.push({ ...c, score: s.score, source: "rerank" }); if (out.length >= topK) break; }
246
- }
247
- return out.length ? out : candidates.slice(0, topK);
248
- } catch {
249
- return candidates.slice(0, topK);
250
- }
251
- }
252
-
253
- /**
254
- * Search for memories attached to a named entity (v0.3.0 Phase 3).
255
- * 合并优先级:entity_attrs.memory_id 精确关联 = 1.0 > 关键词提及 = 0.7;
256
- * attr 命中不覆盖,keyword 只补充召回,最后按 _score 降序取 topK。
257
- * @param {string} entityName
258
- * @param {object} [options]
259
- * @param {number} [options.topK=20]
260
- * @returns {any[]}
261
- */
262
- function searchByEntity(entityName, { topK = 20 } = {}) {
263
- const entity = store.findEntityByName(entityName);
264
- if (!entity) return [];
265
- const attrs = store.getCurrentAttrs(entity.id);
266
- const memoryIds = [...new Set(attrs.map((a) => a.memory_id).filter(Boolean))];
267
- const attrHits = memoryIds.map((id) => store.getById(id)).filter(Boolean);
268
- const keywordHits = store.search(entityName, { limit: topK });
269
- const merged = new Map();
270
- for (const mem of attrHits) merged.set(mem.id, { ...mem, _source: "entity_attr", _score: 1.0 });
271
- for (const mem of keywordHits) {
272
- if (!merged.has(mem.id)) merged.set(mem.id, { ...mem, _source: "keyword", _score: 0.7 });
273
- }
274
- const hits = Array.from(merged.values()).sort((a, b) => b._score - a._score).slice(0, topK);
275
- touchRecalled(hits);
276
- return hits;
277
- }
278
-
279
- /**
280
- * Search for memories by attribute key/value (v0.3.0 Phase 3).
281
- * value 为空时由 store.findMemoriesByAttr 返回该 key 的全部有效记忆。
282
- * @param {string} key
283
- * @param {string | undefined} value
284
- * @param {object} [options]
285
- * @param {number} [options.topK=20]
286
- * @returns {any[]}
287
- */
288
- function searchByAttr(key, value, { topK = 20 } = {}) {
289
- if (!key) return [];
290
- // value 可能为 undefined(attr:key 无 = 值):归一为空串后交给
291
- // store.findMemoriesByAttr —— 空 value 契约 = 返回该 attr_key 的全部
292
- // 当前有效记忆(v0.3.0,store.js 已实现)。
293
- const rows = store.findMemoriesByAttr(key, value ?? "");
294
- const hits = rows.slice(0, topK);
295
- touchRecalled(hits);
296
- return hits;
297
- }
298
-
299
- /**
300
- * Semantic-aware memory search: keyword recall (store.search) plus optional
301
- * vector recall + rerank. mode:
302
- * auto (default) keyword first, vector fills remaining slots (legacy)
303
- * hybrid vector first, keyword fills remaining slots
304
- * vector vector only, falls back to keyword when unavailable
305
- * keyword text only, never touches the embedder
306
- * useRerank runs the cross-encoder over the merged list when a reranker is
307
- * installed; results carry an extra `score` when reranked.
308
- */
309
- // Weighted blend factor for hybrid search; exposed so callers can tune it.
310
- const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
311
-
312
- // Cosine over two plain arrays (shared by the search-time semantic dedup).
313
- function cosineVec(a, b) {
314
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
315
- let dot = 0, na = 0, nb = 0;
316
- for (let i = 0; i < a.length; i++) {
317
- dot += a[i] * b[i];
318
- na += a[i] * a[i];
319
- nb += b[i] * b[i];
320
- }
321
- if (na === 0 || nb === 0) return 0;
322
- return dot / (Math.sqrt(na) * Math.sqrt(nb));
323
- }
324
-
325
- /**
326
- * BM25 third recall path (v0.5.0 1.1). Scores the query tokens against the
327
- * live non-archived rows and returns the top `limit` hits with scores
328
- * normalized to [0,1]. Failures degrade to [] — BM25 is a recall booster,
329
- * never a correctness gate.
330
- */
331
- function bm25Recall(q, limit) {
332
- if (config?.bm25SearchEnabled === false) return [];
333
- try {
334
- const docs = store.list({ limit: 500, includeForgotten: false }).filter((m) => !m.archived);
335
- if (!docs.length) return [];
336
- return createBM25Index(docs).search(q, { limit });
337
- } catch {
338
- return [];
339
- }
340
- }
341
-
342
- /**
343
- * Search-time semantic dedup (v0.5.0 2.3): greedy pass dropping candidates
344
- * whose embedding similarity to an already-kept row exceeds the threshold.
345
- * Rows without a stored embedding are always kept (no signal = no drop).
346
- */
347
- function semanticDeduplicate(candidates) {
348
- // Opt-in aggressive mode (default off): collapsing near-duplicates can
349
- // drop legitimately distinct rows on small embedding models, so it ships
350
- // behind searchSemanticDedup=true.
351
- if (config?.searchSemanticDedup !== true || candidates.length < 2) return candidates;
352
- const threshold = config?.searchSemanticDedupThreshold ?? 0.95;
353
- try {
354
- const vecs = store.getEmbeddings(candidates.map((c) => c.id));
355
- if (vecs.size < 2) return candidates;
356
- const kept = [];
357
- for (const c of candidates) {
358
- const v = vecs.get(c.id);
359
- if (!v) { kept.push(c); continue; }
360
- const dup = kept.some((k) => {
361
- const kv = vecs.get(k.id);
362
- return kv && cosineVec(v, kv) > threshold;
363
- });
364
- if (!dup) kept.push(c);
365
- }
366
- return kept;
367
- } catch {
368
- return candidates;
369
- }
370
- }
371
-
372
- /**
373
- * Give a keyword-hit row a relevance score in [0,1]: title hits score
374
- * higher than content hits, then scaled by importance (1-5). This lets
375
- * keyword results participate in weighted hybrid blends.
376
- */
377
- function scoreKeyword(row, q) {
378
- const ql = q.toLowerCase();
379
- const title = (row.title ?? "").toLowerCase();
380
- const content = (row.content ?? "").toLowerCase();
381
- const titleHit = title.includes(ql);
382
- const base = titleHit ? 1 : content.includes(ql) ? 0.6 : 0.3;
383
- return base * (0.5 + (row.importance ?? 3) / 10);
384
- }
385
-
386
- /**
387
- * Sleep touch (v0.4.0): when sleep is enabled, any memory surfaced by recall
388
- * or auto-injection gets its last_accessed_at bumped, so the "unrecalled N
389
- * days → demote/archive" tiering counts real access. Best-effort and gated on
390
- * config.sleepModeEnabled — when sleep is off this is a complete no-op (no
391
- * writes on the hot recall path). A touch failure must never break search/inject.
392
- */
393
- function touchRecalled(memories) {
394
- if (config?.sleepModeEnabled !== true || !Array.isArray(memories) || memories.length === 0) return;
395
- for (const m of memories) {
396
- if (!m?.id) continue;
397
- try {
398
- store.touchLastAccess(m.id);
399
- } catch { /* touch is best effort */ }
400
- }
401
- }
402
-
403
- async function searchMemories(query, options = {}) {
404
- const { mode = "auto", topK = 20, threshold, useRerank = true, recordRecall = false } = options;
405
- const q = String(query ?? "").trim();
406
- if (!q) return [];
407
-
408
- // entity:/attr: 前缀路由(v0.3.0 Phase 3)。entitySearchEnabled 关闭时走原逻辑。
409
- if (config?.entitySearchEnabled) {
410
- if (q.startsWith("entity:")) {
411
- return searchByEntity(q.slice(7).trim(), options);
412
- }
413
- if (q.startsWith("attr:")) {
414
- const [key, value] = q.slice(5).split("=");
415
- return searchByAttr(key, value, options);
416
- }
417
- }
418
-
419
- const lim = topK > 0 ? topK : 20;
420
-
421
- // Keyword results, decorated with a score so they can be weight-blended
422
- // with vector results and reported uniformly. source tracks where each
423
- // candidate came from for the recall layer receipt.
424
- const rawKeyword = store.search(q, { limit: lim });
425
- const keyword = rawKeyword.map((m) => ({ ...m, score: scoreKeyword(m, q), source: "keyword" }));
426
- const wantVector = mode === "vector" || mode === "hybrid" || (mode === "auto" && !!embedder);
427
- let vector = [];
428
- if (wantVector && embedder) {
429
- try {
430
- // Legacy embedders expose embed(query); local ones expose embedSingle.
431
- const embedSingle = typeof embedder.embedSingle === "function"
432
- ? embedder.embedSingle.bind(embedder)
433
- : embedder.embed.bind(embedder);
434
- const qv = await embedSingle(q);
435
- if (qv?.length) {
436
- // Adaptive threshold (v0.5.0 1.2): the fetch runs at the loosest
437
- // branch floor so the head-gap rule can still re-admit the tail;
438
- // the final cutoff is computed against the fetched score
439
- // distribution. Explicit `threshold` wins; disabled → legacy 0.
440
- const adaptive = config?.adaptiveThresholdEnabled !== false;
441
- const fetchThreshold = adaptive && threshold === undefined
442
- ? Math.min(0.5, adaptiveThreshold(q))
443
- : (threshold ?? 0);
444
- const search = vectorIndex
445
- ? vectorIndex.search(qv, { limit: lim * 2, threshold: fetchThreshold })
446
- : store.searchVector(qv, { limit: lim * 2, threshold: fetchThreshold });
447
- const finalThreshold = adaptive && threshold === undefined
448
- ? adaptiveThreshold(q, search)
449
- : (threshold ?? 0);
450
- vector = search
451
- .filter((m) => (m.score ?? 1) >= finalThreshold)
452
- .map((m) => ({ ...m, vector: true, source: "vector" }));
453
- }
454
- } catch { /* vector unavailable: keep keyword results */ }
455
- }
456
-
457
- // BM25 third path (v0.5.0 1.1): IDF-weighted token overlap recalls rows
458
- // whose query terms are scattered — the gap LIKE substring matching
459
- // cannot close. Scores are already normalized to [0,1].
460
- const bm25 = bm25Recall(q, lim).map((m) => ({ ...m, source: "bm25" }));
461
- // Loose blend weight: BM25 confirms and backfills, never dominates the
462
- // semantic signal. Same-memory overlap boosts, unseen ids backfill.
463
- const wb = 0.3;
464
- // Path bookkeeping for the boost rule below: which ids each semantic
465
- // recall path surfaced.
466
- const vectorIds = new Set(vector.map((m) => m.id));
467
- const keywordIds = new Set(keyword.map((m) => m.id));
468
-
469
- // Hybrid blending weights from config when provided.
470
- const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
471
- const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
472
-
473
- let merged;
474
- if (mode === "keyword") {
475
- merged = keyword;
476
- } else if (mode === "vector" || mode === "hybrid") {
477
- // semantic-first: vector recalls lead, keyword + BM25 fill remaining
478
- // slots. Weighted blend when sides scored the same memory; otherwise
479
- // vector order leads (it is the semantic signal), lexical paths
480
- // backfill.
481
- const byId = new Map();
482
- for (const m of vector) {
483
- const rec = byId.get(m.id);
484
- byId.set(m.id, rec ? { ...rec, score: Math.max(rec.score ?? 0, m.score ?? 0) } : m);
485
- }
486
- for (const m of keyword) {
487
- const rec = byId.get(m.id);
488
- if (rec) {
489
- // Same memory from both sides: blend the scores.
490
- byId.set(m.id, { ...rec, score: (rec.score ?? 0) * wv + (m.score ?? 0) * wk });
491
- } else {
492
- byId.set(m.id, m);
493
- }
494
- }
495
- for (const m of bm25) {
496
- const rec = byId.get(m.id);
497
- if (rec) {
498
- // Boost rule: a row the LIKE keyword path already hit carries the
499
- // query as a substring, so BM25 tokens are trivially present —
500
- // boosting it double-counts lexical evidence. Only vector-recalled
501
- // rows (lexical hit is genuinely new information) get the boost.
502
- if (keywordIds.has(m.id)) continue;
503
- byId.set(m.id, { ...rec, score: (rec.score ?? 0) + wb * (m.score ?? 0) });
504
- } else {
505
- byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
506
- }
507
- }
508
- const ranked = [...byId.values()]
509
- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
510
- .map((r) => ({ ...r, score: Math.max(0, Math.min(1, r.score ?? 0)) }));
511
- merged = ranked.slice(0, lim);
512
- if (merged.length < lim && !merged.length) {
513
- // Vector unavailable entirely: fall back to plain keyword.
514
- merged = keyword.slice(0, lim);
515
- }
516
- } else {
517
- // auto: keyword leads, vector + BM25 fill remaining slots (legacy
518
- // behavior, extended with the third path)
519
- merged = keyword.slice(0, lim);
520
- const seen = new Set(merged.map((m) => m.id));
521
- for (const m of vector) {
522
- if (merged.length >= lim) break;
523
- if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
524
- }
525
- for (const m of bm25) {
526
- if (merged.length >= lim) break;
527
- if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
528
- }
529
- }
530
-
531
- // Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
532
- // dropped before the reranker sees them, so topK slots carry distinct
533
- // information instead of the same memory twice. Keyword mode is exempt —
534
- // it is the documented text-only path and must not be altered by
535
- // embedding state.
536
- merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
537
- merged = merged.slice(0, lim);
538
- let result = useRerank && reranker && merged.length
539
- ? await rerankCandidates(q, merged, lim)
540
- : merged;
541
- // Epistemic trust (v0.4.5): opt-in re-weighting of the final candidate
542
- // scores by source credibility. When off (default) `result` is returned
543
- // untouched — exactly the legacy behavior.
544
- if (config.trustEpistemicWeighting === true) {
545
- result = result
546
- .map((m) => ({
547
- ...m,
548
- score: (m.score ?? 0) * (EPISTEMIC_WEIGHTS[m.epistemic_status] ?? 1)
549
- }))
550
- .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
551
- .slice(0, lim);
552
- }
553
-
554
- // Recall layer receipt: with recordRecall on, hand the actual merged
555
- // candidate list (id/title/content/score/source) to the injected recorder
556
- // before returning, making the retrieval scene replayable — the sibling of
557
- // the dream judgment-layer audit trail. Recorder failures must never break
558
- // the search itself.
559
- if (recordRecall && recallRecorder) {
560
- try {
561
- recallRecorder({
562
- query: q,
563
- mode,
564
- topK: lim,
565
- threshold: threshold ?? null,
566
- candidates: result.map((m) => ({
567
- id: m.id,
568
- title: m.title,
569
- content: m.content,
570
- score: m.score ?? null,
571
- source: m.source ?? "keyword"
572
- })),
573
- createdAt: new Date().toISOString()
574
- });
575
- } catch { /* recall receipt is best effort */ }
576
- }
577
- // Bug4: cache the latest semantic recall so the sync injection path can
578
- // reuse it when the injection query matches (no async embed available).
579
- lastSemanticRecall = { query: q, items: result };
580
- touchRecalled(result);
581
- return result;
582
- }
583
-
584
- /**
585
- * Retrieval evaluation (方案 B): run one search for `query`, compare the ids
586
- * it actually returned against `expectedIds`, and return the computed
587
- * metrics. When persistence is on (config.evalPersistTestResults, or an
588
- * explicit `persist` override per call) the snapshot is written to the
589
- * recall_evals table — a SEPARATE store from the recall_runs production audit,
590
- * so test/eval data never inflates the production trail.
591
- *
592
- * options:
593
- * mode/topK/threshold/useRerank — passed through to searchMemories
594
- * evalType — label for the snapshot (default 'manual')
595
- * recordRecall — also write a recall_runs audit row for the
596
- * same scene and link it via recall_run_id
597
- * (default false: eval stays unlinked)
598
- * recallRunId — explicit link to an existing recall_runs id
599
- * persist — override the config gate for this call
600
- *
601
- * Returns { metrics, actualIds, expectedIds, recallRunId, persisted }.
602
- * Never throws on persistence failures: a broken eval write must not break
603
- * the retrieval quality measurement.
604
- */
605
- async function evaluateRetrieval(query, expectedIds, options = {}) {
606
- const q = String(query ?? "").trim();
607
- const expected = Array.isArray(expectedIds) ? expectedIds : [];
608
- const {
609
- mode = "auto",
610
- topK = 20,
611
- threshold,
612
- useRerank = true,
613
- evalType = "manual",
614
- recordRecall = false,
615
- recallRunId = null,
616
- persist = config.evalPersistTestResults === true
617
- } = options;
618
- if (!q) {
619
- const empty = computeRetrievalMetrics([], expected);
620
- return { metrics: empty, actualIds: [], expectedIds: expected, recallRunId: null, persisted: false };
621
- }
622
-
623
- const rows = await searchMemories(q, { mode, topK, threshold, useRerank, recordRecall: false });
624
- const actualIds = rows.map((m) => m.id);
625
- const metrics = computeRetrievalMetrics(actualIds, expected);
626
-
627
- // Optional recall_runs audit for the same scene; the eval row then links to
628
- // it. Kept separate from the production recorder (which fires only on
629
- // recordRecall=true inside searchMemories) — eval never double-records.
630
- // An explicit recallRunId wins; recordRecall only mints a NEW audit run when
631
- // the caller did not already link one (never clobber an existing link).
632
- let runId = recallRunId ?? null;
633
- if (recordRecall && runId === null) {
634
- try {
635
- const run = store.saveRecallRun({
636
- query: q,
637
- mode,
638
- topK,
639
- threshold: threshold ?? null,
640
- candidates: rows.map((m) => ({
641
- id: m.id,
642
- title: m.title,
643
- content: m.content,
644
- score: m.score ?? null,
645
- source: m.source ?? "keyword"
646
- })),
647
- created_at: new Date().toISOString()
648
- });
649
- runId = run.id;
650
- } catch { /* non-fatal: the eval itself still succeeds */ }
651
- }
652
-
653
- let persisted = false;
654
- if (persist) {
655
- try {
656
- store.saveRecallEval({
657
- recall_run_id: runId,
658
- query: q,
659
- expected_ids: expected,
660
- actual_ids: actualIds,
661
- metrics,
662
- eval_type: evalType,
663
- created_at: new Date().toISOString()
664
- });
665
- persisted = true;
666
- } catch { /* non-fatal: measurement survives a failed eval write */ }
667
- }
668
- return { metrics, actualIds, expectedIds: expected, recallRunId: runId, persisted };
669
- }
670
-
671
- /**
672
- * Fire-and-forget write notification; errors are swallowed to keep write
673
- * paths clean. The store mutation has already committed, so a throwing
674
- * subscriber must not surface as a write failure. Archive/forget flags are
675
- * state toggles, not content writes, so they never notify.
676
- */
677
- function notifyWrite() {
678
- if (txDepth > 0) return; // deferred to the transaction's commit
679
- if (onWrite) {
680
- try { onWrite(); } catch { /* ignore */ }
681
- }
682
- if (dreamHook) {
683
- try { dreamHook(); } catch { /* ignore */ }
684
- }
685
- if (sleepHook) {
686
- try { sleepHook(); } catch { /* ignore */ }
687
- }
688
- }
689
-
690
- /**
691
- * Run several store mutations atomically (SQLite BEGIN/COMMIT/ROLLBACK) and
692
- * fire the deferred side effects once against the committed state. A throwing
693
- * body rolls the whole batch back — no partial writes, no diverged mirror.
694
- * Errors propagate to the caller. NOTE: the commit path re-renders the mirror
695
- * and notifies subscribers, but re-embedding is left to the caller (the dream
696
- * flow re-embeds through maintainIndexAfterDream).
697
- */
698
- function transaction(fn) {
699
- store.db.exec("BEGIN");
700
- txDepth++;
701
- try {
702
- const result = fn();
703
- store.db.exec("COMMIT");
704
- return result;
705
- } catch (error) {
706
- try { store.db.exec("ROLLBACK"); } catch { /* store may be closed */ }
707
- throw error;
708
- } finally {
709
- txDepth--;
710
- // Sync failures are surfaced, not swallowed (peer blocker 2): the mirror
711
- // debt was already recorded by markMirrorDirty inside syncMirror, so a
712
- // restart recovers — but the operator must see it now, not after restart.
713
- const syncResult = syncMirror();
714
- if (!syncResult?.success && !syncResult?.deferred) {
715
- logger?.warn?.("mirror sync failed after transaction:", syncResult?.error);
716
- }
717
- notifyWrite();
718
- }
719
- }
720
-
721
- /**
722
- * Embed an arbitrary query text and return its vector (null on failure / no
723
- * embedder). Used by the injector to prefetch the semantic-first recall
724
- * vector for the current user message — the system-prompt render is
725
- * synchronous, so the vector must be cached in advance (Bug4).
726
- */
727
- async function embedQuery(query) {
728
- const q = String(query ?? "").trim();
729
- if (!q || !embedder) return null;
730
- try {
731
- const embedSingle = typeof embedder.embedSingle === "function"
732
- ? embedder.embedSingle.bind(embedder)
733
- : embedder.embed.bind(embedder);
734
- const vector = await embedSingle(q);
735
- return Array.isArray(vector) && vector.length ? vector : null;
736
- } catch {
737
- return null;
738
- }
739
- }
740
-
741
- /**
742
- * Save a memory, merging into an existing one when title matches within the same type.
743
- *
744
- * Bug5: a same-title merge no longer overwrites — the new content is appended
745
- * under a timestamped `---` separator (`旧内容\n\n---\n[时间戳] 新内容`) and the
746
- * previous content is archived into content_history (source: auto_merge, FIFO
747
- * capped at 20). importance takes the max of both (capped at 5). Callers that
748
- * truly replace a row (dream summary regeneration) pass `_overwrite: true` to
749
- * overwrite directly while still archiving the old version (source: overwrite).
750
- * mergeHumanEdits entry points pass `_humanEdited: true` — same direct
751
- * overwrite semantics, source: human_override.
752
- *
753
- * Bug7 (memory quality filter): when config.memoryQualityFilter.enabled, the
754
- * memory is scored after dedupe, before write:
755
- * score >= degradeThreshold → stored normally (score persisted)
756
- * archiveThreshold <= score < 60 → persisted + ranked degraded
757
- * score < archiveThreshold → archived + tagged low_quality (still
758
- * explicitly searchable via includeArchived)
759
- * @returns {{action: "created"|"merged", memory: object}}
760
- */
761
- function saveWithDedupe(memory) {
762
- // Bug7: score quality once (after dedupe lookup, before write). Failures
763
- // inside the evaluator are impossible (pure function), but the write that
764
- // records the score must never fail the save — wrap defensively.
765
- const qf = config.memoryQualityFilter;
766
- let quality = null;
767
- if (qf?.enabled === true) {
768
- try {
769
- const recentContents = store.all().slice(0, 20).map((m) => m.content ?? "");
770
- quality = evaluateMemoryQuality(memory, {
771
- minContentLength: qf.minContentLength ?? 10,
772
- recentContents
773
- });
774
- } catch { /* quality scoring is best-effort */ }
775
- }
776
- const existing = store
777
- .list({ type: memory.type, limit: 100 })
778
- .find((m) => m.title.trim() === String(memory.title).trim());
779
- if (existing) {
780
- const newContent = String(memory.content ?? "");
781
- if (!newContent.trim()) {
782
- // Nothing to merge: the row stays untouched.
783
- return { action: "merged", memory: existing };
784
- }
785
- const direct = memory._overwrite === true || memory._humanEdited === true;
786
- const content = direct
787
- ? newContent
788
- : appendContent(existing.content, newContent);
789
- const importance = Math.min(5, Math.max(existing.importance, memory.importance ?? existing.importance));
790
- const merged = store.update(existing.id, {
791
- content,
792
- importance,
793
- tags: memory.tags ?? existing.tags,
794
- title: memory.title ?? existing.title,
795
- content_history: pushContentHistory(existing, direct
796
- ? (memory._humanEdited === true ? "human_override" : "overwrite")
797
- : "auto_merge"),
798
- ...(quality ? { quality_score: quality.score } : {})
799
- });
800
- // Bug7: a degraded/archived result is applied on top of the merged row.
801
- const result = applyQualityDisposition(merged, quality, qf);
802
- afterSync("write");
803
- notifyWrite();
804
- scheduleEmbed(result);
805
- return { action: "merged", memory: result };
806
- }
807
- const created = store.save({
808
- type: memory.type,
809
- title: memory.title,
810
- content: memory.content,
811
- tags: memory.tags ?? [],
812
- importance: memory.importance ?? 3,
813
- source: memory.source ?? "manual",
814
- // Provenance (v0.5.x): birth session rides through the create path; the
815
- // merge path above preserves the original row's session_id untouched.
816
- session_id: memory.session_id ?? undefined,
817
- ...(quality ? { quality_score: quality.score } : {})
818
- });
819
- const result = applyQualityDisposition(created, quality, qf);
820
- afterSync("write");
821
- notifyWrite();
822
- scheduleEmbed(result);
823
- scheduleEntityExtraction(result);
824
- return { action: "created", memory: result };
825
- }
826
-
827
- /**
828
- * Bug7: apply the quality verdict to a freshly written row. Below the archive
829
- * threshold the memory is archived + tagged low_quality (still searchable
830
- * explicitly via includeArchived); between archive and degrade thresholds the
831
- * score is already persisted and only the injection ranking is affected
832
- * (importance × score/100). Best-effort: a disposition write failure must
833
- * never fail the save. Returns the (possibly refreshed) memory row so callers
834
- * see the archived/tagged state, not the pre-disposition snapshot.
835
- */
836
- function applyQualityDisposition(memory, quality, qf) {
837
- if (!quality || qf?.enabled !== true) return memory;
838
- const archiveThreshold = qf.archiveThreshold ?? 30;
839
- // Signal tags (meta / repetitive / duplicate / short_content / low_quality)
840
- // are merged onto the stored row in every assessed band so the verdict is
841
- // observable, not just the numeric score. Below the archive threshold the
842
- // memory is additionally archived (still explicitly searchable).
843
- const tags = [...new Set([...(memory.tags ?? []), ...(quality.tags ?? [])])];
844
- if (tags.length === (memory.tags?.length ?? 0) && quality.score >= archiveThreshold) {
845
- return memory; // no tag drift and not archived → nothing extra to write
846
- }
847
- try {
848
- store.update(memory.id, { tags, quality_score: quality.score });
849
- if (quality.score < archiveThreshold) store.setArchived(memory.id, true);
850
- return store.getById(memory.id);
851
- } catch {
852
- return memory;
853
- }
854
- }
855
-
856
- /**
857
- * Candidate memories for automatic context injection:
858
- * summaries first, then all preferences, then non-forgotten items with
859
- * importance >= threshold. History is never auto-injected. Archived entries
860
- * are excluded (store.list already filters them by default; the extra
861
- * !m.archived check is kept as double insurance).
862
- *
863
- * Bug4 (hybridInject): when a non-empty `query` is available and a matching
864
- * semantic recall was cached by the last searchMemories, the vector hits
865
- * lead the selection (up to maxItems*2 candidates) and the rule-based pick
866
- * fills + dedupes the remaining slots. Empty query / no cached recall /
867
- * hybridInject off → pure legacy rule-based selection.
868
- */
869
- function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector } = {}) {
870
- const q = String(query ?? "").trim();
871
- // Bug7: quality-weighted importance in the rule-based tier. Unassessed rows
872
- // (quality_score null) count as 100 (weight 1), so legacy stores keep their
873
- // exact summary>preference>importance ordering.
874
- const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
875
- const items = store.list({ limit: 200, includeForgotten: false })
876
- .filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
877
- (m.type === "summary" || m.type === "preference" || m.importance >= threshold))
878
- .sort((a, b) => {
879
- const pa = a.type === "summary" ? 0 : a.type === "preference" ? 1 : 2;
880
- const pb = b.type === "summary" ? 0 : b.type === "preference" ? 1 : 2;
881
- return pa - pb || (b.importance * qualityWeight(b)) - (a.importance * qualityWeight(a));
882
- });
883
- let candidates = items;
884
- if (config.hybridInject !== false && q) {
885
- // Bug4: semantic-first recall. Vector hits (queryVector, cached by the
886
- // injector's async prefetch) lead when present; otherwise the last
887
- // searchMemories recall for the exact same query is reused. Rule-based
888
- // items fill + dedupe the remaining slots. Empty query / no vector /
889
- // no cached recall → pure legacy rule-based selection.
890
- const semanticItems = [];
891
- if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
892
- try {
893
- const hits = vectorIndex.search(queryVector, { limit: maxItems * 2, threshold: 0 });
894
- for (const m of hits) {
895
- if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
896
- (m.type === "summary" || m.type === "preference" || m.importance >= threshold)) {
897
- semanticItems.push(m);
898
- }
899
- }
900
- } catch { /* vector unavailable: fall through to the recall cache */ }
901
- }
902
- if (!semanticItems.length && lastSemanticRecall?.query === q && lastSemanticRecall.items?.length) {
903
- for (const m of lastSemanticRecall.items) {
904
- if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten) semanticItems.push(m);
905
- }
906
- }
907
- if (semanticItems.length) {
908
- const seen = new Set();
909
- const merged = [];
910
- const push = (m) => {
911
- if (seen.has(m.id)) return;
912
- seen.add(m.id);
913
- merged.push(m);
914
- };
915
- for (const m of semanticItems) {
916
- push(m);
917
- if (merged.length >= maxItems * 2) break;
918
- }
919
- for (const m of items) {
920
- if (merged.length >= maxItems * 2) break;
921
- push(m);
922
- }
923
- candidates = merged;
924
- }
925
- }
926
- // Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
927
- // available the whole candidate list is re-ordered by similarity to that
928
- // vector, so the injected slots go to memories on the current topic
929
- // rather than to the rule-based order. Rows the index did not return
930
- // keep their relative order after the scored ones.
931
- if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
932
- try {
933
- const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
934
- const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
935
- if (sim.size) {
936
- candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
937
- }
938
- } catch { /* topic re-rank unavailable: keep rule-based order */ }
939
- }
940
- const selected = candidates.slice(0, maxItems);
941
- touchRecalled(selected);
942
- return selected;
943
- }
944
-
945
- /**
946
- * Merge human edits parsed from a mirror file back into the store.
947
- * Only content/title are taken; structure fields stay machine-owned.
948
- */
949
- function mergeHumanEdits(type, edits) {
950
- let applied = 0;
951
- for (const edit of edits) {
952
- if (!edit.id) continue; // corrupt/malformed edit: skip it, keep merging the rest
953
- const existing = store.getById(edit.id);
954
- if (!existing || existing.type !== type) continue;
955
- const patch = {};
956
- if (typeof edit.title === "string" && edit.title.trim()) patch.title = edit.title.trim();
957
- if (typeof edit.content === "string" && edit.content.trim()) patch.content = edit.content.trim();
958
- if (Object.keys(patch).length) {
959
- // 启动回灌(F-NEW-01):digest 存在且匹配 = 文件自渲染后无人触碰(旧机器
960
- // 镜像),机器 wins,DB 的 New 必须保留,静默改回 Old 是 bug。
961
- const digestMatches = typeof edit.digest === "string"
962
- && typeof edit.title === "string"
963
- && typeof edit.content === "string"
964
- && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
965
- if (digestMatches) continue;
966
- // 文件 == store(无实际变化)时不覆盖,也不计入 applied。
967
- const hasDiff = (patch.title !== undefined && existing.title !== patch.title)
968
- || (patch.content !== undefined && existing.content !== patch.content);
969
- if (!hasDiff) continue;
970
- // 人工编辑回灌后触发 re-embed(issue #3 残留修复):向量必须与
971
- // 新 title/content 一致。scheduleEmbed 为 fire-and-forget,
972
- // 内部 try/catch 吞错,失败不影响主流程。
973
- // Bug5: human edits overwrite directly, but the machine version is
974
- // archived into content_history (source: human_override) before being
975
- // replaced, so a manual correction never silently destroys the old value.
976
- const merged = store.update(edit.id, {
977
- ...patch,
978
- content_history: patch.content !== undefined && existing.content !== patch.content
979
- ? pushContentHistory(existing, "human_override")
980
- : existing.content_history
981
- });
982
- applied++;
983
- scheduleEmbed(merged);
984
- }
985
- }
986
- if (applied) {
987
- afterSync("write");
988
- notifyWrite();
989
- }
990
- return applied;
991
- }
992
-
993
- function toApiList(rows) {
994
- return rows.map((m) => ({
995
- id: m.id,
996
- type: m.type,
997
- title: m.title,
998
- content: m.content,
999
- tags: m.tags,
1000
- importance: m.importance,
1001
- source: m.source,
1002
- created_at: m.created_at,
1003
- updated_at: m.updated_at
1004
- }));
1005
- }
1006
-
1007
- /**
1008
- * Three-way merge of in-flight human mirror edits before a re-render.
1009
- * Runs on every syncMirror, so a human edit made between two store writes is
1010
- * never silently overwritten by the next sync (human priority is not limited
1011
- * to startup). Per edited entry:
1012
- * - file changed only → human wins; the edit is merged back into the store.
1013
- * - file AND store changed → real three-way conflict: keep the human edit
1014
- * and append a marker preserving the store's concurrent version, so no
1015
- * side is dropped.
1016
- * - store changed only → store wins (the file is simply re-rendered).
1017
- * Only title/content are taken (structure fields stay machine-owned, matching
1018
- * mergeHumanEdits). Returns the memory list to render.
1019
- */
1020
- function reconcileHumanEdits(memories) {
1021
- if (!mirror) return memories;
1022
- const byType = new Map();
1023
- for (const m of memories) {
1024
- if (!byType.has(m.type)) byType.set(m.type, []);
1025
- byType.get(m.type).push(m);
1026
- }
1027
- const result = [];
1028
- for (const type of Object.keys(TYPE_FILE)) {
1029
- const list = byType.get(type) ?? [];
1030
- if (list.length === 0) continue;
1031
- const editsById = new Map(mirror.readHumanEdits(type).map((e) => [e.id, e]));
1032
- for (const m of list) {
1033
- const edit = editsById.get(m.id);
1034
- if (!edit) { result.push(m); continue; }
1035
- const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
1036
- || (typeof edit.content === "string" && edit.content !== m.content);
1037
- if (!humanChanged) { result.push(m); continue; }
1038
- // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
1039
- // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
1040
- // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
1041
- // 并发人工编辑导致机器写丢失 + 伪冲突标记。
1042
- const digestMatches = typeof edit.digest === "string"
1043
- && typeof edit.title === "string"
1044
- && typeof edit.content === "string"
1045
- && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1046
- if (digestMatches) {
1047
- // 无人触碰,机器 wins,走原样
1048
- result.push(m);
1049
- continue;
1050
- }
1051
- // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
1052
- // (保留现有 storeChanged 逻辑)
1053
- const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
1054
- if (storeChanged) {
1055
- const marker = `\n\n> ⚠️ 并发冲突:人工编辑 vs 记忆库并发更新(${m.updated_at})\n> 记忆库版本:${m.content}`;
1056
- store.update(m.id, { title: edit.title, content: `${edit.content}${marker}` });
1057
- } else {
1058
- store.update(m.id, { title: edit.title, content: edit.content });
1059
- }
1060
- const merged = store.getById(m.id);
1061
- scheduleEmbed(merged);
1062
- result.push(merged);
1063
- }
1064
- }
1065
- return result;
1066
- }
1067
-
1068
- /**
1069
- * Re-render the human-editable mirror after any store mutation, merging any
1070
- * in-flight human edits first (never silently overwriting them). Only
1071
- * non-forgotten memories are mirrored: forgotten entries must not reach the
1072
- * human-editable file (a human "edit" could otherwise resurrect them).
1073
- */
1074
- // syncMirror: 同步 mirror,并在失败/成功时持久记录 dirty 状态;保证自身不抛出。
1075
- // v0.3.6(audit peer 4 阻断):
1076
- // - 开始时 incrementGeneration 绑定本次期望轮次 gen;成功用
1077
- // markMirrorCleanForGeneration(gen, now) CAS/fence 清 dirty——旧 worker
1078
- // (gen 已过期)不会误清另一 worker 未恢复的故障债务;
1079
- // - 失败写 markMirrorDirty(递增 desired 绑定新债务),下次 recover 恢复;
1080
- // - 逐 type 用 setTypeStatus 记录部分成功/失败(type_status JSON);
1081
- // - 所有 store 状态写入各自 try/catch,失败只 warn,绝不向外抛(F-NEW-03)。
1082
- function syncMirror() {
1083
- if (txDepth > 0 || !mirror) return { success: true, deferred: true }; // deferred to the transaction's commit
1084
- const now = new Date().toISOString();
1085
- let gen;
1086
- try {
1087
- // desired generation 已在业务写事务中原子递增(peer blocker 1);这里
1088
- // 直接读当前值作为本次同步的目标轮次,不再自行 incrementGeneration。
1089
- const state = store.getMirrorState();
1090
- gen = state?.generation ?? 0;
1091
- } catch (stateError) {
1092
- logger?.warn?.("syncMirror: getMirrorState failed:", stateError);
1093
- return { success: false, error: stateError?.message ?? String(stateError) };
1094
- }
1095
- // coveredTypes 提到 try 外初始化:即使 store.list 先抛错,catch 分支也有
1096
- // 合法的空 Set 可迭代,保证 syncMirror 自身绝不抛(fail-safe)。
1097
- const coveredTypes = new Set();
1098
- try {
1099
- // 预先获取本次要覆盖的 type 集合(只调一次 store.list)
1100
- const list = store.list({ limit: 500, includeForgotten: false });
1101
- for (const memory of list) {
1102
- if (memory?.type && TYPE_FILE[memory.type]) {
1103
- coveredTypes.add(memory.type);
1104
- }
1105
- }
1106
-
1107
- // Per-type physical outcome (audit peer D): mirror.sync writes each type
1108
- // file independently and reports per-type success/failure. A type whose
1109
- // file was physically committed must be marked committed even when a
1110
- // sibling type errors — the old code batch-failed every type on any error,
1111
- // leaving committed files mislabeled as failed and masking partial state.
1112
- // Absent entries (a type with no memories) count as success: sync prunes
1113
- // the stale file, which is itself a completed physical state.
1114
- let allOk = true;
1115
- const results = mirror.sync(reconcileHumanEdits(list)) ?? {};
1116
- for (const type of Object.keys(TYPE_FILE)) {
1117
- const r = results[type];
1118
- const ok = !r || r.ok === true;
1119
- if (!ok) allOk = false;
1120
- try {
1121
- if (ok) {
1122
- store.setTypeStatus(type, { status: "committed", applied_gen: gen, last_error: null });
1123
- } else {
1124
- store.setTypeStatus(type, { status: "failed", last_error: r.error ?? "mirror sync failed" });
1125
- }
1126
- } catch (stateError) {
1127
- logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1128
- }
1129
- }
1130
-
1131
- // 全部 type 物理收敛:CAS/fence 绑定到本地 gen,旧 worker(gen 已过期)会被
1132
- // 拦截。此步失败说明核心 clean 状态没写成功,向上层报失败(不再静默)。
1133
- if (allOk) {
1134
- try {
1135
- store.markMirrorCleanForGeneration(gen, now);
1136
- } catch (stateError) {
1137
- logger?.warn?.("syncMirror: markMirrorCleanForGeneration failed:", stateError);
1138
- return { success: false, error: stateError?.message ?? String(stateError) };
1139
- }
1140
- return { success: true };
1141
- }
1142
-
1143
- // 部分 type 失败:持久 dirty(债务绑定到新轮次),下次 recover 只补未收敛
1144
- // 的 type。committed 的 type 已应用本轮 gen,不因兄弟失败被回滚。
1145
- const failedTypes = Object.entries(results)
1146
- .filter(([, r]) => r && r.ok === false)
1147
- .map(([t]) => t);
1148
- try {
1149
- store.markMirrorDirty(`mirror sync failed for: ${failedTypes.join(", ")}`, now);
1150
- } catch (stateError) {
1151
- logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1152
- }
1153
- return { success: false, error: `mirror sync failed for: ${failedTypes.join(", ")}` };
1154
- } catch (error) {
1155
- const errMsg = error?.message ?? String(error);
1156
- logger?.warn?.("syncMirror failed:", error);
1157
- try {
1158
- // 债务绑定到新的一轮(desired generation 原子递增;即便 dirty 写失败,
1159
- // generation 已推进,recoverMirror 仍能捕获,不产生 false-clean)。
1160
- store.markMirrorDirty(errMsg, now);
1161
- } catch (stateError) {
1162
- logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1163
- }
1164
- // 逐 type 标记为 failed(applied_gen 不动)
1165
- for (const type of coveredTypes) {
1166
- try {
1167
- store.setTypeStatus(type, { status: "failed", last_error: errMsg });
1168
- } catch (stateError) {
1169
- logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1170
- }
1171
- }
1172
- return { success: false, error: errMsg };
1173
- }
1174
- }
1175
-
1176
- // afterSync: run syncMirror and surface a failure to the operator instead of
1177
- // swallowing it (peer blocker 2 + audit peer B). The mirror debt has already
1178
- // been persisted by markMirrorDirty inside syncMirror, so a restart recovers —
1179
- // but the calling write path must not report clean while the mirror is
1180
- // known-stale. Returns the sync result so the caller can attach an explicit
1181
- // degraded/pending receipt to its return value instead of faking success.
1182
- function afterSync(label) {
1183
- const r = syncMirror();
1184
- if (!r?.success && !r?.deferred) {
1185
- logger?.warn?.(`${label}: mirror sync failed (will recover on restart):`, r?.error);
1186
- }
1187
- return r;
1188
- }
1189
-
1190
- // recoverMirror: 启动/手动 reconcile 时根据持久 dirty 状态决定是否恢复同步
1191
- // (F-NEW-03 + v0.3.6)。触发条件不只是 dirty——还检查
1192
- // generation > applied_generation(有未应用的债务),这样 COMMIT→dirty 崩溃
1193
- // 窗口(DB 提交后、markMirrorDirty/clean 前进程退出 → dirty=false 但
1194
- // generation 不一致)也能被捕获。有界重试(最多 3 次)重跑 syncMirror 收敛;
1195
- // 某次成功后 dirty=false 且无更新债务(generation <= applied_generation)
1196
- // 立即停止。返回 { recovered, error } 供 index.js 启动 / api.js health 判断。
1197
- // 一切 fail-safe,绝不向外抛。
1198
- function recoverMirror() {
1199
- const MAX_ATTEMPTS = 3;
1200
- let lastError = null;
1201
- let recovered = false;
1202
-
1203
- try {
1204
- const state = store.getMirrorState();
1205
- // 崩溃窗口检测:dirty 或 generation > applied_generation(COMMIT→dirty 窗口)
1206
- if (!state?.dirty && !(state.generation > state.applied_generation)) {
1207
- // 本来就干净:无需恢复,视为成功
1208
- return { recovered: true, error: null };
1209
- }
1210
-
1211
- // 有 dirty 或有未应用债务:最多尝试 3 次 sync
1212
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
1213
- try {
1214
- syncMirror(); // syncMirror 内部已 catch,不会向外抛
1215
- const currentState = store.getMirrorState();
1216
- // 成功条件:dirty 为 false 且没有更新一轮的债务
1217
- // (generation <= applied_generation,恢复后由 syncMirror 里
1218
- // markMirrorCleanForGeneration 自动把 applied 跟上)
1219
- if (!currentState?.dirty && currentState.generation <= currentState.applied_generation) {
1220
- recovered = true;
1221
- lastError = null;
1222
- break;
1223
- }
1224
- // 仍 dirty 或仍有更新债务:记录最后一次错误供重试耗尽后上报。
1225
- // 注意:若别的 worker 又失败产生新债务(dirty 仍 true),这是"新债务"
1226
- // 不是本次失败,继续重试直到耗尽次数。
1227
- lastError = currentState.last_error || `Sync attempt ${attempt + 1} left mirror dirty or has pending debt`;
1228
- } catch (syncError) {
1229
- // syncMirror 理论不抛,fail-safe 兜底
1230
- const errMsg = syncError?.message ?? String(syncError);
1231
- logger?.warn?.("recoverMirror: sync attempt failed:", errMsg);
1232
- lastError = errMsg;
1233
- }
1234
- }
1235
-
1236
- if (!recovered) {
1237
- logger?.warn?.("dsh-mneme mirror: recover failed after", MAX_ATTEMPTS, "attempts");
1238
- } else {
1239
- logger?.warn?.("dsh-mneme mirror: recovered from dirty/pending state");
1240
- }
1241
- } catch (error) {
1242
- // fail-safe:任何意外异常不向外抛
1243
- lastError = error?.message ?? String(error);
1244
- logger?.warn?.("dsh-mneme mirror: recover failed with unexpected error:", error);
1245
- }
1246
-
1247
- return { recovered, error: recovered ? null : lastError };
1248
- }
1249
-
1250
- // getMirrorHealth: 暴露 mirror 同步健康状态,供 api.js /health 使用
1251
- // (F-NEW-03)。把 DB 的 dirty 0/1 转成 boolean;fail-safe,绝不向外抛。
1252
- function getMirrorHealth() {
1253
- try {
1254
- const state = store.getMirrorState();
1255
- if (!state) {
1256
- // 无状态行:返回安全默认值
1257
- return {
1258
- dirty: false,
1259
- last_error: null,
1260
- last_attempt: null,
1261
- success_at: null
1262
- };
1263
- }
1264
- return {
1265
- dirty: Boolean(state.dirty),
1266
- last_error: state.last_error ?? null,
1267
- last_attempt: state.last_attempt ?? null,
1268
- success_at: state.success_at ?? null
1269
- };
1270
- } catch (error) {
1271
- // fail-safe:状态读取失败也不向外抛,但必须显式表达"未知"而非伪装成
1272
- // 干净(peer blocker 5:真实读取失败要显式 unknown,不得归一为 dirty:false)。
1273
- logger?.warn?.("getMirrorHealth failed:", error);
1274
- return {
1275
- dirty: null,
1276
- last_error: error?.message ?? String(error),
1277
- last_attempt: null,
1278
- success_at: null
1279
- };
1280
- }
1281
- }
1282
-
1283
- return {
1284
- saveWithDedupe,
1285
- recoverMirror,
1286
- getMirrorHealth,
1287
- getMirrorState: () => store.getMirrorState(),
1288
- injectCandidates,
1289
- mergeHumanEdits,
1290
- toApiList,
1291
- transaction,
1292
- enqueue,
1293
- setDreamHook(fn) { dreamHook = fn; },
1294
- setSleepHook(fn) { sleepHook = fn; },
1295
- setEmbedder(emb) {
1296
- embedder = emb;
1297
- if (!emb) {
1298
- // embedder removed (init failed in index.js): stop polling and drop
1299
- // queued re-embeds — search just degrades to keyword.
1300
- stopEmbedReadyPolling();
1301
- embedPending = [];
1302
- return;
1303
- }
1304
- if (emb.ready === true) {
1305
- flushEmbedPending();
1306
- return;
1307
- }
1308
- // Async-initializing embedder: poll `ready` until it flips, then flush.
1309
- if ("ready" in emb && embedReadyTimer === null) {
1310
- let attempts = 0;
1311
- embedReadyTimer = setInterval(() => {
1312
- attempts++;
1313
- if (emb.ready === true || attempts >= EMBED_READY_POLL_LIMIT) {
1314
- stopEmbedReadyPolling();
1315
- if (emb.ready === true) flushEmbedPending();
1316
- else embedPending = []; // init never landed: drop the queue
1317
- }
1318
- }, EMBED_READY_POLL_MS);
1319
- }
1320
- },
1321
- setEntityExtractor(fn) { entityExtractor = fn; },
1322
- setVectorIndex(vi) { vectorIndex = vi; },
1323
- setReranker(rn) { reranker = rn; },
1324
- setRecallRecorder(fn) { recallRecorder = fn; },
1325
- searchMemories,
1326
- embedQuery,
1327
- evaluateRetrieval,
1328
- computeRetrievalMetrics,
1329
- // passthroughs used by tools and api layers; mutations keep the mirror in sync
1330
- search: (q, o) => store.search(q, o),
1331
- searchVector: (v, o) => store.searchVector(v, o),
1332
- embeddedCount: () => store.embeddedCount(),
1333
- list: (o) => store.list(o),
1334
- all: () => store.all(),
1335
- count: (type, opts) => store.count(type, opts),
1336
- getById: (id) => store.getById(id),
1337
- remove: (id) => {
1338
- store.remove(id);
1339
- afterSync("write");
1340
- notifyWrite();
1341
- },
1342
- update: (id, p, ctx = {}) => {
1343
- const old = store.getById(id);
1344
- const updated = store.update(id, p);
1345
- // Record a user correction when any meaningful field changed and the
1346
- // reflection failure tracker is enabled. expected = what it became,
1347
- // actual = what it was before; query (when provided) captures the
1348
- // user's original intent so later reflection can reason about recall.
1349
- const hasMeaningfulChange = old && updated && (
1350
- old.content !== updated.content ||
1351
- old.title !== updated.title ||
1352
- old.importance !== updated.importance
1353
- );
1354
- if (hasMeaningfulChange && config.reflectionFailureTracking) {
1355
- store.saveFailure({
1356
- id: randomUUID(),
1357
- query: ctx.query ?? null,
1358
- expected: updated.content,
1359
- actual: old.content,
1360
- before: { title: old.title, content: old.content, importance: old.importance },
1361
- failure_type: "user_correction",
1362
- memory_id: id
1363
- });
1364
- }
1365
- const sync = afterSync("write");
1366
- notifyWrite();
1367
- scheduleEmbed(updated);
1368
- // Audit peer B: when the mirror sync failed, the store write landed but
1369
- // the mirror did not converge — return an explicit degraded receipt rather
1370
- // than a plain success. Non-enumerable so existing deepEqual assertions on
1371
- // the memory shape keep passing.
1372
- if (!sync?.success && !sync?.deferred) {
1373
- Object.defineProperty(updated, "_mirror", {
1374
- value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1375
- enumerable: false,
1376
- configurable: true
1377
- });
1378
- }
1379
- return updated;
1380
- },
1381
- // Compare-and-set update: applies the patch only when the row still carries
1382
- // `expectedUpdatedAt`. Returns undefined on a miss (no write) so the caller
1383
- // can re-read and retry — the primitive that prevents lost updates across
1384
- // concurrent read-modify-write (see scripts/stress-dsh.js axis 3).
1385
- compareAndUpdate: (id, expectedUpdatedAt, patch, ctx = {}) => {
1386
- const old = store.getById(id);
1387
- const updated = store.compareAndUpdate(id, expectedUpdatedAt, patch);
1388
- if (updated === undefined) return undefined; // CAS miss: no write, no side effects
1389
- const hasMeaningfulChange = old && updated && (
1390
- old.content !== updated.content ||
1391
- old.title !== updated.title ||
1392
- old.importance !== updated.importance
1393
- );
1394
- if (hasMeaningfulChange && config.reflectionFailureTracking) {
1395
- store.saveFailure({
1396
- id: randomUUID(),
1397
- query: ctx.query ?? null,
1398
- expected: updated.content,
1399
- actual: old.content,
1400
- before: { title: old.title, content: old.content, importance: old.importance },
1401
- failure_type: "user_correction",
1402
- memory_id: id
1403
- });
1404
- }
1405
- const sync = afterSync("write");
1406
- notifyWrite();
1407
- scheduleEmbed(updated);
1408
- // Audit peer B: mirror sync failure on a CAS write must surface too.
1409
- if (!sync?.success && !sync?.deferred) {
1410
- Object.defineProperty(updated, "_mirror", {
1411
- value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1412
- enumerable: false,
1413
- configurable: true
1414
- });
1415
- }
1416
- return updated;
1417
- },
1418
- setForget: (id, f) => {
1419
- const updated = store.setForget(id, f);
1420
- afterSync("write");
1421
- return updated;
1422
- },
1423
- setArchived: (id, f) => {
1424
- const updated = store.setArchived(id, f);
1425
- afterSync("write");
1426
- return updated;
1427
- },
1428
- // sleep-mode storage (v0.4.0). demoteToSummary / restoreContent mutate
1429
- // content so they ride the normal write-hook path (mirror re-renders).
1430
- // touchLastAccess is a read-stamp — deliberately NO write hook (a recall
1431
- // must not dirty the mirror). getUnrecalledSince is a pure read.
1432
- demoteToSummary: (id, summary, opts) => {
1433
- const updated = store.demoteToSummary(id, summary, opts);
1434
- afterSync("write");
1435
- return updated;
1436
- },
1437
- restoreContent: (id) => {
1438
- const updated = store.restoreContent(id);
1439
- afterSync("write");
1440
- return updated;
1441
- },
1442
- touchLastAccess: (id, at) => store.touchLastAccess(id, at),
1443
- getUnrecalledSince: (cutMs, opts) => store.getUnrecalledSince(cutMs, opts),
1444
- // autoDream audit trail: passthroughs deliberately bypass write hooks —
1445
- // an audit write is bookkeeping, and notifyWrite would loop back into the
1446
- // dream scheduler that just recorded the run.
1447
- saveDreamRun: (run) => store.saveDreamRun(run),
1448
- getDreamRun: (id) => store.getDreamRun(id),
1449
- listDreamRuns: (opts) => store.listDreamRuns(opts),
1450
- // Per-record receipt chain (same bookkeeping semantics as saveDreamRun: an
1451
- // audit write, never a write-hook-triggering memory mutation).
1452
- saveReceipt: (r) => store.saveReceipt(r),
1453
- getReceipt: (id) => store.getReceipt(id),
1454
- listReceipts: (opts) => store.listReceipts(opts),
1455
- // Conflict freeze bookkeeping (same semantics as the audit passthroughs
1456
- // above: an audit write, never a write-hook-triggering memory mutation).
1457
- saveConflictPending: (r) => store.saveConflictPending(r),
1458
- listConflictPending: (opts) => store.listConflictPending(opts),
1459
- resolveConflictPending: (id, o) => store.resolveConflictPending(id, o),
1460
- countConflictPending: () => store.countConflictPending(),
1461
- // Recall evaluation trail (方案 B): audit-bookkeeping semantics like the
1462
- // dream/recall passthroughs above — a recall_evals write is a snapshot, not
1463
- // a memory mutation, so it never triggers write hooks.
1464
- saveRecallEval: (r) => store.saveRecallEval(r),
1465
- getRecallEval: (id) => store.getRecallEval(id),
1466
- listRecallEvals: (opts) => store.listRecallEvals(opts),
1467
- // LLM audit trail (Bug8): bookkeeping semantics like the recall/dream
1468
- // passthroughs — a saveLlmAudit write never triggers write hooks.
1469
- saveLlmAudit: (entry) => store.saveLlmAudit(entry),
1470
- listLlmAudits: (opts) => store.listLlmAudits(opts),
1471
- countLlmAudits: (opts) => store.countLlmAudits(opts),
1472
- getLlmAuditStats: (opts) => store.getLlmAuditStats(opts),
1473
- deleteOldLlmAudits: (before) => store.deleteOldLlmAudits(before),
1474
- // Entity gene (v0.3.0) passthroughs for the autoDream apply path
1475
- // (applyDecisions): records supersedes relations after an update and
1476
- // migrates entity_attrs on merge. Bookkeeping writes like the audit
1477
- // passthroughs above — never write-hook-triggering memory mutations.
1478
- saveRelation: (r) => store.saveRelation(r),
1479
- listEntities: (o) => store.listEntities(o),
1480
- getRelations: (id) => store.getRelations(id),
1481
- saveAttr: (r) => store.saveAttr(r),
1482
- createEntity: (r) => store.createEntity(r),
1483
- findEntityByName: (n) => store.findEntityByName(n),
1484
- findEntityById: (id) => store.findEntityById(id),
1485
- getAttrsByMemory: (id) => store.getAttrsByMemory(id),
1486
- getCurrentAttrs: (id) => store.getCurrentAttrs(id),
1487
- migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
1488
- };
1489
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { TYPE_FILE } from "./mirror.js";
3
+ import { evaluateMemoryQuality } from "./quality-filter.js";
4
+ import { createBM25Index } from "./search/bm25.js";
5
+ import { adaptiveThreshold } from "./search/adaptive.js";
6
+
7
+ const INJECT_TYPES = new Set(["preference", "project", "decision", "summary"]);
8
+
9
+ // Epistemic trust weights (v0.4.5): when config.trustEpistemicWeighting is on,
10
+ // each recall candidate's existing score is multiplied by the weight of its
11
+ // epistemic_status before ranking — measured facts outrank guesses. Missing /
12
+ // unknown statuses are unscaled (×1). Off by default, so nothing changes.
13
+ const EPISTEMIC_WEIGHTS = { observation: 1.0, inferred: 0.85, subjective: 0.7 };
14
+
15
+ // Bug5: content version history cap (FIFO — the newest 20 versions are kept,
16
+ // older ones dropped). Entries are {content, source, updated_at}; source marks
17
+ // how the version was superseded (auto_merge | human_override | overwrite).
18
+ const CONTENT_HISTORY_MAX = 20;
19
+
20
+ /** Prepend the previous content to a memory's content_history (FIFO capped). */
21
+ function pushContentHistory(existing, source) {
22
+ const history = Array.isArray(existing?.content_history) ? existing.content_history : [];
23
+ return [
24
+ { content: existing?.content ?? "", source, updated_at: new Date().toISOString() },
25
+ ...history
26
+ ].slice(0, CONTENT_HISTORY_MAX);
27
+ }
28
+
29
+ /** Bug5: same-title merge appends the new content under a timestamped `---`
30
+ * separator instead of overwriting, so a re-noted memory never loses history.
31
+ * The `---` line is compatible with the mirror's readHumanEdits (which strips
32
+ * only the LAST structural `---` when parsing the human-editable file). */
33
+ function appendContent(oldContent, newContent) {
34
+ const ts = new Date().toISOString();
35
+ return `${oldContent}\n\n---\n[${ts}] ${newContent}`;
36
+ }
37
+
38
+ /**
39
+ * Standard retrieval-quality metrics over the ordered candidate ids actually
40
+ * returned vs the ids the evaluator marked relevant (方案 B). Pure + total, so
41
+ * callers (and tests) get deterministic numbers without touching a store:
42
+ * precision = |relevant ∩ retrieved| / |retrieved|
43
+ * recall = |relevant ∩ retrieved| / |expected|
44
+ * mrr = 1 / rank of the first relevant doc (0 when none retrieved)
45
+ * hit_count is the raw intersection size. Values are rounded to 4 decimals so
46
+ * repeated divisions (e.g. 1/3) never surface binary-float noise.
47
+ */
48
+ export function computeRetrievalMetrics(actualIds, expectedIds) {
49
+ const expected = new Set(Array.isArray(expectedIds) ? expectedIds : []);
50
+ const actual = Array.isArray(actualIds) ? actualIds : [];
51
+ const relevant = actual.filter((id) => expected.has(id)).length;
52
+ const round4 = (x) => Math.round(x * 10000) / 10000;
53
+ let mrr = 0;
54
+ for (let i = 0; i < actual.length; i++) {
55
+ if (expected.has(actual[i])) { mrr = 1 / (i + 1); break; }
56
+ }
57
+ return {
58
+ precision: round4(actual.length ? relevant / actual.length : 0),
59
+ recall: round4(expected.size ? relevant / expected.size : 0),
60
+ mrr: round4(mrr),
61
+ hit_count: relevant
62
+ };
63
+ }
64
+
65
+ export function createService({ store, mirror, config, onWrite, logger }) {
66
+ // Optional dream scheduler hook, installed via setDreamHook after creation
67
+ // (the scheduler holds a reference back to the service, so it cannot be
68
+ // passed in the constructor). Fired on the same write events as onWrite.
69
+ let dreamHook = null;
70
+
71
+ // Optional sleep scheduler hook (v0.4.0), installed via setSleepHook after
72
+ // creation. Fired on the same write events as onWrite: it tells the sleep
73
+ // scheduler the store just changed so the idle-detection clock resets.
74
+ let sleepHook = null;
75
+
76
+ // Optional vector embedder, installed via setEmbedder after creation. After
77
+ // any content write it fire-and-forgets a re-embed of the row so vector
78
+ // search stays in sync; failures are swallowed inside the embedder.
79
+ let embedder = null;
80
+
81
+ // Optional entity extractor, installed via setEntityExtractor after creation
82
+ // (index.js injects it so the service never depends on the LLM directly).
83
+ // After a new memory is saved it fire-and-forgets an extraction pass for the
84
+ // entity gene (v0.3.0); failures are swallowed so a broken extraction never
85
+ // surfaces as a write failure. Extraction only runs when
86
+ // config.entityExtractionEnabled is true.
87
+ let entityExtractor = null;
88
+ let vectorIndex = null;
89
+ let reranker = null;
90
+
91
+ // Optional recall recorder, installed via setRecallRecorder after creation.
92
+ // When searchMemories is called with recordRecall=true it receives the
93
+ // actual merged recall scene (candidates + scores + source + threshold) so
94
+ // the retrieval layer can be audited/replayed — the sibling of the dream
95
+ // judgment-layer audit trail (dream_runs).
96
+ let recallRecorder = null;
97
+
98
+ // Bug4: semantic recall cache for the injection path. The system-prompt
99
+ // interpolator renders context synchronously, so injectCandidates cannot
100
+ // fire a fresh async embed. The most recent searchMemories recall is cached
101
+ // here (query + ordered candidates) and reused when the injection query
102
+ // matches, giving semantic-first injection without breaking the sync render.
103
+ let lastSemanticRecall = null;
104
+
105
+ // Transaction nesting depth. Inside service.transaction the per-mutation side
106
+ // effects (mirror render, write notify, re-embed) are deferred so a ROLLBACK
107
+ // never leaves the mirror file diverged from the database; transaction()
108
+ // replays them exactly once against the committed state.
109
+ let txDepth = 0;
110
+
111
+ // Serial task queue (sleep v0.4.0). Long-running background passes — dream
112
+ // consolidation, sleep cycles — must never overlap: two sleep runs racing
113
+ // would double-demote or double-mint patterns. enqueue chains the task onto
114
+ // a promise tail so N callers can queue work that runs strictly one at a
115
+ // time. A task that rejects doesn't poison the queue (the tail swallows the
116
+ // rejection) but the rejection still propagates to that caller.
117
+ let queueTail = Promise.resolve();
118
+ function enqueue(fn) {
119
+ const next = queueTail.then(fn, fn);
120
+ queueTail = next.catch(() => {});
121
+ return next;
122
+ }
123
+
124
+ // issue #6 (part 2): startup race defense. A local embedder (LocalEmbedder /
125
+ // Ollama) exposes an async init(), so between `setEmbedder` and init()
126
+ // resolving there is a window where embedSingle would throw "not initialized"
127
+ // and the re-embed would be silently dropped. When the embedder carries a
128
+ // `ready` flag we queue writes in embedPending until init sets ready=true,
129
+ // then flush them through the embedder's real interface. Embedders without a
130
+ // `ready` flag (legacy OpenAI, instantly usable) keep their old behavior.
131
+ let embedPending = [];
132
+ let embedReadyTimer = null;
133
+ const EMBED_PENDING_MAX = 100; // bound the queue; drop oldest beyond this
134
+ const EMBED_READY_POLL_MS = 100;
135
+ const EMBED_READY_POLL_LIMIT = 30; // ~3s ceiling; never poll forever
136
+
137
+ /** Flush the queued re-embeds once the embedder is ready. Fail-safe. */
138
+ function flushEmbedPending() {
139
+ if (!embedder || embedPending.length === 0) return;
140
+ const batch = embedPending.splice(0, embedPending.length);
141
+ for (const memory of batch) {
142
+ try {
143
+ if (!memory?.id) continue;
144
+ if (typeof embedder.schedule === "function") {
145
+ embedder.schedule(memory);
146
+ } else if (typeof embedder.embedSingle === "function") {
147
+ const text = [memory.title, memory.content].filter(Boolean).join("\n");
148
+ if (!text) continue;
149
+ embedder
150
+ .embedSingle(text)
151
+ .then((vec) => {
152
+ if (Array.isArray(vec) && vec.length) {
153
+ store.setEmbedding(memory.id, vec);
154
+ }
155
+ })
156
+ .catch((err) => {
157
+ logger?.warn?.("flushEmbedPending embedSingle failed:", err);
158
+ });
159
+ }
160
+ } catch (err) {
161
+ logger?.warn?.("flushEmbedPending failed:", err);
162
+ }
163
+ }
164
+ }
165
+
166
+ function stopEmbedReadyPolling() {
167
+ if (embedReadyTimer) {
168
+ clearInterval(embedReadyTimer);
169
+ embedReadyTimer = null;
170
+ }
171
+ }
172
+
173
+ function scheduleEmbed(memory) {
174
+ try {
175
+ if (txDepth > 0) return; // deferred to the transaction's commit
176
+ if (!embedder || !memory?.id) return;
177
+
178
+ // Readiness gate: embedder exposes `ready` (async init) and is not ready
179
+ // yet — queue instead of firing embedSingle into a half-built extractor.
180
+ const hasReady = "ready" in embedder;
181
+ if (hasReady && embedder.ready !== true) {
182
+ if (embedPending.length >= EMBED_PENDING_MAX) embedPending.shift();
183
+ embedPending.push(memory);
184
+ return;
185
+ }
186
+
187
+ if (typeof embedder.schedule === "function") {
188
+ embedder.schedule(memory);
189
+ return;
190
+ }
191
+
192
+ if (typeof embedder.embedSingle === "function") {
193
+ const text = [memory.title, memory.content].filter(Boolean).join("\n");
194
+ if (!text) return;
195
+
196
+ embedder
197
+ .embedSingle(text)
198
+ .then((vec) => {
199
+ if (Array.isArray(vec) && vec.length) {
200
+ store.setEmbedding(memory.id, vec);
201
+ }
202
+ })
203
+ .catch((err) => {
204
+ logger?.warn?.("scheduleEmbed embedSingle failed:", err);
205
+ });
206
+ }
207
+ } catch (err) {
208
+ logger?.warn?.("scheduleEmbed failed:", err);
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Fire-and-forget entity extraction for a freshly saved memory (entity gene
214
+ * v0.3.0). Opt-in via config.entityExtractionEnabled; the extractor is
215
+ * injected as a hook so the service never needs a direct LLM reference.
216
+ * The hook itself is expected to resolve to { ok:boolean } and never throw;
217
+ * a thrown rejection is swallowed here as a final fail-safe.
218
+ */
219
+ function scheduleEntityExtraction(memory) {
220
+ if (txDepth > 0) return; // deferred to the transaction's commit
221
+ if (!config.entityExtractionEnabled || !entityExtractor) return;
222
+ try {
223
+ entityExtractor(memory).catch((err) => {
224
+ logger?.warn?.("entity extraction failed:", err);
225
+ });
226
+ } catch (err) {
227
+ logger?.warn?.("entity extraction failed:", err);
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Cross-encoder rerank over a candidate list (best effort). Reranker
233
+ * failures degrade to the original candidate order — reranking is an
234
+ * accuracy upgrade, never a correctness gate.
235
+ */
236
+ async function rerankCandidates(query, candidates, topK) {
237
+ if (!reranker || !candidates.length) return candidates.slice(0, topK);
238
+ try {
239
+ const scored = await reranker.rerank(query, candidates.map((c) => ({ id: c.id, title: c.title, content: c.content })));
240
+ if (!Array.isArray(scored)) return candidates.slice(0, topK);
241
+ const byId = new Map(candidates.map((c) => [c.id, c]));
242
+ const out = [];
243
+ for (const s of scored) {
244
+ const c = byId.get(s.id);
245
+ if (c) { out.push({ ...c, score: s.score, source: "rerank" }); if (out.length >= topK) break; }
246
+ }
247
+ return out.length ? out : candidates.slice(0, topK);
248
+ } catch {
249
+ return candidates.slice(0, topK);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Search for memories attached to a named entity (v0.3.0 Phase 3).
255
+ * 合并优先级:entity_attrs.memory_id 精确关联 = 1.0 > 关键词提及 = 0.7;
256
+ * attr 命中不覆盖,keyword 只补充召回,最后按 _score 降序取 topK。
257
+ * @param {string} entityName
258
+ * @param {object} [options]
259
+ * @param {number} [options.topK=20]
260
+ * @returns {any[]}
261
+ */
262
+ function searchByEntity(entityName, { topK = 20 } = {}) {
263
+ const entity = store.findEntityByName(entityName);
264
+ if (!entity) return [];
265
+ const attrs = store.getCurrentAttrs(entity.id);
266
+ const memoryIds = [...new Set(attrs.map((a) => a.memory_id).filter(Boolean))];
267
+ const attrHits = memoryIds.map((id) => store.getById(id)).filter(Boolean);
268
+ const keywordHits = store.search(entityName, { limit: topK });
269
+ const merged = new Map();
270
+ for (const mem of attrHits) merged.set(mem.id, { ...mem, _source: "entity_attr", _score: 1.0 });
271
+ for (const mem of keywordHits) {
272
+ if (!merged.has(mem.id)) merged.set(mem.id, { ...mem, _source: "keyword", _score: 0.7 });
273
+ }
274
+ const hits = Array.from(merged.values()).sort((a, b) => b._score - a._score).slice(0, topK);
275
+ touchRecalled(hits);
276
+ return hits;
277
+ }
278
+
279
+ /**
280
+ * Search for memories by attribute key/value (v0.3.0 Phase 3).
281
+ * value 为空时由 store.findMemoriesByAttr 返回该 key 的全部有效记忆。
282
+ * @param {string} key
283
+ * @param {string | undefined} value
284
+ * @param {object} [options]
285
+ * @param {number} [options.topK=20]
286
+ * @returns {any[]}
287
+ */
288
+ function searchByAttr(key, value, { topK = 20 } = {}) {
289
+ if (!key) return [];
290
+ // value 可能为 undefined(attr:key 无 = 值):归一为空串后交给
291
+ // store.findMemoriesByAttr —— 空 value 契约 = 返回该 attr_key 的全部
292
+ // 当前有效记忆(v0.3.0,store.js 已实现)。
293
+ const rows = store.findMemoriesByAttr(key, value ?? "");
294
+ const hits = rows.slice(0, topK);
295
+ touchRecalled(hits);
296
+ return hits;
297
+ }
298
+
299
+ /**
300
+ * Semantic-aware memory search: keyword recall (store.search) plus optional
301
+ * vector recall + rerank. mode:
302
+ * auto (default) keyword first, vector fills remaining slots (legacy)
303
+ * hybrid vector first, keyword fills remaining slots
304
+ * vector vector only, falls back to keyword when unavailable
305
+ * keyword text only, never touches the embedder
306
+ * useRerank runs the cross-encoder over the merged list when a reranker is
307
+ * installed; results carry an extra `score` when reranked.
308
+ */
309
+ // Weighted blend factor for hybrid search; exposed so callers can tune it.
310
+ const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
311
+
312
+ // Cosine over two plain arrays (shared by the search-time semantic dedup).
313
+ function cosineVec(a, b) {
314
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
315
+ let dot = 0, na = 0, nb = 0;
316
+ for (let i = 0; i < a.length; i++) {
317
+ dot += a[i] * b[i];
318
+ na += a[i] * a[i];
319
+ nb += b[i] * b[i];
320
+ }
321
+ if (na === 0 || nb === 0) return 0;
322
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
323
+ }
324
+
325
+ /**
326
+ * BM25 third recall path (v0.5.0 1.1). Scores the query tokens against the
327
+ * live non-archived rows and returns the top `limit` hits with scores
328
+ * normalized to [0,1]. Failures degrade to [] — BM25 is a recall booster,
329
+ * never a correctness gate.
330
+ */
331
+ function bm25Recall(q, limit) {
332
+ if (config?.bm25SearchEnabled === false) return [];
333
+ try {
334
+ const docs = store.list({ limit: 500, includeForgotten: false }).filter((m) => !m.archived);
335
+ if (!docs.length) return [];
336
+ return createBM25Index(docs).search(q, { limit });
337
+ } catch {
338
+ return [];
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Search-time semantic dedup (v0.5.0 2.3): greedy pass dropping candidates
344
+ * whose embedding similarity to an already-kept row exceeds the threshold.
345
+ * Rows without a stored embedding are always kept (no signal = no drop).
346
+ */
347
+ function semanticDeduplicate(candidates) {
348
+ // Opt-in aggressive mode (default off): collapsing near-duplicates can
349
+ // drop legitimately distinct rows on small embedding models, so it ships
350
+ // behind searchSemanticDedup=true.
351
+ if (config?.searchSemanticDedup !== true || candidates.length < 2) return candidates;
352
+ const threshold = config?.searchSemanticDedupThreshold ?? 0.95;
353
+ try {
354
+ const vecs = store.getEmbeddings(candidates.map((c) => c.id));
355
+ if (vecs.size < 2) return candidates;
356
+ const kept = [];
357
+ for (const c of candidates) {
358
+ const v = vecs.get(c.id);
359
+ if (!v) { kept.push(c); continue; }
360
+ const dup = kept.some((k) => {
361
+ const kv = vecs.get(k.id);
362
+ return kv && cosineVec(v, kv) > threshold;
363
+ });
364
+ if (!dup) kept.push(c);
365
+ }
366
+ return kept;
367
+ } catch {
368
+ return candidates;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Give a keyword-hit row a relevance score in [0,1]: title hits score
374
+ * higher than content hits, then scaled by importance (1-5). This lets
375
+ * keyword results participate in weighted hybrid blends.
376
+ */
377
+ function scoreKeyword(row, q) {
378
+ const ql = q.toLowerCase();
379
+ const title = (row.title ?? "").toLowerCase();
380
+ const content = (row.content ?? "").toLowerCase();
381
+ const titleHit = title.includes(ql);
382
+ const base = titleHit ? 1 : content.includes(ql) ? 0.6 : 0.3;
383
+ return base * (0.5 + (row.importance ?? 3) / 10);
384
+ }
385
+
386
+ /**
387
+ * Sleep touch (v0.4.0): when sleep is enabled, any memory surfaced by recall
388
+ * or auto-injection gets its last_accessed_at bumped, so the "unrecalled N
389
+ * days → demote/archive" tiering counts real access. Best-effort and gated on
390
+ * config.sleepModeEnabled — when sleep is off this is a complete no-op (no
391
+ * writes on the hot recall path). A touch failure must never break search/inject.
392
+ */
393
+ function touchRecalled(memories) {
394
+ if (config?.sleepModeEnabled !== true || !Array.isArray(memories) || memories.length === 0) return;
395
+ for (const m of memories) {
396
+ if (!m?.id) continue;
397
+ try {
398
+ store.touchLastAccess(m.id);
399
+ } catch { /* touch is best effort */ }
400
+ }
401
+ }
402
+
403
+ async function searchMemories(query, options = {}) {
404
+ const { mode = "auto", topK = 20, threshold, useRerank = true, recordRecall = false } = options;
405
+ const q = String(query ?? "").trim();
406
+ if (!q) return [];
407
+
408
+ // entity:/attr: 前缀路由(v0.3.0 Phase 3)。entitySearchEnabled 关闭时走原逻辑。
409
+ if (config?.entitySearchEnabled) {
410
+ if (q.startsWith("entity:")) {
411
+ return searchByEntity(q.slice(7).trim(), options);
412
+ }
413
+ if (q.startsWith("attr:")) {
414
+ const [key, value] = q.slice(5).split("=");
415
+ return searchByAttr(key, value, options);
416
+ }
417
+ }
418
+
419
+ const lim = topK > 0 ? topK : 20;
420
+
421
+ // Keyword results, decorated with a score so they can be weight-blended
422
+ // with vector results and reported uniformly. source tracks where each
423
+ // candidate came from for the recall layer receipt.
424
+ const rawKeyword = store.search(q, { limit: lim });
425
+ const keyword = rawKeyword.map((m) => ({ ...m, score: scoreKeyword(m, q), source: "keyword" }));
426
+ const wantVector = mode === "vector" || mode === "hybrid" || (mode === "auto" && !!embedder);
427
+ let vector = [];
428
+ if (wantVector && embedder) {
429
+ try {
430
+ // Legacy embedders expose embed(query); local ones expose embedSingle.
431
+ const embedSingle = typeof embedder.embedSingle === "function"
432
+ ? embedder.embedSingle.bind(embedder)
433
+ : embedder.embed.bind(embedder);
434
+ const qv = await embedSingle(q);
435
+ if (qv?.length) {
436
+ // Adaptive threshold (v0.5.0 1.2): the fetch runs at the loosest
437
+ // branch floor so the head-gap rule can still re-admit the tail;
438
+ // the final cutoff is computed against the fetched score
439
+ // distribution. Explicit `threshold` wins; disabled → legacy 0.
440
+ const adaptive = config?.adaptiveThresholdEnabled !== false;
441
+ const fetchThreshold = adaptive && threshold === undefined
442
+ ? Math.min(0.5, adaptiveThreshold(q))
443
+ : (threshold ?? 0);
444
+ const search = vectorIndex
445
+ ? vectorIndex.search(qv, { limit: lim * 2, threshold: fetchThreshold })
446
+ : store.searchVector(qv, { limit: lim * 2, threshold: fetchThreshold });
447
+ const finalThreshold = adaptive && threshold === undefined
448
+ ? adaptiveThreshold(q, search)
449
+ : (threshold ?? 0);
450
+ vector = search
451
+ .filter((m) => (m.score ?? 1) >= finalThreshold)
452
+ .map((m) => ({ ...m, vector: true, source: "vector" }));
453
+ }
454
+ } catch { /* vector unavailable: keep keyword results */ }
455
+ }
456
+
457
+ // BM25 third path (v0.5.0 1.1): IDF-weighted token overlap recalls rows
458
+ // whose query terms are scattered — the gap LIKE substring matching
459
+ // cannot close. Scores are already normalized to [0,1].
460
+ const bm25 = bm25Recall(q, lim).map((m) => ({ ...m, source: "bm25" }));
461
+ // Loose blend weight: BM25 confirms and backfills, never dominates the
462
+ // semantic signal. Same-memory overlap boosts, unseen ids backfill.
463
+ const wb = 0.3;
464
+ // Path bookkeeping for the boost rule below: which ids each semantic
465
+ // recall path surfaced.
466
+ const vectorIds = new Set(vector.map((m) => m.id));
467
+ const keywordIds = new Set(keyword.map((m) => m.id));
468
+
469
+ // Hybrid blending weights from config when provided.
470
+ const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
471
+ const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
472
+
473
+ let merged;
474
+ if (mode === "keyword") {
475
+ merged = keyword;
476
+ } else if (mode === "vector" || mode === "hybrid") {
477
+ // semantic-first: vector recalls lead, keyword + BM25 fill remaining
478
+ // slots. Weighted blend when sides scored the same memory; otherwise
479
+ // vector order leads (it is the semantic signal), lexical paths
480
+ // backfill.
481
+ const byId = new Map();
482
+ for (const m of vector) {
483
+ const rec = byId.get(m.id);
484
+ byId.set(m.id, rec ? { ...rec, score: Math.max(rec.score ?? 0, m.score ?? 0) } : m);
485
+ }
486
+ for (const m of keyword) {
487
+ const rec = byId.get(m.id);
488
+ if (rec) {
489
+ // Same memory from both sides: blend the scores.
490
+ byId.set(m.id, { ...rec, score: (rec.score ?? 0) * wv + (m.score ?? 0) * wk });
491
+ } else {
492
+ byId.set(m.id, m);
493
+ }
494
+ }
495
+ for (const m of bm25) {
496
+ const rec = byId.get(m.id);
497
+ if (rec) {
498
+ // Boost rule: a row the LIKE keyword path already hit carries the
499
+ // query as a substring, so BM25 tokens are trivially present —
500
+ // boosting it double-counts lexical evidence. Only vector-recalled
501
+ // rows (lexical hit is genuinely new information) get the boost.
502
+ if (keywordIds.has(m.id)) continue;
503
+ byId.set(m.id, { ...rec, score: (rec.score ?? 0) + wb * (m.score ?? 0) });
504
+ } else {
505
+ byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
506
+ }
507
+ }
508
+ const ranked = [...byId.values()]
509
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
510
+ .map((r) => ({ ...r, score: Math.max(0, Math.min(1, r.score ?? 0)) }));
511
+ merged = ranked.slice(0, lim);
512
+ if (merged.length < lim && !merged.length) {
513
+ // Vector unavailable entirely: fall back to plain keyword.
514
+ merged = keyword.slice(0, lim);
515
+ }
516
+ } else {
517
+ // auto: keyword leads, vector + BM25 fill remaining slots (legacy
518
+ // behavior, extended with the third path)
519
+ merged = keyword.slice(0, lim);
520
+ const seen = new Set(merged.map((m) => m.id));
521
+ for (const m of vector) {
522
+ if (merged.length >= lim) break;
523
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
524
+ }
525
+ for (const m of bm25) {
526
+ if (merged.length >= lim) break;
527
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
528
+ }
529
+ }
530
+
531
+ // Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
532
+ // dropped before the reranker sees them, so topK slots carry distinct
533
+ // information instead of the same memory twice. Keyword mode is exempt —
534
+ // it is the documented text-only path and must not be altered by
535
+ // embedding state.
536
+ merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
537
+ merged = merged.slice(0, lim);
538
+ let result = useRerank && reranker && merged.length
539
+ ? await rerankCandidates(q, merged, lim)
540
+ : merged;
541
+ // Epistemic trust (v0.4.5): opt-in re-weighting of the final candidate
542
+ // scores by source credibility. When off (default) `result` is returned
543
+ // untouched — exactly the legacy behavior.
544
+ if (config.trustEpistemicWeighting === true) {
545
+ result = result
546
+ .map((m) => ({
547
+ ...m,
548
+ score: (m.score ?? 0) * (EPISTEMIC_WEIGHTS[m.epistemic_status] ?? 1)
549
+ }))
550
+ .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
551
+ .slice(0, lim);
552
+ }
553
+
554
+ // Recall layer receipt: with recordRecall on, hand the actual merged
555
+ // candidate list (id/title/content/score/source) to the injected recorder
556
+ // before returning, making the retrieval scene replayable — the sibling of
557
+ // the dream judgment-layer audit trail. Recorder failures must never break
558
+ // the search itself.
559
+ if (recordRecall && recallRecorder) {
560
+ try {
561
+ recallRecorder({
562
+ query: q,
563
+ mode,
564
+ topK: lim,
565
+ threshold: threshold ?? null,
566
+ candidates: result.map((m) => ({
567
+ id: m.id,
568
+ title: m.title,
569
+ content: m.content,
570
+ score: m.score ?? null,
571
+ source: m.source ?? "keyword"
572
+ })),
573
+ createdAt: new Date().toISOString()
574
+ });
575
+ } catch { /* recall receipt is best effort */ }
576
+ }
577
+ // Bug4: cache the latest semantic recall so the sync injection path can
578
+ // reuse it when the injection query matches (no async embed available).
579
+ lastSemanticRecall = { query: q, items: result };
580
+ touchRecalled(result);
581
+ return result;
582
+ }
583
+
584
+ /**
585
+ * Retrieval evaluation (方案 B): run one search for `query`, compare the ids
586
+ * it actually returned against `expectedIds`, and return the computed
587
+ * metrics. When persistence is on (config.evalPersistTestResults, or an
588
+ * explicit `persist` override per call) the snapshot is written to the
589
+ * recall_evals table — a SEPARATE store from the recall_runs production audit,
590
+ * so test/eval data never inflates the production trail.
591
+ *
592
+ * options:
593
+ * mode/topK/threshold/useRerank — passed through to searchMemories
594
+ * evalType — label for the snapshot (default 'manual')
595
+ * recordRecall — also write a recall_runs audit row for the
596
+ * same scene and link it via recall_run_id
597
+ * (default false: eval stays unlinked)
598
+ * recallRunId — explicit link to an existing recall_runs id
599
+ * persist — override the config gate for this call
600
+ *
601
+ * Returns { metrics, actualIds, expectedIds, recallRunId, persisted }.
602
+ * Never throws on persistence failures: a broken eval write must not break
603
+ * the retrieval quality measurement.
604
+ */
605
+ async function evaluateRetrieval(query, expectedIds, options = {}) {
606
+ const q = String(query ?? "").trim();
607
+ const expected = Array.isArray(expectedIds) ? expectedIds : [];
608
+ const {
609
+ mode = "auto",
610
+ topK = 20,
611
+ threshold,
612
+ useRerank = true,
613
+ evalType = "manual",
614
+ recordRecall = false,
615
+ recallRunId = null,
616
+ persist = config.evalPersistTestResults === true
617
+ } = options;
618
+ if (!q) {
619
+ const empty = computeRetrievalMetrics([], expected);
620
+ return { metrics: empty, actualIds: [], expectedIds: expected, recallRunId: null, persisted: false };
621
+ }
622
+
623
+ const rows = await searchMemories(q, { mode, topK, threshold, useRerank, recordRecall: false });
624
+ const actualIds = rows.map((m) => m.id);
625
+ const metrics = computeRetrievalMetrics(actualIds, expected);
626
+
627
+ // Optional recall_runs audit for the same scene; the eval row then links to
628
+ // it. Kept separate from the production recorder (which fires only on
629
+ // recordRecall=true inside searchMemories) — eval never double-records.
630
+ // An explicit recallRunId wins; recordRecall only mints a NEW audit run when
631
+ // the caller did not already link one (never clobber an existing link).
632
+ let runId = recallRunId ?? null;
633
+ if (recordRecall && runId === null) {
634
+ try {
635
+ const run = store.saveRecallRun({
636
+ query: q,
637
+ mode,
638
+ topK,
639
+ threshold: threshold ?? null,
640
+ candidates: rows.map((m) => ({
641
+ id: m.id,
642
+ title: m.title,
643
+ content: m.content,
644
+ score: m.score ?? null,
645
+ source: m.source ?? "keyword"
646
+ })),
647
+ created_at: new Date().toISOString()
648
+ });
649
+ runId = run.id;
650
+ } catch { /* non-fatal: the eval itself still succeeds */ }
651
+ }
652
+
653
+ let persisted = false;
654
+ if (persist) {
655
+ try {
656
+ store.saveRecallEval({
657
+ recall_run_id: runId,
658
+ query: q,
659
+ expected_ids: expected,
660
+ actual_ids: actualIds,
661
+ metrics,
662
+ eval_type: evalType,
663
+ created_at: new Date().toISOString()
664
+ });
665
+ persisted = true;
666
+ } catch { /* non-fatal: measurement survives a failed eval write */ }
667
+ }
668
+ return { metrics, actualIds, expectedIds: expected, recallRunId: runId, persisted };
669
+ }
670
+
671
+ /**
672
+ * Fire-and-forget write notification; errors are swallowed to keep write
673
+ * paths clean. The store mutation has already committed, so a throwing
674
+ * subscriber must not surface as a write failure. Archive/forget flags are
675
+ * state toggles, not content writes, so they never notify.
676
+ */
677
+ function notifyWrite() {
678
+ if (txDepth > 0) return; // deferred to the transaction's commit
679
+ if (onWrite) {
680
+ try { onWrite(); } catch { /* ignore */ }
681
+ }
682
+ if (dreamHook) {
683
+ try { dreamHook(); } catch { /* ignore */ }
684
+ }
685
+ if (sleepHook) {
686
+ try { sleepHook(); } catch { /* ignore */ }
687
+ }
688
+ }
689
+
690
+ /**
691
+ * Run several store mutations atomically (SQLite BEGIN/COMMIT/ROLLBACK) and
692
+ * fire the deferred side effects once against the committed state. A throwing
693
+ * body rolls the whole batch back — no partial writes, no diverged mirror.
694
+ * Errors propagate to the caller. NOTE: the commit path re-renders the mirror
695
+ * and notifies subscribers, but re-embedding is left to the caller (the dream
696
+ * flow re-embeds through maintainIndexAfterDream).
697
+ */
698
+ function transaction(fn) {
699
+ store.db.exec("BEGIN");
700
+ txDepth++;
701
+ try {
702
+ const result = fn();
703
+ store.db.exec("COMMIT");
704
+ return result;
705
+ } catch (error) {
706
+ try { store.db.exec("ROLLBACK"); } catch { /* store may be closed */ }
707
+ throw error;
708
+ } finally {
709
+ txDepth--;
710
+ // Sync failures are surfaced, not swallowed (peer blocker 2): the mirror
711
+ // debt was already recorded by markMirrorDirty inside syncMirror, so a
712
+ // restart recovers — but the operator must see it now, not after restart.
713
+ const syncResult = syncMirror();
714
+ if (!syncResult?.success && !syncResult?.deferred) {
715
+ logger?.warn?.("mirror sync failed after transaction:", syncResult?.error);
716
+ }
717
+ notifyWrite();
718
+ }
719
+ }
720
+
721
+ /**
722
+ * Embed an arbitrary query text and return its vector (null on failure / no
723
+ * embedder). Used by the injector to prefetch the semantic-first recall
724
+ * vector for the current user message — the system-prompt render is
725
+ * synchronous, so the vector must be cached in advance (Bug4).
726
+ */
727
+ async function embedQuery(query) {
728
+ const q = String(query ?? "").trim();
729
+ if (!q || !embedder) return null;
730
+ try {
731
+ const embedSingle = typeof embedder.embedSingle === "function"
732
+ ? embedder.embedSingle.bind(embedder)
733
+ : embedder.embed.bind(embedder);
734
+ const vector = await embedSingle(q);
735
+ return Array.isArray(vector) && vector.length ? vector : null;
736
+ } catch {
737
+ return null;
738
+ }
739
+ }
740
+
741
+ /**
742
+ * Save a memory, merging into an existing one when title matches within the same type.
743
+ *
744
+ * Bug5: a same-title merge no longer overwrites — the new content is appended
745
+ * under a timestamped `---` separator (`旧内容\n\n---\n[时间戳] 新内容`) and the
746
+ * previous content is archived into content_history (source: auto_merge, FIFO
747
+ * capped at 20). importance takes the max of both (capped at 5). Callers that
748
+ * truly replace a row (dream summary regeneration) pass `_overwrite: true` to
749
+ * overwrite directly while still archiving the old version (source: overwrite).
750
+ * mergeHumanEdits entry points pass `_humanEdited: true` — same direct
751
+ * overwrite semantics, source: human_override.
752
+ *
753
+ * Bug7 (memory quality filter): when config.memoryQualityFilter.enabled, the
754
+ * memory is scored after dedupe, before write:
755
+ * score >= degradeThreshold → stored normally (score persisted)
756
+ * archiveThreshold <= score < 60 → persisted + ranked degraded
757
+ * score < archiveThreshold → archived + tagged low_quality (still
758
+ * explicitly searchable via includeArchived)
759
+ * @returns {{action: "created"|"merged", memory: object}}
760
+ */
761
+ function saveWithDedupe(memory) {
762
+ // Bug7: score quality once (after dedupe lookup, before write). Failures
763
+ // inside the evaluator are impossible (pure function), but the write that
764
+ // records the score must never fail the save — wrap defensively.
765
+ const qf = config.memoryQualityFilter;
766
+ let quality = null;
767
+ if (qf?.enabled === true) {
768
+ try {
769
+ const recentContents = store.all().slice(0, 20).map((m) => m.content ?? "");
770
+ quality = evaluateMemoryQuality(memory, {
771
+ minContentLength: qf.minContentLength ?? 10,
772
+ recentContents
773
+ });
774
+ } catch { /* quality scoring is best-effort */ }
775
+ }
776
+ const existing = store
777
+ .list({ type: memory.type, limit: 100 })
778
+ .find((m) => m.title.trim() === String(memory.title).trim());
779
+ if (existing) {
780
+ const newContent = String(memory.content ?? "");
781
+ if (!newContent.trim()) {
782
+ // Nothing to merge: the row stays untouched.
783
+ return { action: "merged", memory: existing };
784
+ }
785
+ const direct = memory._overwrite === true || memory._humanEdited === true;
786
+ const content = direct
787
+ ? newContent
788
+ : appendContent(existing.content, newContent);
789
+ const importance = Math.min(5, Math.max(existing.importance, memory.importance ?? existing.importance));
790
+ const merged = store.update(existing.id, {
791
+ content,
792
+ importance,
793
+ tags: memory.tags ?? existing.tags,
794
+ title: memory.title ?? existing.title,
795
+ content_history: pushContentHistory(existing, direct
796
+ ? (memory._humanEdited === true ? "human_override" : "overwrite")
797
+ : "auto_merge"),
798
+ ...(quality ? { quality_score: quality.score } : {})
799
+ });
800
+ // Bug7: a degraded/archived result is applied on top of the merged row.
801
+ const result = applyQualityDisposition(merged, quality, qf);
802
+ afterSync("write");
803
+ notifyWrite();
804
+ scheduleEmbed(result);
805
+ return { action: "merged", memory: result };
806
+ }
807
+ const created = store.save({
808
+ type: memory.type,
809
+ title: memory.title,
810
+ content: memory.content,
811
+ tags: memory.tags ?? [],
812
+ importance: memory.importance ?? 3,
813
+ source: memory.source ?? "manual",
814
+ // Provenance (v0.5.x): birth session rides through the create path; the
815
+ // merge path above preserves the original row's session_id untouched.
816
+ session_id: memory.session_id ?? undefined,
817
+ ...(quality ? { quality_score: quality.score } : {})
818
+ });
819
+ const result = applyQualityDisposition(created, quality, qf);
820
+ afterSync("write");
821
+ notifyWrite();
822
+ scheduleEmbed(result);
823
+ scheduleEntityExtraction(result);
824
+ return { action: "created", memory: result };
825
+ }
826
+
827
+ /**
828
+ * Bug7: apply the quality verdict to a freshly written row. Below the archive
829
+ * threshold the memory is archived + tagged low_quality (still searchable
830
+ * explicitly via includeArchived); between archive and degrade thresholds the
831
+ * score is already persisted and only the injection ranking is affected
832
+ * (importance × score/100). Best-effort: a disposition write failure must
833
+ * never fail the save. Returns the (possibly refreshed) memory row so callers
834
+ * see the archived/tagged state, not the pre-disposition snapshot.
835
+ */
836
+ function applyQualityDisposition(memory, quality, qf) {
837
+ if (!quality || qf?.enabled !== true) return memory;
838
+ const archiveThreshold = qf.archiveThreshold ?? 30;
839
+ // Signal tags (meta / repetitive / duplicate / short_content / low_quality)
840
+ // are merged onto the stored row in every assessed band so the verdict is
841
+ // observable, not just the numeric score. Below the archive threshold the
842
+ // memory is additionally archived (still explicitly searchable).
843
+ const tags = [...new Set([...(memory.tags ?? []), ...(quality.tags ?? [])])];
844
+ if (tags.length === (memory.tags?.length ?? 0) && quality.score >= archiveThreshold) {
845
+ return memory; // no tag drift and not archived → nothing extra to write
846
+ }
847
+ try {
848
+ store.update(memory.id, { tags, quality_score: quality.score });
849
+ if (quality.score < archiveThreshold) store.setArchived(memory.id, true);
850
+ return store.getById(memory.id);
851
+ } catch {
852
+ return memory;
853
+ }
854
+ }
855
+
856
+ /**
857
+ * Candidate memories for automatic context injection:
858
+ * summaries first, then all preferences, then non-forgotten items with
859
+ * importance >= threshold. History is never auto-injected. Archived entries
860
+ * are excluded (store.list already filters them by default; the extra
861
+ * !m.archived check is kept as double insurance).
862
+ *
863
+ * Bug4 (hybridInject): when a non-empty `query` is available and a matching
864
+ * semantic recall was cached by the last searchMemories, the vector hits
865
+ * lead the selection (up to maxItems*2 candidates) and the rule-based pick
866
+ * fills + dedupes the remaining slots. Empty query / no cached recall /
867
+ * hybridInject off → pure legacy rule-based selection.
868
+ */
869
+ function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector } = {}) {
870
+ const q = String(query ?? "").trim();
871
+ // Bug7: quality-weighted importance in the rule-based tier. Unassessed rows
872
+ // (quality_score null) count as 100 (weight 1), so legacy stores keep their
873
+ // exact summary>preference>importance ordering.
874
+ const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
875
+ const items = store.list({ limit: 200, includeForgotten: false })
876
+ .filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
877
+ (m.type === "summary" || m.type === "preference" || m.importance >= threshold))
878
+ .sort((a, b) => {
879
+ const pa = a.type === "summary" ? 0 : a.type === "preference" ? 1 : 2;
880
+ const pb = b.type === "summary" ? 0 : b.type === "preference" ? 1 : 2;
881
+ return pa - pb || (b.importance * qualityWeight(b)) - (a.importance * qualityWeight(a));
882
+ });
883
+ let candidates = items;
884
+ if (config.hybridInject !== false && q) {
885
+ // Bug4: semantic-first recall. Vector hits (queryVector, cached by the
886
+ // injector's async prefetch) lead when present; otherwise the last
887
+ // searchMemories recall for the exact same query is reused. Rule-based
888
+ // items fill + dedupe the remaining slots. Empty query / no vector /
889
+ // no cached recall → pure legacy rule-based selection.
890
+ const semanticItems = [];
891
+ if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
892
+ try {
893
+ const hits = vectorIndex.search(queryVector, { limit: maxItems * 2, threshold: 0 });
894
+ for (const m of hits) {
895
+ if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
896
+ (m.type === "summary" || m.type === "preference" || m.importance >= threshold)) {
897
+ semanticItems.push(m);
898
+ }
899
+ }
900
+ } catch { /* vector unavailable: fall through to the recall cache */ }
901
+ }
902
+ if (!semanticItems.length && lastSemanticRecall?.query === q && lastSemanticRecall.items?.length) {
903
+ for (const m of lastSemanticRecall.items) {
904
+ if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten) semanticItems.push(m);
905
+ }
906
+ }
907
+ if (semanticItems.length) {
908
+ const seen = new Set();
909
+ const merged = [];
910
+ const push = (m) => {
911
+ if (seen.has(m.id)) return;
912
+ seen.add(m.id);
913
+ merged.push(m);
914
+ };
915
+ for (const m of semanticItems) {
916
+ push(m);
917
+ if (merged.length >= maxItems * 2) break;
918
+ }
919
+ for (const m of items) {
920
+ if (merged.length >= maxItems * 2) break;
921
+ push(m);
922
+ }
923
+ candidates = merged;
924
+ }
925
+ }
926
+ // Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
927
+ // available the whole candidate list is re-ordered by similarity to that
928
+ // vector, so the injected slots go to memories on the current topic
929
+ // rather than to the rule-based order. Rows the index did not return
930
+ // keep their relative order after the scored ones.
931
+ if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
932
+ try {
933
+ const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
934
+ const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
935
+ if (sim.size) {
936
+ candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
937
+ }
938
+ } catch { /* topic re-rank unavailable: keep rule-based order */ }
939
+ }
940
+ const selected = candidates.slice(0, maxItems);
941
+ touchRecalled(selected);
942
+ return selected;
943
+ }
944
+
945
+ /**
946
+ * Merge human edits parsed from a mirror file back into the store.
947
+ * Only content/title are taken; structure fields stay machine-owned.
948
+ */
949
+ function mergeHumanEdits(type, edits) {
950
+ let applied = 0;
951
+ for (const edit of edits) {
952
+ if (!edit.id) continue; // corrupt/malformed edit: skip it, keep merging the rest
953
+ const existing = store.getById(edit.id);
954
+ if (!existing || existing.type !== type) continue;
955
+ const patch = {};
956
+ if (typeof edit.title === "string" && edit.title.trim()) patch.title = edit.title.trim();
957
+ if (typeof edit.content === "string" && edit.content.trim()) patch.content = edit.content.trim();
958
+ if (Object.keys(patch).length) {
959
+ // 启动回灌(F-NEW-01):digest 存在且匹配 = 文件自渲染后无人触碰(旧机器
960
+ // 镜像),机器 wins,DB 的 New 必须保留,静默改回 Old 是 bug。
961
+ const digestMatches = typeof edit.digest === "string"
962
+ && typeof edit.title === "string"
963
+ && typeof edit.content === "string"
964
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
965
+ if (digestMatches) continue;
966
+ // 文件 == store(无实际变化)时不覆盖,也不计入 applied。
967
+ const hasDiff = (patch.title !== undefined && existing.title !== patch.title)
968
+ || (patch.content !== undefined && existing.content !== patch.content);
969
+ if (!hasDiff) continue;
970
+ // 人工编辑回灌后触发 re-embed(issue #3 残留修复):向量必须与
971
+ // 新 title/content 一致。scheduleEmbed 为 fire-and-forget,
972
+ // 内部 try/catch 吞错,失败不影响主流程。
973
+ // Bug5: human edits overwrite directly, but the machine version is
974
+ // archived into content_history (source: human_override) before being
975
+ // replaced, so a manual correction never silently destroys the old value.
976
+ const merged = store.update(edit.id, {
977
+ ...patch,
978
+ content_history: patch.content !== undefined && existing.content !== patch.content
979
+ ? pushContentHistory(existing, "human_override")
980
+ : existing.content_history
981
+ });
982
+ applied++;
983
+ scheduleEmbed(merged);
984
+ }
985
+ }
986
+ if (applied) {
987
+ afterSync("write");
988
+ notifyWrite();
989
+ }
990
+ return applied;
991
+ }
992
+
993
+ function toApiList(rows) {
994
+ return rows.map((m) => ({
995
+ id: m.id,
996
+ type: m.type,
997
+ title: m.title,
998
+ content: m.content,
999
+ tags: m.tags,
1000
+ importance: m.importance,
1001
+ source: m.source,
1002
+ created_at: m.created_at,
1003
+ updated_at: m.updated_at
1004
+ }));
1005
+ }
1006
+
1007
+ /**
1008
+ * Three-way merge of in-flight human mirror edits before a re-render.
1009
+ * Runs on every syncMirror, so a human edit made between two store writes is
1010
+ * never silently overwritten by the next sync (human priority is not limited
1011
+ * to startup). Per edited entry:
1012
+ * - file changed only → human wins; the edit is merged back into the store.
1013
+ * - file AND store changed → real three-way conflict: keep the human edit
1014
+ * and append a marker preserving the store's concurrent version, so no
1015
+ * side is dropped.
1016
+ * - store changed only → store wins (the file is simply re-rendered).
1017
+ * Only title/content are taken (structure fields stay machine-owned, matching
1018
+ * mergeHumanEdits). Returns the memory list to render.
1019
+ */
1020
+ function reconcileHumanEdits(memories) {
1021
+ if (!mirror) return memories;
1022
+ const byType = new Map();
1023
+ for (const m of memories) {
1024
+ if (!byType.has(m.type)) byType.set(m.type, []);
1025
+ byType.get(m.type).push(m);
1026
+ }
1027
+ const result = [];
1028
+ for (const type of Object.keys(TYPE_FILE)) {
1029
+ const list = byType.get(type) ?? [];
1030
+ if (list.length === 0) continue;
1031
+ const editsById = new Map(mirror.readHumanEdits(type).map((e) => [e.id, e]));
1032
+ for (const m of list) {
1033
+ const edit = editsById.get(m.id);
1034
+ if (!edit) { result.push(m); continue; }
1035
+ const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
1036
+ || (typeof edit.content === "string" && edit.content !== m.content);
1037
+ if (!humanChanged) { result.push(m); continue; }
1038
+ // 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
1039
+ // digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
1040
+ // 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
1041
+ // 并发人工编辑导致机器写丢失 + 伪冲突标记。
1042
+ const digestMatches = typeof edit.digest === "string"
1043
+ && typeof edit.title === "string"
1044
+ && typeof edit.content === "string"
1045
+ && createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
1046
+ if (digestMatches) {
1047
+ // 无人触碰,机器 wins,走原样
1048
+ result.push(m);
1049
+ continue;
1050
+ }
1051
+ // 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
1052
+ // (保留现有 storeChanged 逻辑)
1053
+ const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
1054
+ if (storeChanged) {
1055
+ const marker = `\n\n> ⚠️ 并发冲突:人工编辑 vs 记忆库并发更新(${m.updated_at})\n> 记忆库版本:${m.content}`;
1056
+ store.update(m.id, { title: edit.title, content: `${edit.content}${marker}` });
1057
+ } else {
1058
+ store.update(m.id, { title: edit.title, content: edit.content });
1059
+ }
1060
+ const merged = store.getById(m.id);
1061
+ scheduleEmbed(merged);
1062
+ result.push(merged);
1063
+ }
1064
+ }
1065
+ return result;
1066
+ }
1067
+
1068
+ /**
1069
+ * Re-render the human-editable mirror after any store mutation, merging any
1070
+ * in-flight human edits first (never silently overwriting them). Only
1071
+ * non-forgotten memories are mirrored: forgotten entries must not reach the
1072
+ * human-editable file (a human "edit" could otherwise resurrect them).
1073
+ */
1074
+ // syncMirror: 同步 mirror,并在失败/成功时持久记录 dirty 状态;保证自身不抛出。
1075
+ // v0.3.6(audit peer 4 阻断):
1076
+ // - 开始时 incrementGeneration 绑定本次期望轮次 gen;成功用
1077
+ // markMirrorCleanForGeneration(gen, now) CAS/fence 清 dirty——旧 worker
1078
+ // (gen 已过期)不会误清另一 worker 未恢复的故障债务;
1079
+ // - 失败写 markMirrorDirty(递增 desired 绑定新债务),下次 recover 恢复;
1080
+ // - 逐 type 用 setTypeStatus 记录部分成功/失败(type_status JSON);
1081
+ // - 所有 store 状态写入各自 try/catch,失败只 warn,绝不向外抛(F-NEW-03)。
1082
+ function syncMirror() {
1083
+ if (txDepth > 0 || !mirror) return { success: true, deferred: true }; // deferred to the transaction's commit
1084
+ const now = new Date().toISOString();
1085
+ let gen;
1086
+ try {
1087
+ // desired generation 已在业务写事务中原子递增(peer blocker 1);这里
1088
+ // 直接读当前值作为本次同步的目标轮次,不再自行 incrementGeneration。
1089
+ const state = store.getMirrorState();
1090
+ gen = state?.generation ?? 0;
1091
+ } catch (stateError) {
1092
+ logger?.warn?.("syncMirror: getMirrorState failed:", stateError);
1093
+ return { success: false, error: stateError?.message ?? String(stateError) };
1094
+ }
1095
+ // coveredTypes 提到 try 外初始化:即使 store.list 先抛错,catch 分支也有
1096
+ // 合法的空 Set 可迭代,保证 syncMirror 自身绝不抛(fail-safe)。
1097
+ const coveredTypes = new Set();
1098
+ try {
1099
+ // 预先获取本次要覆盖的 type 集合(只调一次 store.list)
1100
+ const list = store.list({ limit: 500, includeForgotten: false });
1101
+ for (const memory of list) {
1102
+ if (memory?.type && TYPE_FILE[memory.type]) {
1103
+ coveredTypes.add(memory.type);
1104
+ }
1105
+ }
1106
+
1107
+ // Per-type physical outcome (audit peer D): mirror.sync writes each type
1108
+ // file independently and reports per-type success/failure. A type whose
1109
+ // file was physically committed must be marked committed even when a
1110
+ // sibling type errors — the old code batch-failed every type on any error,
1111
+ // leaving committed files mislabeled as failed and masking partial state.
1112
+ // Absent entries (a type with no memories) count as success: sync prunes
1113
+ // the stale file, which is itself a completed physical state.
1114
+ let allOk = true;
1115
+ const results = mirror.sync(reconcileHumanEdits(list)) ?? {};
1116
+ for (const type of Object.keys(TYPE_FILE)) {
1117
+ const r = results[type];
1118
+ const ok = !r || r.ok === true;
1119
+ if (!ok) allOk = false;
1120
+ try {
1121
+ if (ok) {
1122
+ store.setTypeStatus(type, { status: "committed", applied_gen: gen, last_error: null });
1123
+ } else {
1124
+ store.setTypeStatus(type, { status: "failed", last_error: r.error ?? "mirror sync failed" });
1125
+ }
1126
+ } catch (stateError) {
1127
+ logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1128
+ }
1129
+ }
1130
+
1131
+ // 全部 type 物理收敛:CAS/fence 绑定到本地 gen,旧 worker(gen 已过期)会被
1132
+ // 拦截。此步失败说明核心 clean 状态没写成功,向上层报失败(不再静默)。
1133
+ if (allOk) {
1134
+ try {
1135
+ store.markMirrorCleanForGeneration(gen, now);
1136
+ } catch (stateError) {
1137
+ logger?.warn?.("syncMirror: markMirrorCleanForGeneration failed:", stateError);
1138
+ return { success: false, error: stateError?.message ?? String(stateError) };
1139
+ }
1140
+ return { success: true };
1141
+ }
1142
+
1143
+ // 部分 type 失败:持久 dirty(债务绑定到新轮次),下次 recover 只补未收敛
1144
+ // 的 type。committed 的 type 已应用本轮 gen,不因兄弟失败被回滚。
1145
+ const failedTypes = Object.entries(results)
1146
+ .filter(([, r]) => r && r.ok === false)
1147
+ .map(([t]) => t);
1148
+ try {
1149
+ store.markMirrorDirty(`mirror sync failed for: ${failedTypes.join(", ")}`, now);
1150
+ } catch (stateError) {
1151
+ logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1152
+ }
1153
+ return { success: false, error: `mirror sync failed for: ${failedTypes.join(", ")}` };
1154
+ } catch (error) {
1155
+ const errMsg = error?.message ?? String(error);
1156
+ logger?.warn?.("syncMirror failed:", error);
1157
+ try {
1158
+ // 债务绑定到新的一轮(desired generation 原子递增;即便 dirty 写失败,
1159
+ // generation 已推进,recoverMirror 仍能捕获,不产生 false-clean)。
1160
+ store.markMirrorDirty(errMsg, now);
1161
+ } catch (stateError) {
1162
+ logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
1163
+ }
1164
+ // 逐 type 标记为 failed(applied_gen 不动)
1165
+ for (const type of coveredTypes) {
1166
+ try {
1167
+ store.setTypeStatus(type, { status: "failed", last_error: errMsg });
1168
+ } catch (stateError) {
1169
+ logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
1170
+ }
1171
+ }
1172
+ return { success: false, error: errMsg };
1173
+ }
1174
+ }
1175
+
1176
+ // afterSync: run syncMirror and surface a failure to the operator instead of
1177
+ // swallowing it (peer blocker 2 + audit peer B). The mirror debt has already
1178
+ // been persisted by markMirrorDirty inside syncMirror, so a restart recovers —
1179
+ // but the calling write path must not report clean while the mirror is
1180
+ // known-stale. Returns the sync result so the caller can attach an explicit
1181
+ // degraded/pending receipt to its return value instead of faking success.
1182
+ function afterSync(label) {
1183
+ const r = syncMirror();
1184
+ if (!r?.success && !r?.deferred) {
1185
+ logger?.warn?.(`${label}: mirror sync failed (will recover on restart):`, r?.error);
1186
+ }
1187
+ return r;
1188
+ }
1189
+
1190
+ // recoverMirror: 启动/手动 reconcile 时根据持久 dirty 状态决定是否恢复同步
1191
+ // (F-NEW-03 + v0.3.6)。触发条件不只是 dirty——还检查
1192
+ // generation > applied_generation(有未应用的债务),这样 COMMIT→dirty 崩溃
1193
+ // 窗口(DB 提交后、markMirrorDirty/clean 前进程退出 → dirty=false 但
1194
+ // generation 不一致)也能被捕获。有界重试(最多 3 次)重跑 syncMirror 收敛;
1195
+ // 某次成功后 dirty=false 且无更新债务(generation <= applied_generation)
1196
+ // 立即停止。返回 { recovered, error } 供 index.js 启动 / api.js health 判断。
1197
+ // 一切 fail-safe,绝不向外抛。
1198
+ function recoverMirror() {
1199
+ const MAX_ATTEMPTS = 3;
1200
+ let lastError = null;
1201
+ let recovered = false;
1202
+
1203
+ try {
1204
+ const state = store.getMirrorState();
1205
+ // 崩溃窗口检测:dirty 或 generation > applied_generation(COMMIT→dirty 窗口)
1206
+ if (!state?.dirty && !(state.generation > state.applied_generation)) {
1207
+ // 本来就干净:无需恢复,视为成功
1208
+ return { recovered: true, error: null };
1209
+ }
1210
+
1211
+ // 有 dirty 或有未应用债务:最多尝试 3 次 sync
1212
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
1213
+ try {
1214
+ syncMirror(); // syncMirror 内部已 catch,不会向外抛
1215
+ const currentState = store.getMirrorState();
1216
+ // 成功条件:dirty 为 false 且没有更新一轮的债务
1217
+ // (generation <= applied_generation,恢复后由 syncMirror 里
1218
+ // markMirrorCleanForGeneration 自动把 applied 跟上)
1219
+ if (!currentState?.dirty && currentState.generation <= currentState.applied_generation) {
1220
+ recovered = true;
1221
+ lastError = null;
1222
+ break;
1223
+ }
1224
+ // 仍 dirty 或仍有更新债务:记录最后一次错误供重试耗尽后上报。
1225
+ // 注意:若别的 worker 又失败产生新债务(dirty 仍 true),这是"新债务"
1226
+ // 不是本次失败,继续重试直到耗尽次数。
1227
+ lastError = currentState.last_error || `Sync attempt ${attempt + 1} left mirror dirty or has pending debt`;
1228
+ } catch (syncError) {
1229
+ // syncMirror 理论不抛,fail-safe 兜底
1230
+ const errMsg = syncError?.message ?? String(syncError);
1231
+ logger?.warn?.("recoverMirror: sync attempt failed:", errMsg);
1232
+ lastError = errMsg;
1233
+ }
1234
+ }
1235
+
1236
+ if (!recovered) {
1237
+ logger?.warn?.("dsh-mneme mirror: recover failed after", MAX_ATTEMPTS, "attempts");
1238
+ } else {
1239
+ logger?.warn?.("dsh-mneme mirror: recovered from dirty/pending state");
1240
+ }
1241
+ } catch (error) {
1242
+ // fail-safe:任何意外异常不向外抛
1243
+ lastError = error?.message ?? String(error);
1244
+ logger?.warn?.("dsh-mneme mirror: recover failed with unexpected error:", error);
1245
+ }
1246
+
1247
+ return { recovered, error: recovered ? null : lastError };
1248
+ }
1249
+
1250
+ // getMirrorHealth: 暴露 mirror 同步健康状态,供 api.js /health 使用
1251
+ // (F-NEW-03)。把 DB 的 dirty 0/1 转成 boolean;fail-safe,绝不向外抛。
1252
+ function getMirrorHealth() {
1253
+ try {
1254
+ const state = store.getMirrorState();
1255
+ if (!state) {
1256
+ // 无状态行:返回安全默认值
1257
+ return {
1258
+ dirty: false,
1259
+ last_error: null,
1260
+ last_attempt: null,
1261
+ success_at: null
1262
+ };
1263
+ }
1264
+ return {
1265
+ dirty: Boolean(state.dirty),
1266
+ last_error: state.last_error ?? null,
1267
+ last_attempt: state.last_attempt ?? null,
1268
+ success_at: state.success_at ?? null
1269
+ };
1270
+ } catch (error) {
1271
+ // fail-safe:状态读取失败也不向外抛,但必须显式表达"未知"而非伪装成
1272
+ // 干净(peer blocker 5:真实读取失败要显式 unknown,不得归一为 dirty:false)。
1273
+ logger?.warn?.("getMirrorHealth failed:", error);
1274
+ return {
1275
+ dirty: null,
1276
+ last_error: error?.message ?? String(error),
1277
+ last_attempt: null,
1278
+ success_at: null
1279
+ };
1280
+ }
1281
+ }
1282
+
1283
+ return {
1284
+ saveWithDedupe,
1285
+ recoverMirror,
1286
+ getMirrorHealth,
1287
+ getMirrorState: () => store.getMirrorState(),
1288
+ injectCandidates,
1289
+ mergeHumanEdits,
1290
+ toApiList,
1291
+ transaction,
1292
+ enqueue,
1293
+ setDreamHook(fn) { dreamHook = fn; },
1294
+ setSleepHook(fn) { sleepHook = fn; },
1295
+ setEmbedder(emb) {
1296
+ embedder = emb;
1297
+ if (!emb) {
1298
+ // embedder removed (init failed in index.js): stop polling and drop
1299
+ // queued re-embeds — search just degrades to keyword.
1300
+ stopEmbedReadyPolling();
1301
+ embedPending = [];
1302
+ return;
1303
+ }
1304
+ if (emb.ready === true) {
1305
+ flushEmbedPending();
1306
+ return;
1307
+ }
1308
+ // Async-initializing embedder: poll `ready` until it flips, then flush.
1309
+ if ("ready" in emb && embedReadyTimer === null) {
1310
+ let attempts = 0;
1311
+ embedReadyTimer = setInterval(() => {
1312
+ attempts++;
1313
+ if (emb.ready === true || attempts >= EMBED_READY_POLL_LIMIT) {
1314
+ stopEmbedReadyPolling();
1315
+ if (emb.ready === true) flushEmbedPending();
1316
+ else embedPending = []; // init never landed: drop the queue
1317
+ }
1318
+ }, EMBED_READY_POLL_MS);
1319
+ }
1320
+ },
1321
+ setEntityExtractor(fn) { entityExtractor = fn; },
1322
+ setVectorIndex(vi) { vectorIndex = vi; },
1323
+ setReranker(rn) { reranker = rn; },
1324
+ setRecallRecorder(fn) { recallRecorder = fn; },
1325
+ searchMemories,
1326
+ embedQuery,
1327
+ evaluateRetrieval,
1328
+ computeRetrievalMetrics,
1329
+ // passthroughs used by tools and api layers; mutations keep the mirror in sync
1330
+ search: (q, o) => store.search(q, o),
1331
+ searchVector: (v, o) => store.searchVector(v, o),
1332
+ embeddedCount: () => store.embeddedCount(),
1333
+ list: (o) => store.list(o),
1334
+ all: () => store.all(),
1335
+ count: (type, opts) => store.count(type, opts),
1336
+ getById: (id) => store.getById(id),
1337
+ remove: (id) => {
1338
+ store.remove(id);
1339
+ afterSync("write");
1340
+ notifyWrite();
1341
+ },
1342
+ update: (id, p, ctx = {}) => {
1343
+ const old = store.getById(id);
1344
+ const updated = store.update(id, p);
1345
+ // Record a user correction when any meaningful field changed and the
1346
+ // reflection failure tracker is enabled. expected = what it became,
1347
+ // actual = what it was before; query (when provided) captures the
1348
+ // user's original intent so later reflection can reason about recall.
1349
+ const hasMeaningfulChange = old && updated && (
1350
+ old.content !== updated.content ||
1351
+ old.title !== updated.title ||
1352
+ old.importance !== updated.importance
1353
+ );
1354
+ if (hasMeaningfulChange && config.reflectionFailureTracking) {
1355
+ store.saveFailure({
1356
+ id: randomUUID(),
1357
+ query: ctx.query ?? null,
1358
+ expected: updated.content,
1359
+ actual: old.content,
1360
+ before: { title: old.title, content: old.content, importance: old.importance },
1361
+ failure_type: "user_correction",
1362
+ memory_id: id
1363
+ });
1364
+ }
1365
+ const sync = afterSync("write");
1366
+ notifyWrite();
1367
+ scheduleEmbed(updated);
1368
+ // Audit peer B: when the mirror sync failed, the store write landed but
1369
+ // the mirror did not converge — return an explicit degraded receipt rather
1370
+ // than a plain success. Non-enumerable so existing deepEqual assertions on
1371
+ // the memory shape keep passing.
1372
+ if (!sync?.success && !sync?.deferred) {
1373
+ Object.defineProperty(updated, "_mirror", {
1374
+ value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1375
+ enumerable: false,
1376
+ configurable: true
1377
+ });
1378
+ }
1379
+ return updated;
1380
+ },
1381
+ // Compare-and-set update: applies the patch only when the row still carries
1382
+ // `expectedUpdatedAt`. Returns undefined on a miss (no write) so the caller
1383
+ // can re-read and retry — the primitive that prevents lost updates across
1384
+ // concurrent read-modify-write (see scripts/stress-dsh.js axis 3).
1385
+ compareAndUpdate: (id, expectedUpdatedAt, patch, ctx = {}) => {
1386
+ const old = store.getById(id);
1387
+ const updated = store.compareAndUpdate(id, expectedUpdatedAt, patch);
1388
+ if (updated === undefined) return undefined; // CAS miss: no write, no side effects
1389
+ const hasMeaningfulChange = old && updated && (
1390
+ old.content !== updated.content ||
1391
+ old.title !== updated.title ||
1392
+ old.importance !== updated.importance
1393
+ );
1394
+ if (hasMeaningfulChange && config.reflectionFailureTracking) {
1395
+ store.saveFailure({
1396
+ id: randomUUID(),
1397
+ query: ctx.query ?? null,
1398
+ expected: updated.content,
1399
+ actual: old.content,
1400
+ before: { title: old.title, content: old.content, importance: old.importance },
1401
+ failure_type: "user_correction",
1402
+ memory_id: id
1403
+ });
1404
+ }
1405
+ const sync = afterSync("write");
1406
+ notifyWrite();
1407
+ scheduleEmbed(updated);
1408
+ // Audit peer B: mirror sync failure on a CAS write must surface too.
1409
+ if (!sync?.success && !sync?.deferred) {
1410
+ Object.defineProperty(updated, "_mirror", {
1411
+ value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
1412
+ enumerable: false,
1413
+ configurable: true
1414
+ });
1415
+ }
1416
+ return updated;
1417
+ },
1418
+ setForget: (id, f) => {
1419
+ const updated = store.setForget(id, f);
1420
+ afterSync("write");
1421
+ return updated;
1422
+ },
1423
+ setArchived: (id, f) => {
1424
+ const updated = store.setArchived(id, f);
1425
+ afterSync("write");
1426
+ return updated;
1427
+ },
1428
+ // sleep-mode storage (v0.4.0). demoteToSummary / restoreContent mutate
1429
+ // content so they ride the normal write-hook path (mirror re-renders).
1430
+ // touchLastAccess is a read-stamp — deliberately NO write hook (a recall
1431
+ // must not dirty the mirror). getUnrecalledSince is a pure read.
1432
+ demoteToSummary: (id, summary, opts) => {
1433
+ const updated = store.demoteToSummary(id, summary, opts);
1434
+ afterSync("write");
1435
+ return updated;
1436
+ },
1437
+ restoreContent: (id) => {
1438
+ const updated = store.restoreContent(id);
1439
+ afterSync("write");
1440
+ return updated;
1441
+ },
1442
+ touchLastAccess: (id, at) => store.touchLastAccess(id, at),
1443
+ getUnrecalledSince: (cutMs, opts) => store.getUnrecalledSince(cutMs, opts),
1444
+ // autoDream audit trail: passthroughs deliberately bypass write hooks —
1445
+ // an audit write is bookkeeping, and notifyWrite would loop back into the
1446
+ // dream scheduler that just recorded the run.
1447
+ saveDreamRun: (run) => store.saveDreamRun(run),
1448
+ getDreamRun: (id) => store.getDreamRun(id),
1449
+ listDreamRuns: (opts) => store.listDreamRuns(opts),
1450
+ // Per-record receipt chain (same bookkeeping semantics as saveDreamRun: an
1451
+ // audit write, never a write-hook-triggering memory mutation).
1452
+ saveReceipt: (r) => store.saveReceipt(r),
1453
+ getReceipt: (id) => store.getReceipt(id),
1454
+ listReceipts: (opts) => store.listReceipts(opts),
1455
+ // Conflict freeze bookkeeping (same semantics as the audit passthroughs
1456
+ // above: an audit write, never a write-hook-triggering memory mutation).
1457
+ saveConflictPending: (r) => store.saveConflictPending(r),
1458
+ listConflictPending: (opts) => store.listConflictPending(opts),
1459
+ resolveConflictPending: (id, o) => store.resolveConflictPending(id, o),
1460
+ countConflictPending: () => store.countConflictPending(),
1461
+ // Recall evaluation trail (方案 B): audit-bookkeeping semantics like the
1462
+ // dream/recall passthroughs above — a recall_evals write is a snapshot, not
1463
+ // a memory mutation, so it never triggers write hooks.
1464
+ saveRecallEval: (r) => store.saveRecallEval(r),
1465
+ getRecallEval: (id) => store.getRecallEval(id),
1466
+ listRecallEvals: (opts) => store.listRecallEvals(opts),
1467
+ // LLM audit trail (Bug8): bookkeeping semantics like the recall/dream
1468
+ // passthroughs — a saveLlmAudit write never triggers write hooks.
1469
+ saveLlmAudit: (entry) => store.saveLlmAudit(entry),
1470
+ listLlmAudits: (opts) => store.listLlmAudits(opts),
1471
+ countLlmAudits: (opts) => store.countLlmAudits(opts),
1472
+ getLlmAuditStats: (opts) => store.getLlmAuditStats(opts),
1473
+ deleteOldLlmAudits: (before) => store.deleteOldLlmAudits(before),
1474
+ // Entity gene (v0.3.0) passthroughs for the autoDream apply path
1475
+ // (applyDecisions): records supersedes relations after an update and
1476
+ // migrates entity_attrs on merge. Bookkeeping writes like the audit
1477
+ // passthroughs above — never write-hook-triggering memory mutations.
1478
+ saveRelation: (r) => store.saveRelation(r),
1479
+ listEntities: (o) => store.listEntities(o),
1480
+ getRelations: (id) => store.getRelations(id),
1481
+ saveAttr: (r) => store.saveAttr(r),
1482
+ createEntity: (r) => store.createEntity(r),
1483
+ findEntityByName: (n) => store.findEntityByName(n),
1484
+ findEntityById: (id) => store.findEntityById(id),
1485
+ getAttrsByMemory: (id) => store.getAttrsByMemory(id),
1486
+ getCurrentAttrs: (id) => store.getCurrentAttrs(id),
1487
+ migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
1488
+ };
1489
+ }