@modusensus/dsh-mneme 0.4.7 → 0.5.1

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,175 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { EventEmitter } from "node:events";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createApi } from "../src/api.js";
7
+ import { createSettings } from "../src/settings.js";
8
+
9
+ // Ego-graph read API (graph panel P1). The routes under test:
10
+ // GET /api/dsh-mneme/semantic/graph/ego?entity=&depth=&limit=
11
+ // GET /api/dsh-mneme/semantic/graph/entity-attrs?entity=
12
+ // Both are read-only: they must stay reachable without an apiToken, exactly
13
+ // like list/search/semantic.
14
+
15
+ class FakeRes extends EventEmitter {
16
+ constructor() { super(); this.statusCode = 200; this.body = ""; }
17
+ writeHead(code, headers) { this.statusCode = code; this.headers = headers; return this; }
18
+ end(text) { this.body = text ?? ""; this.emit("end"); return this; }
19
+ }
20
+
21
+ function req(path) {
22
+ const r = new EventEmitter();
23
+ r.url = path;
24
+ r.method = "GET";
25
+ r.headers = {};
26
+ return r;
27
+ }
28
+
29
+ function setup(apiToken = "") {
30
+ const store = createStore(":memory:");
31
+ const service = createService({ store, mirror: null, config: {} });
32
+ const settings = createSettings(store.db);
33
+ const commands = { add: () => {}, remove: () => {}, list: () => [] };
34
+ const routes = [];
35
+ const ctx = { webServer: { register(route) { routes.push(route); return () => {}; } } };
36
+ createApi(ctx, service, settings, commands, null, undefined, apiToken);
37
+ return { store, service, routes };
38
+ }
39
+
40
+ function graphRoute(routes, path) {
41
+ return routes.find((r) => r.path === path);
42
+ }
43
+
44
+ function buildChain(service, names, linkType = "related_to") {
45
+ // names → entities; each consecutive pair gets one relation. Returns a
46
+ // name→entity map so tests can assert on ids.
47
+ const map = new Map();
48
+ for (const n of names) map.set(n, service.createEntity({ name: n, type: "concept" }));
49
+ for (let i = 0; i < names.length - 1; i++) {
50
+ service.saveRelation({
51
+ from_entity: map.get(names[i]).id,
52
+ to_entity: map.get(names[i + 1]).id,
53
+ relation_type: linkType
54
+ });
55
+ }
56
+ return map;
57
+ }
58
+
59
+ test("ego route is registered and open without apiToken", async () => {
60
+ const { routes } = setup("secret-token");
61
+ const ego = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
62
+ const attrs = graphRoute(routes, "/api/dsh-mneme/semantic/graph/entity-attrs");
63
+ assert.ok(ego, "ego route must be registered");
64
+ assert.ok(attrs, "entity-attrs route must be registered");
65
+ // read-only: no 401 even with a token configured
66
+ const res = new FakeRes();
67
+ await ego.handler(req("/api/dsh-mneme/semantic/graph/ego"), res);
68
+ assert.equal(res.statusCode, 400, "missing param is a 400, not a 401");
69
+ });
70
+
71
+ test("ego depth 1 returns root + direct neighbors with distances", async () => {
72
+ const { routes, service } = setup();
73
+ const map = buildChain(service, ["A", "B", "C"]);
74
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
75
+ const res = new FakeRes();
76
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego?entity=A&depth=1"), res);
77
+ assert.equal(res.statusCode, 200);
78
+ const data = JSON.parse(res.body);
79
+ assert.equal(data.root.name, "A");
80
+ assert.equal(data.nodes.length, 2, "root + B only (C is 2 hops)");
81
+ assert.equal(data.edges.length, 1);
82
+ const b = data.nodes.find((n) => n.name === "B");
83
+ assert.equal(b.distance, 1);
84
+ assert.equal(data.nodes.find((n) => n.name === "A").distance, 0);
85
+ // edge shape: ids + relation_type, memory_id nullable
86
+ const edge = data.edges[0];
87
+ assert.ok(edge.id && edge.from && edge.to);
88
+ assert.equal(edge.relation_type, "related_to");
89
+ assert.equal(edge.memory_id, null);
90
+ });
91
+
92
+ test("ego depth 2 includes 2-hop nodes, not 3-hop", async () => {
93
+ const { routes, service } = setup();
94
+ buildChain(service, ["A", "B", "C", "D"]);
95
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
96
+ const res = new FakeRes();
97
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego?entity=A&depth=2"), res);
98
+ const data = JSON.parse(res.body);
99
+ const names = data.nodes.map((n) => n.name).sort();
100
+ assert.deepEqual(names, ["A", "B", "C"], "D is 3 hops away and must be excluded");
101
+ assert.equal(data.nodes.find((n) => n.name === "C").distance, 2);
102
+ assert.equal(data.edges.length, 2);
103
+ });
104
+
105
+ test("ego respects limit and keeps only in-graph edges", async () => {
106
+ const { routes, service } = setup();
107
+ const map = buildChain(service, ["A", "B", "C"]);
108
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
109
+ const res = new FakeRes();
110
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego?entity=A&depth=2&limit=2"), res);
111
+ const data = JSON.parse(res.body);
112
+ assert.equal(data.nodes.length, 2, "limit caps node count");
113
+ assert.equal(data.edges.length, 1, "edges to cut nodes are dropped");
114
+ });
115
+
116
+ test("ego reports 404 for unknown entity and 400 without entity", async () => {
117
+ const { routes } = setup();
118
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
119
+ let res = new FakeRes();
120
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego?entity=ghost"), res);
121
+ assert.equal(res.statusCode, 404);
122
+ assert.equal(JSON.parse(res.body).error, "entity-not-found");
123
+ res = new FakeRes();
124
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego"), res);
125
+ assert.equal(res.statusCode, 400);
126
+ assert.equal(JSON.parse(res.body).error, "missing-entity");
127
+ });
128
+
129
+ test("entity-attrs returns current valid attrs only", async () => {
130
+ const { routes, service } = setup();
131
+ const mem = service.saveWithDedupe({ type: "project", title: "t", content: "c" });
132
+ const entity = service.createEntity({ name: "X", type: "technology" });
133
+ service.saveAttr({ entity_id: entity.id, attr_key: "version", attr_value: "1", memory_id: mem.id, confidence: 0.9 });
134
+ // a second save of the same key invalidates the first: only one row stays valid
135
+ service.saveAttr({ entity_id: entity.id, attr_key: "version", attr_value: "2", memory_id: mem.id, confidence: 0.8 });
136
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/entity-attrs");
137
+ const res = new FakeRes();
138
+ await route.handler(req("/api/dsh-mneme/semantic/graph/entity-attrs?entity=X"), res);
139
+ assert.equal(res.statusCode, 200);
140
+ const data = JSON.parse(res.body);
141
+ assert.equal(data.entity.name, "X");
142
+ assert.equal(data.attrs.length, 1);
143
+ assert.equal(data.attrs[0].value, "2", "latest valid attr wins");
144
+ assert.equal(data.attrs[0].confidence, 0.8);
145
+ // unknown / missing entity
146
+ let r2 = new FakeRes();
147
+ await route.handler(req("/api/dsh-mneme/semantic/graph/entity-attrs?entity=nope"), r2);
148
+ assert.equal(r2.statusCode, 404);
149
+ r2 = new FakeRes();
150
+ await route.handler(req("/api/dsh-mneme/semantic/graph/entity-attrs"), r2);
151
+ assert.equal(r2.statusCode, 400);
152
+ });
153
+
154
+ test("ego 2-hop over 100+ nodes stays under 50ms (spec §7)", async () => {
155
+ const { routes, service } = setup();
156
+ // star-of-stars: hub → 20 spokes, each spoke → 5 leaves = 121 nodes, 120 edges
157
+ const hub = service.createEntity({ name: "hub", type: "project" });
158
+ for (let i = 0; i < 20; i++) {
159
+ const spoke = service.createEntity({ name: `spoke-${i}`, type: "technology" });
160
+ service.saveRelation({ from_entity: hub.id, to_entity: spoke.id, relation_type: "uses" });
161
+ for (let j = 0; j < 5; j++) {
162
+ const leaf = service.createEntity({ name: `leaf-${i}-${j}`, type: "concept" });
163
+ service.saveRelation({ from_entity: spoke.id, to_entity: leaf.id, relation_type: "related_to" });
164
+ }
165
+ }
166
+ const route = graphRoute(routes, "/api/dsh-mneme/semantic/graph/ego");
167
+ const res = new FakeRes();
168
+ const start = process.hrtime.bigint();
169
+ await route.handler(req("/api/dsh-mneme/semantic/graph/ego?entity=hub&depth=2&limit=100"), res);
170
+ const ms = Number(process.hrtime.bigint() - start) / 1e6;
171
+ const data = JSON.parse(res.body);
172
+ assert.equal(data.nodes.length, 100, "limit caps the traversal");
173
+ assert.ok(data.edges.length > 0);
174
+ assert.ok(ms < 50, `2-hop query took ${ms.toFixed(1)}ms, spec budget is 50ms`);
175
+ });
@@ -0,0 +1,174 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHotMemory, estimateTokens } from "../src/hot-memory.js";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createVectorIndex } from "../src/vector-index.js";
7
+
8
+ // --- hot memory buffer ---
9
+
10
+ test("hot memory keeps the latest rounds within maxRounds", () => {
11
+ const hot = createHotMemory({ maxRounds: 2, maxTokens: 10000 });
12
+ hot.add({ query: "第一轮", response: "答一" });
13
+ hot.add({ query: "第二轮", response: "答二" });
14
+ hot.add({ query: "第三轮", response: "答三" });
15
+ assert.equal(hot.rounds().length, 2);
16
+ assert.ok(hot.getContext().includes("第三轮"));
17
+ assert.ok(!hot.getContext().includes("第一轮"));
18
+ });
19
+
20
+ test("hot memory enforces the token budget", () => {
21
+ const hot = createHotMemory({ maxRounds: 10, maxTokens: 30 });
22
+ hot.add({ query: "很长的第一轮问题".repeat(10), response: "很长的回答".repeat(10) });
23
+ hot.add({ query: "第二轮", response: "答二" });
24
+ // The first round alone blows the budget; the newest round survives and
25
+ // the buffer never empties completely.
26
+ const rounds = hot.rounds();
27
+ assert.ok(rounds.length >= 1);
28
+ assert.equal(rounds[rounds.length - 1].query, "第二轮");
29
+ });
30
+
31
+ test("hot memory getContext uses the Q/A round format", () => {
32
+ const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
33
+ hot.add({ query: "Q1", response: "A1" });
34
+ hot.add({ query: "Q2", response: "A2" });
35
+ assert.equal(hot.getContext(), "Q: Q1\nA: A1\n\nQ: Q2\nA: A2");
36
+ });
37
+
38
+ test("hot memory ignores empty rounds and clears", () => {
39
+ const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
40
+ hot.add({ query: "", response: "x" });
41
+ hot.add(null);
42
+ assert.equal(hot.rounds().length, 0);
43
+ hot.add({ query: "q" });
44
+ hot.clear();
45
+ assert.equal(hot.getContext(), "");
46
+ });
47
+
48
+ test("estimateTokens counts CJK heavier than ASCII", () => {
49
+ assert.ok(estimateTokens("中文内容") > estimateTokens("abcd"));
50
+ });
51
+
52
+ // --- entry defense: non-positive / non-integer bounds fall back to defaults ---
53
+ // Bug: createHotMemory({ maxRounds: -1 }) made the eviction while-loop
54
+ // `while (buffer.length > maxRounds)` unbounded — after the buffer emptied,
55
+ // `0 > -1` stayed true and buffer.shift() on an empty array is a no-op, so
56
+ // every add() spun forever. Non-integer values (1.5, NaN, null) were also
57
+ // silently wrong. The fix clamps them to the 5/2000 defaults at the door.
58
+
59
+ test("hot memory falls back to maxRounds=5 for non-positive/invalid values", () => {
60
+ for (const bad of [0, -1, 1.5, NaN, null]) {
61
+ const hot = createHotMemory({ maxRounds: bad, maxTokens: 10000 });
62
+ for (let i = 0; i < 8; i++) hot.add({ query: `第${i}轮`, response: "x" });
63
+ assert.equal(hot.rounds().length, 5, `maxRounds=${bad} must fall back to 5, no infinite loop`);
64
+ assert.ok(hot.getContext().includes("第7轮"), `maxRounds=${bad}: newest round survives`);
65
+ assert.ok(!hot.getContext().includes("第0轮"), `maxRounds=${bad}: oldest round evicted`);
66
+ }
67
+ });
68
+
69
+ test("hot memory falls back to maxTokens=2000 for non-positive/infinite values", () => {
70
+ for (const bad of [0, -1, Infinity]) {
71
+ const hot = createHotMemory({ maxRounds: 50, maxTokens: bad });
72
+ // 50 rounds at ~74 tokens each blow a 2000-token budget; the fallback must
73
+ // evict into (1, 50). A broken budget of 0/-1 would squeeze to 1 round and
74
+ // Infinity would keep all 50 — both are the pre-fix behavior.
75
+ for (let i = 0; i < 50; i++) hot.add({ query: `第${i}轮`, response: "长回答".repeat(40) });
76
+ const n = hot.rounds().length;
77
+ assert.ok(n > 1 && n < 50, `maxTokens=${bad} falls back to 2000 (kept ${n} rounds)`);
78
+ }
79
+ });
80
+
81
+ // --- service-level: BM25 fusion + semantic dedup + selective injection ---
82
+
83
+ function toyVec(text) {
84
+ const v = new Array(64).fill(0);
85
+ for (const t of String(text).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean)) {
86
+ let h = 0;
87
+ for (const ch of t) h = (h * 31 + ch.codePointAt(0)) >>> 0;
88
+ v[h % 64] += 1;
89
+ }
90
+ const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
91
+ return v.map((x) => x / norm);
92
+ }
93
+
94
+ function setup(overrides = {}) {
95
+ const store = createStore(":memory:");
96
+ const config = {
97
+ entitySearchEnabled: false,
98
+ bm25SearchEnabled: true,
99
+ adaptiveThresholdEnabled: false,
100
+ searchSemanticDedup: true,
101
+ selectiveInjectEnabled: true,
102
+ ...overrides
103
+ };
104
+ const service = createService({ store, mirror: null, config, logger: null });
105
+ service.setVectorIndex(createVectorIndex({ store, logger: null }));
106
+ service.setEmbedder({ embedSingle: async (t) => toyVec(t) });
107
+ return { store, service };
108
+ }
109
+
110
+ test("searchMemories fuses BM25: scattered-term queries recall both rows", async () => {
111
+ const { store, service } = setup();
112
+ const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
113
+ const b = store.save({ type: "decision", title: "语言迁移", content: "编译模块迁移到 Rust", importance: 3 });
114
+ store.save({ type: "project", title: "无关", content: "夜间 ETL 脚本", importance: 3 });
115
+
116
+ // "rust 异步" is not a substring of either row — LIKE misses both; BM25
117
+ // must surface both rows in the merged result.
118
+ const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
119
+ const ids = results.map((r) => r.id);
120
+ assert.ok(ids.includes(a.id), "async row must be recalled via BM25");
121
+ assert.ok(ids.includes(b.id), "rust row must be recalled via BM25");
122
+ assert.equal(results.find((r) => r.id === a.id)?.source, "bm25");
123
+ });
124
+
125
+ test("bm25SearchEnabled=false restores the two-path behavior", async () => {
126
+ const { store, service } = setup({ bm25SearchEnabled: false });
127
+ const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
128
+ const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
129
+ assert.ok(!results.some((r) => r.id === a.id), "no BM25 → scattered-term miss is back");
130
+ });
131
+
132
+ test("search-time semantic dedup drops near-identical embeddings", async () => {
133
+ const { store, service } = setup();
134
+ const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
135
+ const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
136
+ store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
137
+ store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
138
+
139
+ // auto (not keyword): keyword mode is the documented text-only path and is
140
+ // exempt from dedup by design; auto exercises the dedup the way production
141
+ // searches run.
142
+ const results = await service.searchMemories("深色主题", { mode: "auto", topK: 5 });
143
+ const ids = results.map((r) => r.id);
144
+ assert.ok(ids.includes(a.id) !== ids.includes(b.id), "one of the near-duplicate pair is dropped");
145
+ });
146
+
147
+ test("searchSemanticDedup=false keeps duplicate embeddings", async () => {
148
+ const { store, service } = setup({ searchSemanticDedup: false });
149
+ const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
150
+ const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
151
+ store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
152
+ store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
153
+ const results = await service.searchMemories("深色主题", { mode: "keyword", topK: 5 });
154
+ assert.equal(results.length, 2);
155
+ });
156
+
157
+ test("selective injection re-orders candidates by query similarity", () => {
158
+ const { store, service } = setup();
159
+ const thesis = store.save({ type: "project", title: "湿地论文", content: "毕业论文研究城市湿地公园", importance: 5 });
160
+ const plugin = store.save({ type: "project", title: "插件项目", content: "dsh-mneme 记忆插件开发", importance: 5 });
161
+ store.setEmbedding(thesis.id, toyVec("毕业论文研究城市湿地公园"));
162
+ store.setEmbedding(plugin.id, toyVec("dsh-mneme 记忆插件开发"));
163
+
164
+ // Rule-based order would put both at equal importance; the query vector is
165
+ // about the thesis, so topic ranking must put the thesis memory first.
166
+ const picked = service.injectCandidates({
167
+ query: "论文写作",
168
+ queryVector: toyVec("毕业论文研究城市湿地公园"),
169
+ maxItems: 2,
170
+ threshold: 3
171
+ });
172
+ assert.equal(picked[0].id, thesis.id);
173
+ assert.ok(picked.some((m) => m.id === plugin.id));
174
+ });
@@ -25,7 +25,7 @@ const embedder = {
25
25
  // ---------------------------------------------------------------- config schema
26
26
 
27
27
  test("issue#9: dreamMaxTokens accepts the widened 131072 cap and defaults to 4096", () => {
28
- assert.equal(Config({}).dreamMaxTokens, 4096, "default unchanged");
28
+ assert.equal(Config({}).dreamMaxTokens, 8192, "default unchanged");
29
29
  assert.equal(Config({ dreamMaxTokens: 131072 }).dreamMaxTokens, 131072, "new upper bound accepted");
30
30
  assert.equal(Config({ dreamMaxTokens: 65536 }).dreamMaxTokens, 65536, "intermediate value accepted");
31
31
  });
@@ -17,9 +17,9 @@ const embedder = {
17
17
 
18
18
  // Real store + service wired with the mock embedder and a vector index over the
19
19
  // same store (the service's vector path prefers vectorIndex when set).
20
- function setup() {
20
+ function setup(config = {}) {
21
21
  const store = createStore(":memory:");
22
- const service = createService({ store, mirror: null, config: {} });
22
+ const service = createService({ store, mirror: null, config });
23
23
  const vectorIndex = createVectorIndex({ store });
24
24
  service.setEmbedder(embedder);
25
25
  service.setVectorIndex(vectorIndex);
@@ -1,5 +1,7 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { spawnSync } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
3
5
  import { LocalReranker } from "../src/reranker.js";
4
6
 
5
7
  /** Injected scorer: records (query, passage) calls, returns a fixed score. */
@@ -195,3 +197,44 @@ test("dispose releases the loaded pipeline", async () => {
195
197
  assert.equal(r.pipeline, null);
196
198
  assert.equal(extractor.disposed, true);
197
199
  });
200
+
201
+ test("default pipeline loader mirrors cache_dir onto env.cacheDir (issue #13)", () => {
202
+ // The fix lives in the module's *default* loader — the dynamic-import of
203
+ // @huggingface/transformers that the in-process tests bypass by injecting
204
+ // engineFactory. So it is exercised in a child node process under the
205
+ // --experimental-test-module-mocks flag: the transformers module is mocked
206
+ // with an empty env, LocalReranker uses the real default loader, and we
207
+ // assert env.cacheDir picks up the constructor's cache_dir. A regression
208
+ // (loader no longer mirroring) fails the child and surfaces here as a
209
+ // non-zero exit.
210
+ const srcUrl = new URL("../src/reranker.js", import.meta.url).href;
211
+ const cacheDir = "/tmp/dsh-mneme-cache-mirror-test";
212
+ const script = `
213
+ import { test } from "node:test";
214
+ const cacheDir = ${JSON.stringify(cacheDir)};
215
+ test("cache_dir is mirrored onto env.cacheDir", async (t) => {
216
+ t.mock.module("@huggingface/transformers", {
217
+ namedExports: {
218
+ env: {},
219
+ pipeline: async () => ({ dispose: () => {} })
220
+ }
221
+ });
222
+ const { LocalReranker } = await import(${JSON.stringify(srcUrl)});
223
+ const r = new LocalReranker({ cacheDir, device: "cpu" });
224
+ await r.init();
225
+ const { env } = await import("@huggingface/transformers");
226
+ if (env.cacheDir !== cacheDir) {
227
+ throw new Error("env.cacheDir not mirrored from cache_dir: " + env.cacheDir);
228
+ }
229
+ console.log("CACHE_MIRROR_OK");
230
+ });
231
+ `;
232
+ const res = spawnSync(process.execPath, [
233
+ "--experimental-test-module-mocks",
234
+ "--input-type=module",
235
+ "-e",
236
+ script
237
+ ], { encoding: "utf8", cwd: fileURLToPath(new URL("..", import.meta.url)) });
238
+ assert.equal(res.status, 0, `cache-dir mirror child failed:\n${res.stdout}\n${res.stderr}`);
239
+ assert.match(res.stdout, /CACHE_MIRROR_OK/);
240
+ });
@@ -0,0 +1,90 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { tokenize, createBM25Index } from "../src/search/bm25.js";
4
+ import { adaptiveThreshold } from "../src/search/adaptive.js";
5
+
6
+ // --- tokenizer ---
7
+
8
+ test("tokenize keeps ASCII identifiers whole", () => {
9
+ assert.deepEqual(
10
+ tokenize("ZFS-4421 dsh_mneme v2"),
11
+ ["zfs", "4421", "dsh_mneme", "v2"]
12
+ );
13
+ });
14
+
15
+ test("tokenize splits CJK runs into bigrams", () => {
16
+ assert.deepEqual(tokenize("异步编程"), ["异步", "步编", "编程"]);
17
+ assert.deepEqual(tokenize("图"), ["图"]);
18
+ });
19
+
20
+ // --- BM25 index ---
21
+
22
+ const DOCS = [
23
+ { id: "a", title: "异步并发模式", content: "async runtime 选用 tokio,任务 spawn 管理" },
24
+ { id: "b", title: "语言迁移", content: "编译模块从 Go 迁移到 Rust,内存安全" },
25
+ { id: "c", title: "无关条目", content: "夜间 ETL 用 Python 编写" }
26
+ ];
27
+
28
+ test("BM25 recalls rows whose query terms are scattered", () => {
29
+ // The LIKE path cannot match "rust 异步" as a substring of either doc;
30
+ // BM25 must surface both term-bearing rows above the unrelated one.
31
+ const idx = createBM25Index(DOCS);
32
+ const hits = idx.search("rust 异步", { limit: 3 });
33
+ const ids = hits.map((h) => h.id);
34
+ assert.ok(ids.includes("a"), "the async doc must be recalled");
35
+ assert.ok(ids.includes("b"), "the rust doc must be recalled");
36
+ assert.ok(!ids.includes("c"), "the unrelated doc must not lead");
37
+ assert.ok(ids.indexOf("c") === -1 || hits.find((h) => h.id === "c").score < hits[0].score);
38
+ });
39
+
40
+ test("BM25 search scores are normalized to [0,1] with the max on top", () => {
41
+ const idx = createBM25Index(DOCS);
42
+ const hits = idx.search("tokio spawn", { limit: 3 });
43
+ assert.ok(hits.length >= 1);
44
+ assert.equal(hits[0].id, "a");
45
+ for (const h of hits) {
46
+ assert.ok(h.score >= 0 && h.score <= 1, `score ${h.score} out of [0,1]`);
47
+ }
48
+ assert.equal(hits[0].score, 1);
49
+ });
50
+
51
+ test("BM25 score(query, doc) matches search on single-doc corpora", () => {
52
+ const idx = createBM25Index(DOCS);
53
+ const doc = DOCS[0];
54
+ assert.ok(idx.score("tokio", doc) > 0);
55
+ assert.equal(idx.score("完全不相关词汇xyzzy", doc), 0);
56
+ });
57
+
58
+ test("BM25 drops untouched rows entirely", () => {
59
+ const idx = createBM25Index(DOCS);
60
+ const hits = idx.search("ETL Python", { limit: 3 });
61
+ assert.deepEqual(hits.map((h) => h.id), ["c"]);
62
+ });
63
+
64
+ // --- adaptive threshold ---
65
+
66
+ test("adaptive threshold: entity/attr prefixes loosen to 0.5", () => {
67
+ assert.equal(adaptiveThreshold("entity:某个实体"), 0.5);
68
+ assert.equal(adaptiveThreshold("attr:lang=Rust"), 0.5);
69
+ });
70
+
71
+ test("adaptive threshold: short queries tighten, long queries loosen", () => {
72
+ assert.equal(adaptiveThreshold("go"), 0.7);
73
+ const long = "这是一个非常长的查询".repeat(8);
74
+ assert.equal(adaptiveThreshold(long), 0.6);
75
+ });
76
+
77
+ test("adaptive threshold: decisive head gap loosens to 0.5", () => {
78
+ const candidates = [
79
+ { _score: 0.9 }, { _score: 0.55 }, { _score: 0.54 }, { _score: 0.53 }, { _score: 0.52 }
80
+ ];
81
+ assert.equal(adaptiveThreshold("普通长度的查询词组", candidates), 0.5);
82
+ });
83
+
84
+ test("adaptive threshold: flat distribution keeps the 0.65 default", () => {
85
+ const candidates = [
86
+ { _score: 0.7 }, { _score: 0.68 }, { _score: 0.66 }, { _score: 0.64 }, { _score: 0.62 }
87
+ ];
88
+ assert.equal(adaptiveThreshold("普通长度的查询词组", candidates), 0.65);
89
+ assert.equal(adaptiveThreshold("普通长度的查询词组"), 0.65);
90
+ });
@@ -25,9 +25,13 @@ const reranker = {
25
25
 
26
26
  // Real store + service, wired with the mock embedder and a vector index over
27
27
  // the same store (the service's vector path prefers vectorIndex when set).
28
- function setup({ withEmbedder = true } = {}) {
28
+ // The v0.5.0 recall fusion extras (BM25 third path, search-time semantic
29
+ // dedup) are disabled per-test when the assertion targets the legacy blend
30
+ // mechanics — the toy embedder pins every vector hit to the same [1,0,0],
31
+ // which semantic dedup would legitimately collapse.
32
+ function setup({ withEmbedder = true, config = {} } = {}) {
29
33
  const store = createStore(":memory:");
30
- const service = createService({ store, mirror: null, config: {} });
34
+ const service = createService({ store, mirror: null, config });
31
35
  const vectorIndex = createVectorIndex({ store });
32
36
  if (withEmbedder) {
33
37
  service.setEmbedder(embedder);
@@ -81,6 +85,31 @@ test("hybrid blend honors configured vector/keyword weights", async () => {
81
85
  assert.ok(Math.abs(t.score - 0.9) < 1e-9, `tuned blend ${t.score}`);
82
86
  });
83
87
 
88
+ test("hybrid fusion clamps blended scores into [0,1]", async () => {
89
+ // Weights summing above 1 (1.0 + 1.0) push a same-memory blend over 1.0:
90
+ // title hit (importance 5) = 1 * (0.5 + 0.5) = 1.0, vector cosine = 1.0 →
91
+ // raw blend 1.0*1 + 1.0*1 = 2.0. The fused score must be clamped so
92
+ // consumers never see a score outside [0,1].
93
+ const store = createStore(":memory:");
94
+ const service = createService({ store, mirror: null, config: {
95
+ hybridSearchVectorWeight: 1,
96
+ hybridSearchKeywordWeight: 1,
97
+ adaptiveThresholdEnabled: false,
98
+ searchSemanticDedup: false
99
+ } });
100
+ const vi = createVectorIndex({ store });
101
+ service.setEmbedder(embedder);
102
+ service.setVectorIndex(vi);
103
+ const m = service.saveWithDedupe({ type: "preference", title: "量子计算", content: "量子计算入门", importance: 5 });
104
+ vi.saveEmbedding(m.memory.id, [1, 0, 0]);
105
+
106
+ const rows = await service.searchMemories("量子计算", { mode: "hybrid", topK: 10 });
107
+ const hit = rows.find((r) => r.id === m.memory.id);
108
+ assert.ok(hit, "blended row is recalled");
109
+ assert.equal(hit.score, 1, `over-weight blend clamped to 1 (got ${hit.score})`);
110
+ assert.ok(hit.score >= 0 && hit.score <= 1);
111
+ });
112
+
84
113
  test("auto = keyword leads, vector fills the remaining slots", async () => {
85
114
  const { service, vectorIndex } = setup();
86
115
  const kw = service.saveWithDedupe({ type: "preference", title: "量子计算", content: "量子计算入门" });