@modusensus/dsh-mneme 0.4.7 → 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.
- package/README.md +36 -5
- package/lib/api.js +516 -400
- package/lib/client.js +1302 -505
- package/lib/commands.js +64 -64
- package/lib/config.js +252 -223
- package/lib/dream.js +817 -788
- package/lib/embedding.js +154 -154
- package/lib/hot-memory.js +46 -0
- package/lib/index.js +341 -341
- package/lib/inject.js +208 -127
- package/lib/local-embedder.js +282 -276
- package/lib/search/adaptive.js +22 -0
- package/lib/search/bm25.js +96 -0
- package/lib/service.js +135 -8
- package/lib/store.js +24 -0
- package/package.json +9 -1
- package/scripts/benchmark-recall.js +133 -0
- package/src/api.js +117 -1
- package/src/config.js +30 -1
- package/src/dream.js +41 -12
- package/src/hot-memory.js +46 -0
- package/src/inject.js +84 -3
- package/src/local-embedder.js +7 -1
- package/src/search/adaptive.js +22 -0
- package/src/search/bm25.js +96 -0
- package/src/service.js +135 -8
- package/src/store.js +24 -0
- package/test/benchmark.test.js +35 -0
- package/test/client.test.js +205 -15
- package/test/graph-api.test.js +175 -0
- package/test/hot-memory.test.js +145 -0
- package/test/reasoning-effort.test.js +1 -1
- package/test/recall-layer.test.js +2 -2
- package/test/search-fusion.test.js +90 -0
- package/test/service-search.test.js +6 -2
|
@@ -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
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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
|
|
391
|
-
// Weighted blend when
|
|
392
|
-
// vector order leads (it is the semantic signal),
|
|
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
|
|
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
|
@@ -911,6 +911,29 @@ export function createStore(path) {
|
|
|
911
911
|
db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run(json, id);
|
|
912
912
|
}
|
|
913
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
|
+
|
|
914
937
|
function embeddedCount() {
|
|
915
938
|
return db.prepare(
|
|
916
939
|
"SELECT count(*) AS c FROM memories WHERE embedding IS NOT NULL AND embedding != ''"
|
|
@@ -1852,6 +1875,7 @@ export function createStore(path) {
|
|
|
1852
1875
|
all,
|
|
1853
1876
|
search,
|
|
1854
1877
|
setEmbedding,
|
|
1878
|
+
getEmbeddings,
|
|
1855
1879
|
embeddedCount,
|
|
1856
1880
|
needsEmbedding,
|
|
1857
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
|
+
"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
|
+
}
|
package/src/api.js
CHANGED
|
@@ -103,7 +103,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
|
|
|
103
103
|
try {
|
|
104
104
|
const url = new URL(req.url, "http://localhost");
|
|
105
105
|
const q = url.searchParams.get("q") ?? "";
|
|
106
|
-
const limit = Number(url.searchParams.get("limit") ?? 20);
|
|
106
|
+
const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
|
|
107
107
|
// mode selects the recall strategy (defaults to auto):
|
|
108
108
|
// auto (default) keyword first, vector fills remaining slots
|
|
109
109
|
// hybrid vector first, keyword fills remaining slots; scores of
|
|
@@ -306,6 +306,122 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
|
|
|
306
306
|
}
|
|
307
307
|
});
|
|
308
308
|
|
|
309
|
+
// --- ego graph: 1-2 hop neighborhood of one entity (graph panel P1) ---
|
|
310
|
+
// Read-only like list/search/semantic, so it stays open when apiToken is set.
|
|
311
|
+
// BFS from the root entity over entity_relations (both directions; the
|
|
312
|
+
// idx_relations_from/to indexes keep a 2-hop walk in the tens of ms even
|
|
313
|
+
// for a few thousand nodes). `distance` on each node is the hop count from
|
|
314
|
+
// the root so the UI can shade the frontier. The API is graph-traversal
|
|
315
|
+
// only — nodes carry no attr payload; hover summaries come from
|
|
316
|
+
// /semantic/graph/entity-attrs.
|
|
317
|
+
register({
|
|
318
|
+
kind: "exact",
|
|
319
|
+
path: "/api/dsh-mneme/semantic/graph/ego",
|
|
320
|
+
handler(req, res) {
|
|
321
|
+
try {
|
|
322
|
+
const url = new URL(req.url, "http://localhost");
|
|
323
|
+
const name = (url.searchParams.get("entity") ?? "").trim();
|
|
324
|
+
if (!name) {
|
|
325
|
+
sendJson(res, 400, { error: "missing-entity" });
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const root = service.findEntityByName?.(name);
|
|
329
|
+
if (!root) {
|
|
330
|
+
sendJson(res, 404, { error: "entity-not-found" });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const depth = Math.max(1, Math.min(2, Number(url.searchParams.get("depth") ?? 1) || 1));
|
|
334
|
+
const limit = Math.max(1, Math.min(100, Number(url.searchParams.get("limit") ?? 40) || 40));
|
|
335
|
+
|
|
336
|
+
const nodes = new Map([[root.id, { ...root, distance: 0 }]]);
|
|
337
|
+
let frontier = [root.id];
|
|
338
|
+
for (let d = 1; d <= depth && nodes.size < limit; d++) {
|
|
339
|
+
const next = [];
|
|
340
|
+
for (const id of frontier) {
|
|
341
|
+
for (const rel of service.getRelations?.(id) ?? []) {
|
|
342
|
+
const other = rel.from_entity === id ? rel.to_entity : rel.from_entity;
|
|
343
|
+
if (nodes.has(other) || nodes.size >= limit) continue;
|
|
344
|
+
const entity = service.findEntityById?.(other);
|
|
345
|
+
if (!entity) continue;
|
|
346
|
+
nodes.set(other, { ...entity, distance: d });
|
|
347
|
+
next.push(other);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
frontier = next;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Collect every relation whose endpoints both survived the limit cut;
|
|
354
|
+
// each edge is visited twice (once per endpoint) so dedupe by id.
|
|
355
|
+
const edgeMap = new Map();
|
|
356
|
+
for (const id of nodes.keys()) {
|
|
357
|
+
for (const rel of service.getRelations?.(id) ?? []) {
|
|
358
|
+
if (nodes.has(rel.from_entity) && nodes.has(rel.to_entity)) {
|
|
359
|
+
edgeMap.set(rel.id, rel);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
sendJson(res, 200, {
|
|
365
|
+
root: { id: root.id, name: root.name, type: root.type ?? null, mention_count: root.mention_count ?? 1 },
|
|
366
|
+
nodes: [...nodes.values()].map((n) => ({
|
|
367
|
+
id: n.id,
|
|
368
|
+
name: n.name,
|
|
369
|
+
type: n.type ?? null,
|
|
370
|
+
mention_count: n.mention_count ?? 1,
|
|
371
|
+
distance: n.distance
|
|
372
|
+
})),
|
|
373
|
+
edges: [...edgeMap.values()].map((e) => ({
|
|
374
|
+
id: e.id,
|
|
375
|
+
from: e.from_entity,
|
|
376
|
+
to: e.to_entity,
|
|
377
|
+
relation_type: e.relation_type,
|
|
378
|
+
memory_id: e.memory_id ?? null,
|
|
379
|
+
created_at: e.created_at
|
|
380
|
+
}))
|
|
381
|
+
});
|
|
382
|
+
} catch {
|
|
383
|
+
sendJson(res, 500, { error: "internal" });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// --- entity attrs: current valid attrs for one entity (graph hover panel) ---
|
|
389
|
+
// Read-only; mirrors getCurrentAttrs (valid_until IS NULL). Also used as the
|
|
390
|
+
// graph panel's fallback list when the ego graph is too sparse to draw.
|
|
391
|
+
register({
|
|
392
|
+
kind: "exact",
|
|
393
|
+
path: "/api/dsh-mneme/semantic/graph/entity-attrs",
|
|
394
|
+
handler(req, res) {
|
|
395
|
+
try {
|
|
396
|
+
const url = new URL(req.url, "http://localhost");
|
|
397
|
+
const name = (url.searchParams.get("entity") ?? "").trim();
|
|
398
|
+
if (!name) {
|
|
399
|
+
sendJson(res, 400, { error: "missing-entity" });
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const entity = service.findEntityByName?.(name);
|
|
403
|
+
if (!entity) {
|
|
404
|
+
sendJson(res, 404, { error: "entity-not-found" });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const attrs = service.getCurrentAttrs?.(entity.id) ?? [];
|
|
408
|
+
sendJson(res, 200, {
|
|
409
|
+
entity: { id: entity.id, name: entity.name, type: entity.type ?? null, mention_count: entity.mention_count ?? 1 },
|
|
410
|
+
attrs: Array.isArray(attrs)
|
|
411
|
+
? attrs.map((a) => ({
|
|
412
|
+
key: a.attr_key,
|
|
413
|
+
value: a.attr_value,
|
|
414
|
+
confidence: a.confidence ?? null,
|
|
415
|
+
valid_from: a.valid_from ?? null
|
|
416
|
+
}))
|
|
417
|
+
: []
|
|
418
|
+
});
|
|
419
|
+
} catch {
|
|
420
|
+
sendJson(res, 500, { error: "internal" });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
|
|
309
425
|
// --- health: mirror sync state (F-NEW-03 / v0.3.6) ---
|
|
310
426
|
// Auth-gated; only returns a sanitized error code (never raw last_error which
|
|
311
427
|
// may leak paths/token-like strings/internal hosts). On state read failure it
|
package/src/config.js
CHANGED
|
@@ -17,7 +17,7 @@ export const Config = z.object({
|
|
|
17
17
|
dreamDelayMs: z.natural().min(0).max(60000).default(2000),
|
|
18
18
|
dreamProvider: z.string(),
|
|
19
19
|
dreamModel: z.string(),
|
|
20
|
-
dreamMaxTokens: z.natural().min(256).max(131072).default(
|
|
20
|
+
dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
|
|
21
21
|
// Pass-through reasoning effort for dream's LLM calls. 'none' (default)
|
|
22
22
|
// omits the field so the provider's own default applies; low/medium/high
|
|
23
23
|
// are forwarded verbatim. Useful to cap reasoning spend on thinking-type
|
|
@@ -92,6 +92,35 @@ export const Config = z.object({
|
|
|
92
92
|
// rule-based pick to fill/dedupe. Empty query / no vector → legacy behavior.
|
|
93
93
|
hybridInject: z.boolean().default(true),
|
|
94
94
|
|
|
95
|
+
// --- recall optimization (v0.5.0) ----------------------------------------
|
|
96
|
+
// BM25 third recall path beside vector + LIKE keyword (1.1): per-token IDF
|
|
97
|
+
// scoring recalls rows whose query terms are scattered — identifiers, code
|
|
98
|
+
// fragments, mixed CJK/ASCII — where substring LIKE cannot match.
|
|
99
|
+
bm25SearchEnabled: z.boolean().default(true),
|
|
100
|
+
// Query-aware vector cutoff (1.2) replacing the fixed 0.65: entity:/attr:
|
|
101
|
+
// prefixes loosen to 0.5, short queries tighten to 0.7, long queries loosen
|
|
102
|
+
// to 0.6, and a decisive top-1/top-5 score gap loosens to 0.5 so the tail
|
|
103
|
+
// still reaches the reranker. Off = legacy fixed threshold behavior.
|
|
104
|
+
adaptiveThresholdEnabled: z.boolean().default(true),
|
|
105
|
+
// Session-scoped hot memory (1.3): the latest N dialogue rounds rendered
|
|
106
|
+
// ahead of the long-term recall block — short-term context that never
|
|
107
|
+
// enters the memory store.
|
|
108
|
+
hotMemoryEnabled: z.boolean().default(true),
|
|
109
|
+
hotMemoryRounds: z.natural().min(1).max(50).default(5),
|
|
110
|
+
hotMemoryMaxTokens: z.natural().min(200).max(32000).default(2000),
|
|
111
|
+
// Topic-ranked injection (2.2): when a query vector is available the whole
|
|
112
|
+
// injection candidate list is re-ordered by similarity to the current
|
|
113
|
+
// query instead of keeping the rule-based order.
|
|
114
|
+
selectiveInjectEnabled: z.boolean().default(true),
|
|
115
|
+
// Search-time semantic dedup (2.3): greedy pass over the merged candidate
|
|
116
|
+
// list dropping rows whose embedding cosine-similarity to an already-kept
|
|
117
|
+
// row exceeds the threshold — duplicates are filtered at recall time
|
|
118
|
+
// instead of waiting for a dream consolidation. Opt-in aggressive mode:
|
|
119
|
+
// small embedding models can collapse legitimately distinct rows, so the
|
|
120
|
+
// default keeps every recalled row.
|
|
121
|
+
searchSemanticDedup: z.boolean().default(false),
|
|
122
|
+
searchSemanticDedupThreshold: z.number().min(0.5).max(1).default(0.95),
|
|
123
|
+
|
|
95
124
|
// --- semantic: rerank layer (v0.2) --------------------------------------
|
|
96
125
|
// Opt-in by default (item ⑥): the local cross-encoder pulls in onnxruntime
|
|
97
126
|
// (transformers.js) at init, so a bare install must not load it. Only an
|