@modusensus/dsh-mneme 0.4.6 → 0.5.0

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.
@@ -0,0 +1,96 @@
1
+ // BM25 sparse retrieval (v0.5.0 召回率优化 1.1): the third recall path beside
2
+ // vector search and the LIKE keyword scan. The LIKE path only matches full
3
+ // substrings, so a multi-term query ("rust 异步 tokio") misses rows whose
4
+ // terms are scattered. BM25 scores per-token overlap with IDF weighting,
5
+ // which is exactly the gap: identifiers, code fragments and mixed CJK/ASCII
6
+ // queries recall rows the substring scan cannot see.
7
+
8
+ // Tokenizer: ASCII words keep their shape (identifiers like "dsh-mneme" or
9
+ // "ZFS_4421" survive as whole tokens); CJK runs become sliding bigrams
10
+ // (unigram only for single characters), the standard workaround for BM25's
11
+ // whitespace tokenization on Chinese.
12
+ export function tokenize(text) {
13
+ const raw = String(text ?? "").toLowerCase();
14
+ const tokens = [];
15
+ const ascii = raw.match(/[a-z0-9_]+/g) ?? [];
16
+ tokens.push(...ascii);
17
+ const cjkRuns = raw.match(/[\u4e00-\u9fff]+/g) ?? [];
18
+ for (const run of cjkRuns) {
19
+ if (run.length === 1) { tokens.push(run); continue; }
20
+ for (let i = 0; i < run.length - 1; i++) tokens.push(run.slice(i, i + 2));
21
+ }
22
+ return tokens;
23
+ }
24
+
25
+ const K1 = 1.5; // term-frequency saturation
26
+ const B = 0.75; // length normalization
27
+
28
+ /**
29
+ * Build a BM25 index over documents: [{id, title, content}].
30
+ * Returns { score, search }:
31
+ * score(query, doc) — per-spec ad-hoc scoring (re-tokenizes the doc)
32
+ * search(query, {limit}) — precomputed-tf ranking, scores normalized to
33
+ * [0,1] by the max so BM25 hits can weight-blend with vector/keyword
34
+ * scores on one scale. Rows the query does not touch at all are dropped.
35
+ */
36
+ export function createBM25Index(documents) {
37
+ const docs = Array.isArray(documents) ? documents.filter(Boolean) : [];
38
+ const N = docs.length;
39
+ const df = new Map();
40
+ const prepared = docs.map((doc) => {
41
+ const tokens = tokenize(`${doc.title ?? ""} ${doc.content ?? ""}`);
42
+ const tf = new Map();
43
+ for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);
44
+ for (const t of tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);
45
+ return { doc, tf, len: tokens.length };
46
+ });
47
+ const avgLen = N ? prepared.reduce((s, p) => s + p.len, 0) / N : 0 || 1;
48
+
49
+ const idf = (t) => {
50
+ const n = df.get(t) ?? 0;
51
+ return Math.log((N - n + 0.5) / (n + 0.5) + 1);
52
+ };
53
+
54
+ function scorePrepared(queryTokens, p) {
55
+ let score = 0;
56
+ for (const t of queryTokens) {
57
+ const f = p.tf.get(t);
58
+ if (!f) continue;
59
+ const norm = p.len ? K1 * (1 - B + B * (p.len / avgLen)) : K1;
60
+ score += idf(t) * ((f * (K1 + 1)) / (f + norm));
61
+ }
62
+ return score;
63
+ }
64
+
65
+ return {
66
+ score(query, doc) {
67
+ const tokens = tokenize(`${doc?.title ?? ""} ${doc?.content ?? ""}`);
68
+ const tf = new Map();
69
+ for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);
70
+ const len = tokens.length;
71
+ // Ad-hoc scoring can't see corpus df; fall back to tf-only saturation
72
+ // (df is approximated as 1 so idf ≈ log(N - 0.5 + 1) is constant).
73
+ let score = 0;
74
+ for (const t of tokenize(query)) {
75
+ const f = tf.get(t);
76
+ if (!f) continue;
77
+ const norm = len ? K1 * (1 - B + B * (len / avgLen)) : K1;
78
+ score += idf(t) * ((f * (K1 + 1)) / (f + norm));
79
+ }
80
+ return score;
81
+ },
82
+ search(query, { limit = 20 } = {}) {
83
+ const qTokens = tokenize(query);
84
+ if (!qTokens.length || !N) return [];
85
+ const scored = [];
86
+ for (const p of prepared) {
87
+ const s = scorePrepared(qTokens, p);
88
+ if (s > 0) scored.push({ row: p.doc, raw: s });
89
+ }
90
+ scored.sort((a, b) => b.raw - a.raw);
91
+ const top = scored.slice(0, limit);
92
+ const max = top[0]?.raw || 1;
93
+ return top.map(({ row, raw }) => ({ ...row, score: max ? raw / max : 0 }));
94
+ }
95
+ };
96
+ }
package/lib/service.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { TYPE_FILE } from "./mirror.js";
3
3
  import { evaluateMemoryQuality } from "./quality-filter.js";
4
+ import { createBM25Index } from "./search/bm25.js";
5
+ import { adaptiveThreshold } from "./search/adaptive.js";
4
6
 
5
7
  const INJECT_TYPES = new Set(["preference", "project", "decision", "summary"]);
6
8
 
@@ -307,6 +309,66 @@ export function createService({ store, mirror, config, onWrite, logger }) {
307
309
  // Weighted blend factor for hybrid search; exposed so callers can tune it.
308
310
  const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
309
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
+
310
372
  /**
311
373
  * Give a keyword-hit row a relevance score in [0,1]: title hits score
312
374
  * higher than content hits, then scaled by importance (1-5). This lets
@@ -371,14 +433,39 @@ export function createService({ store, mirror, config, onWrite, logger }) {
371
433
  : embedder.embed.bind(embedder);
372
434
  const qv = await embedSingle(q);
373
435
  if (qv?.length) {
374
- const hits = vectorIndex
375
- ? vectorIndex.search(qv, { limit: lim * 2, threshold: threshold ?? 0 })
376
- : store.searchVector(qv, { limit: lim * 2, threshold: threshold ?? 0 });
377
- vector = hits.map((m) => ({ ...m, vector: true, source: "vector" }));
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" }));
378
453
  }
379
454
  } catch { /* vector unavailable: keep keyword results */ }
380
455
  }
381
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
+
382
469
  // Hybrid blending weights from config when provided.
383
470
  const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
384
471
  const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
@@ -387,9 +474,10 @@ export function createService({ store, mirror, config, onWrite, logger }) {
387
474
  if (mode === "keyword") {
388
475
  merged = keyword;
389
476
  } else if (mode === "vector" || mode === "hybrid") {
390
- // semantic-first: vector recalls lead, keyword fills remaining slots.
391
- // Weighted blend when both sides scored the same memory; otherwise
392
- // vector order leads (it is the semantic signal), keyword backfills.
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.
393
481
  const byId = new Map();
394
482
  for (const m of vector) {
395
483
  const rec = byId.get(m.id);
@@ -404,6 +492,19 @@ export function createService({ store, mirror, config, onWrite, logger }) {
404
492
  byId.set(m.id, m);
405
493
  }
406
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
+ }
407
508
  const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
408
509
  merged = ranked.slice(0, lim);
409
510
  if (merged.length < lim && !merged.length) {
@@ -411,15 +512,26 @@ export function createService({ store, mirror, config, onWrite, logger }) {
411
512
  merged = keyword.slice(0, lim);
412
513
  }
413
514
  } else {
414
- // auto: keyword leads, vector fills remaining slots (legacy behavior)
515
+ // auto: keyword leads, vector + BM25 fill remaining slots (legacy
516
+ // behavior, extended with the third path)
415
517
  merged = keyword.slice(0, lim);
416
518
  const seen = new Set(merged.map((m) => m.id));
417
519
  for (const m of vector) {
418
520
  if (merged.length >= lim) break;
419
521
  if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
420
522
  }
523
+ for (const m of bm25) {
524
+ if (merged.length >= lim) break;
525
+ if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
526
+ }
421
527
  }
422
528
 
529
+ // Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
530
+ // dropped before the reranker sees them, so topK slots carry distinct
531
+ // information instead of the same memory twice. Keyword mode is exempt —
532
+ // it is the documented text-only path and must not be altered by
533
+ // embedding state.
534
+ merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
423
535
  merged = merged.slice(0, lim);
424
536
  let result = useRerank && reranker && merged.length
425
537
  ? await rerankCandidates(q, merged, lim)
@@ -806,6 +918,20 @@ export function createService({ store, mirror, config, onWrite, logger }) {
806
918
  candidates = merged;
807
919
  }
808
920
  }
921
+ // Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
922
+ // available the whole candidate list is re-ordered by similarity to that
923
+ // vector, so the injected slots go to memories on the current topic
924
+ // rather than to the rule-based order. Rows the index did not return
925
+ // keep their relative order after the scored ones.
926
+ if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
927
+ try {
928
+ const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
929
+ const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
930
+ if (sim.size) {
931
+ candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
932
+ }
933
+ } catch { /* topic re-rank unavailable: keep rule-based order */ }
934
+ }
809
935
  const selected = candidates.slice(0, maxItems);
810
936
  touchRecalled(selected);
811
937
  return selected;
@@ -1352,6 +1478,7 @@ export function createService({ store, mirror, config, onWrite, logger }) {
1352
1478
  findEntityByName: (n) => store.findEntityByName(n),
1353
1479
  findEntityById: (id) => store.findEntityById(id),
1354
1480
  getAttrsByMemory: (id) => store.getAttrsByMemory(id),
1481
+ getCurrentAttrs: (id) => store.getCurrentAttrs(id),
1355
1482
  migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
1356
1483
  };
1357
1484
  }
package/lib/store.js CHANGED
@@ -548,51 +548,39 @@ export function createStore(path) {
548
548
  db.exec("PRAGMA journal_mode = WAL;");
549
549
  db.exec(SCHEMA);
550
550
 
551
- // Schema migrations for legacy databases (idempotent).
552
- const columns = db.prepare("PRAGMA table_info(memories)").all().map((c) => c.name);
553
- if (!columns.includes("archived")) {
554
- db.exec("ALTER TABLE memories ADD COLUMN archived INTEGER NOT NULL DEFAULT 0");
555
- }
556
- if (!columns.includes("embedding")) {
557
- db.exec("ALTER TABLE memories ADD COLUMN embedding TEXT");
558
- }
559
- if (!columns.includes("last_accessed_at")) {
560
- db.exec("ALTER TABLE memories ADD COLUMN last_accessed_at TEXT");
561
- }
562
- if (!columns.includes("_full_content")) {
563
- db.exec("ALTER TABLE memories ADD COLUMN _full_content TEXT");
564
- }
565
- if (!columns.includes("epistemic_status")) {
566
- db.exec("ALTER TABLE memories ADD COLUMN epistemic_status TEXT NOT NULL DEFAULT 'subjective'");
567
- }
568
- if (!columns.includes("content_history")) {
569
- db.exec("ALTER TABLE memories ADD COLUMN content_history TEXT");
570
- }
571
- if (!columns.includes("quality_score")) {
572
- db.exec("ALTER TABLE memories ADD COLUMN quality_score REAL");
573
- }
551
+ // Schema migrations for legacy databases (idempotent). Each ADD COLUMN is
552
+ // also race-safe: two concurrently-opening processes can both pass the
553
+ // PRAGMA table_info check before either ALTERs, so the ALTER itself is
554
+ // guarded against the "duplicate column name" error SQLite raises when the
555
+ // other process won the race (SQLite has no ADD COLUMN IF NOT EXISTS).
556
+ const addColumn = (table, column, ddl) => {
557
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name);
558
+ if (!cols.includes(column)) {
559
+ try {
560
+ db.exec(ddl);
561
+ } catch (e) {
562
+ if (!/duplicate column name/i.test(String(e?.message ?? e))) throw e;
563
+ }
564
+ }
565
+ };
566
+
567
+ addColumn("memories", "archived", "ALTER TABLE memories ADD COLUMN archived INTEGER NOT NULL DEFAULT 0");
568
+ addColumn("memories", "embedding", "ALTER TABLE memories ADD COLUMN embedding TEXT");
569
+ addColumn("memories", "last_accessed_at", "ALTER TABLE memories ADD COLUMN last_accessed_at TEXT");
570
+ addColumn("memories", "_full_content", "ALTER TABLE memories ADD COLUMN _full_content TEXT");
571
+ addColumn("memories", "epistemic_status", "ALTER TABLE memories ADD COLUMN epistemic_status TEXT NOT NULL DEFAULT 'subjective'");
572
+ addColumn("memories", "content_history", "ALTER TABLE memories ADD COLUMN content_history TEXT");
573
+ addColumn("memories", "quality_score", "ALTER TABLE memories ADD COLUMN quality_score REAL");
574
574
 
575
575
  // Legacy dream_runs without policy_epoch → backfill with the default epoch.
576
- const dreamCols = db.prepare("PRAGMA table_info(dream_runs)").all().map((c) => c.name);
577
- if (!dreamCols.includes("policy_epoch")) {
578
- db.exec("ALTER TABLE dream_runs ADD COLUMN policy_epoch INTEGER NOT NULL DEFAULT 0");
579
- }
580
- if (!dreamCols.includes("run_type")) {
581
- db.exec("ALTER TABLE dream_runs ADD COLUMN run_type TEXT NOT NULL DEFAULT 'auto'");
582
- }
576
+ addColumn("dream_runs", "policy_epoch", "ALTER TABLE dream_runs ADD COLUMN policy_epoch INTEGER NOT NULL DEFAULT 0");
577
+ addColumn("dream_runs", "run_type", "ALTER TABLE dream_runs ADD COLUMN run_type TEXT NOT NULL DEFAULT 'auto'");
583
578
 
584
579
  // Legacy mirror_state without v0.3.6 generation columns → add each missing
585
580
  // column idempotently (old DBs open cleanly, no data loss).
586
- const mirrorCols = db.prepare("PRAGMA table_info(mirror_state)").all().map((c) => c.name);
587
- if (!mirrorCols.includes("generation")) {
588
- db.exec("ALTER TABLE mirror_state ADD COLUMN generation INTEGER NOT NULL DEFAULT 0");
589
- }
590
- if (!mirrorCols.includes("applied_generation")) {
591
- db.exec("ALTER TABLE mirror_state ADD COLUMN applied_generation INTEGER NOT NULL DEFAULT 0");
592
- }
593
- if (!mirrorCols.includes("type_status")) {
594
- db.exec("ALTER TABLE mirror_state ADD COLUMN type_status TEXT");
595
- }
581
+ addColumn("mirror_state", "generation", "ALTER TABLE mirror_state ADD COLUMN generation INTEGER NOT NULL DEFAULT 0");
582
+ addColumn("mirror_state", "applied_generation", "ALTER TABLE mirror_state ADD COLUMN applied_generation INTEGER NOT NULL DEFAULT 0");
583
+ addColumn("mirror_state", "type_status", "ALTER TABLE mirror_state ADD COLUMN type_status TEXT");
596
584
 
597
585
  // Audit peer F: a legacy DB may hold a non-integer generation/applied_generation
598
586
  // (pre-v0.3.9 the JS gate truncated with Math.trunc and SQLite's CHECK only
@@ -923,6 +911,29 @@ export function createStore(path) {
923
911
  db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run(json, id);
924
912
  }
925
913
 
914
+ /** Batch fetch stored embeddings by id (v0.5.0 search-time semantic dedup).
915
+ * Returns a Map(id → number[]); rows without a parseable embedding are
916
+ * simply absent from the map. */
917
+ function getEmbeddings(ids) {
918
+ const out = new Map();
919
+ const list = (Array.isArray(ids) ? ids : []).filter(Boolean);
920
+ for (let i = 0; i < list.length; i += 100) {
921
+ const chunk = list.slice(i, i + 100);
922
+ const rows = db.prepare(
923
+ `SELECT id, embedding FROM memories
924
+ WHERE embedding IS NOT NULL AND embedding != ''
925
+ AND id IN (${chunk.map(() => "?").join(",")})`
926
+ ).all(...chunk);
927
+ for (const row of rows) {
928
+ try {
929
+ const vec = JSON.parse(row.embedding);
930
+ if (Array.isArray(vec) && vec.length) out.set(row.id, vec);
931
+ } catch { /* corrupt row: skip */ }
932
+ }
933
+ }
934
+ return out;
935
+ }
936
+
926
937
  function embeddedCount() {
927
938
  return db.prepare(
928
939
  "SELECT count(*) AS c FROM memories WHERE embedding IS NOT NULL AND embedding != ''"
@@ -1864,6 +1875,7 @@ export function createStore(path) {
1864
1875
  all,
1865
1876
  search,
1866
1877
  setEmbedding,
1878
+ getEmbeddings,
1867
1879
  embeddedCount,
1868
1880
  needsEmbedding,
1869
1881
  searchVector,
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 7 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.4.6",
4
+ "version": "0.5.0",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/modusensus/dsh-mneme.git"
9
+ },
10
+ "homepage": "https://github.com/modusensus/dsh-mneme#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/modusensus/dsh-mneme/issues"
13
+ },
6
14
  "type": "module",
7
15
  "main": "lib/index.js",
8
16
  "exports": {
@@ -0,0 +1,133 @@
1
+ // Recall benchmark (v0.5.0 评测体系): a self-contained harness that seeds an
2
+ // in-memory store with labelled memories, runs a standard query set through
3
+ // the real searchMemories pipeline, and reports Recall@K / MRR per case and
4
+ // in aggregate. Runs in two configurations so the BM25/third-path lift is
5
+ // visible: `legacy` (bm25 + adaptive + dedup off) vs `fused` (defaults on).
6
+ //
7
+ // Usage:
8
+ // node scripts/benchmark-recall.js # run both configurations
9
+ // node scripts/benchmark-recall.js --json # machine-readable output
10
+ // The harness exports runBenchmark()/TEST_CASES for the test suite; the CLI
11
+ // path below only executes when invoked directly.
12
+ import { createStore } from "../src/store.js";
13
+ import { createService } from "../src/service.js";
14
+ import { createVectorIndex } from "../src/vector-index.js";
15
+
16
+ // Deterministic toy embedder: bag-of-words hashed into a fixed-dimension
17
+ // vector, so cosine similarity ≈ lexical overlap. Good enough to exercise
18
+ // the vector path mechanically — semantic quality is not under test here.
19
+ const DIM = 256;
20
+ function hashVec(text) {
21
+ const v = new Array(DIM).fill(0);
22
+ const tokens = String(text ?? "").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
23
+ for (const t of tokens) {
24
+ let h = 0;
25
+ for (const ch of t) h = (h * 31 + ch.codePointAt(0)) >>> 0;
26
+ v[h % DIM] += 1;
27
+ }
28
+ const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
29
+ return v.map((x) => x / norm);
30
+ }
31
+
32
+ const SEED = [
33
+ { id: "mem_user_pref", type: "preference", title: "编辑器偏好", content: "用户偏好 VS Code,深色主题,等宽字体 JetBrains Mono", importance: 4, tags: ["editor"] },
34
+ { id: "mem_user_project", type: "project", title: "dsh-mneme 插件项目", content: "用户在开发 dsh-mneme 记忆插件,TypeScript 与 cordis 框架", importance: 5, tags: ["plugin"] },
35
+ { id: "mem_rust_switch", type: "decision", title: "语言迁移决策", content: "项目编译模块从 Go 迁移到 Rust,理由是内存安全", importance: 4, tags: ["rust"] },
36
+ { id: "mem_zfs_bug", type: "project", title: "ZFS-4421 数据损坏", content: "线上池 ZFS-4421 出现 checksum 错误,根因是 HBA 固件 bug", importance: 5, tags: ["ops"] },
37
+ { id: "mem_city_thesis", type: "project", title: "湿地论文", content: "毕业论文研究城市湿地公园周边开发案例,ArcGIS 空间分析", importance: 4, tags: ["thesis"] },
38
+ { id: "mem_async_pattern", type: "decision", title: "异步并发模式", content: "async runtime 选用 tokio,任务用 spawn 管理,channel 通信", importance: 3, tags: ["rust"] },
39
+ { id: "mem_python_etl", type: "project", title: "ETL 脚本", content: "夜间 ETL 用 Python 编写,pandas 清洗,SQLite 落地", importance: 3, tags: ["etl"] },
40
+ { id: "mem_ui_style", type: "preference", title: "界面审美", content: "喜欢编辑风 brutalism 排版,低饱和度配色,衬线标题", importance: 3, tags: ["design"] }
41
+ ];
42
+
43
+ // Standard query set: each case is a query plus the ids that MUST appear in
44
+ // the top-K for the case to count as a hit. Covers the three recall paths —
45
+ // multi-term lexical (BM25's home turf), identifier lookup, and semantic.
46
+ export const TEST_CASES = [
47
+ { query: "rust 异步", expected: ["mem_async_pattern", "mem_rust_switch"], note: "scattered terms — BM25 territory" },
48
+ { query: "ZFS-4421 checksum", expected: ["mem_zfs_bug"], note: "identifier + keyword" },
49
+ { query: "插件 开发", expected: ["mem_user_project"], note: "multi-term CJK" },
50
+ { query: "论文 空间分析", expected: ["mem_city_thesis"], note: "scattered CJK terms" },
51
+ { query: "ETL 脚本", expected: ["mem_python_etl"], note: "mixed" },
52
+ { query: "深色主题", expected: ["mem_user_pref"], note: "substring match" },
53
+ { query: "channel 通信 任务", expected: ["mem_async_pattern"], note: "scattered terms" },
54
+ { query: "内存安全 语言", expected: ["mem_rust_switch"], note: "scattered terms" },
55
+ { query: "配色 审美", expected: ["mem_ui_style"], note: "scattered CJK" },
56
+ { query: "HBA 固件", expected: ["mem_zfs_bug"], note: "scattered terms" }
57
+ ];
58
+
59
+ function seedService(overrides = {}) {
60
+ const store = createStore(":memory:");
61
+ const config = {
62
+ bm25SearchEnabled: true,
63
+ adaptiveThresholdEnabled: true,
64
+ searchSemanticDedup: true,
65
+ searchSemanticDedupThreshold: 0.95,
66
+ selectiveInjectEnabled: true,
67
+ entitySearchEnabled: false,
68
+ ...overrides
69
+ };
70
+ const service = createService({ store, mirror: null, config, logger: null });
71
+ const vectorIndex = createVectorIndex({ store, logger: null });
72
+ service.setVectorIndex(vectorIndex);
73
+ service.setEmbedder({
74
+ embedSingle: async (text) => hashVec(text)
75
+ });
76
+ for (const m of SEED) {
77
+ const row = store.save({ type: m.type, title: m.title, content: m.content, tags: m.tags, importance: m.importance, source: "seed" });
78
+ store.setEmbedding(row.id, hashVec(`${m.title} ${m.content}`));
79
+ }
80
+ return service;
81
+ }
82
+
83
+ export async function runBenchmark({ topK = 5, mode = "auto" } = {}) {
84
+ const configs = [
85
+ { name: "legacy", overrides: { bm25SearchEnabled: false, adaptiveThresholdEnabled: false, searchSemanticDedup: false } },
86
+ { name: "fused", overrides: {} }
87
+ ];
88
+ const runs = [];
89
+ for (const cfg of configs) {
90
+ const service = seedService(cfg.overrides);
91
+ const rows = [];
92
+ let hits = 0;
93
+ let mrrSum = 0;
94
+ for (const tc of TEST_CASES) {
95
+ const results = await service.searchMemories(tc.query, { mode, topK, useRerank: false });
96
+ const ids = results.map((r) => r.id);
97
+ const metrics = service.computeRetrievalMetrics(ids, tc.expected);
98
+ if (metrics.recall === 1) hits++;
99
+ mrrSum += metrics.mrr;
100
+ rows.push({ query: tc.query, note: tc.note, expected: tc.expected, got: ids, ...metrics });
101
+ }
102
+ runs.push({
103
+ config: cfg.name,
104
+ recallAtK: +(hits / TEST_CASES.length).toFixed(3),
105
+ avgMrr: +(mrrSum / TEST_CASES.length).toFixed(3),
106
+ rows
107
+ });
108
+ }
109
+ return { topK, mode, runs };
110
+ }
111
+
112
+ function printReport(report) {
113
+ for (const run of report.runs) {
114
+ console.log(`\n=== ${run.config} (topK=${report.topK}, mode=${report.mode}) ===`);
115
+ for (const r of run.rows) {
116
+ const ok = r.recall === 1 ? "PASS" : "MISS";
117
+ console.log(` [${ok}] "${r.query}" (${r.note}) recall=${r.recall} mrr=${r.mrr}`);
118
+ if (r.recall < 1) console.log(` expected ⊇ ${r.expected.join(", ")} got: ${r.got.join(", ") || "—"}`);
119
+ }
120
+ console.log(` → Recall@${report.topK}: ${(run.recallAtK * 100).toFixed(1)}% avg MRR: ${run.avgMrr}`);
121
+ }
122
+ const [legacy, fused] = report.runs;
123
+ const lift = ((fused.recallAtK - legacy.recallAtK) * 100).toFixed(1);
124
+ console.log(`\n三路融合 vs 旧两路: Recall@${report.topK} ${legacy.recallAtK * 100}% → ${fused.recallAtK * 100}% (${lift >= 0 ? "+" : ""}${lift}pp)`);
125
+ }
126
+
127
+ const invokedDirectly = process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop() ?? "");
128
+ if (invokedDirectly) {
129
+ const asJson = process.argv.includes("--json");
130
+ const report = await runBenchmark({});
131
+ if (asJson) console.log(JSON.stringify(report, null, 2));
132
+ else printReport(report);
133
+ }