@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.
- package/README.md +37 -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 +52 -40
- 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 +52 -40
- 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,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,145 @@
|
|
|
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
|
+
// --- service-level: BM25 fusion + semantic dedup + selective injection ---
|
|
53
|
+
|
|
54
|
+
function toyVec(text) {
|
|
55
|
+
const v = new Array(64).fill(0);
|
|
56
|
+
for (const t of String(text).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean)) {
|
|
57
|
+
let h = 0;
|
|
58
|
+
for (const ch of t) h = (h * 31 + ch.codePointAt(0)) >>> 0;
|
|
59
|
+
v[h % 64] += 1;
|
|
60
|
+
}
|
|
61
|
+
const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
|
|
62
|
+
return v.map((x) => x / norm);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function setup(overrides = {}) {
|
|
66
|
+
const store = createStore(":memory:");
|
|
67
|
+
const config = {
|
|
68
|
+
entitySearchEnabled: false,
|
|
69
|
+
bm25SearchEnabled: true,
|
|
70
|
+
adaptiveThresholdEnabled: false,
|
|
71
|
+
searchSemanticDedup: true,
|
|
72
|
+
selectiveInjectEnabled: true,
|
|
73
|
+
...overrides
|
|
74
|
+
};
|
|
75
|
+
const service = createService({ store, mirror: null, config, logger: null });
|
|
76
|
+
service.setVectorIndex(createVectorIndex({ store, logger: null }));
|
|
77
|
+
service.setEmbedder({ embedSingle: async (t) => toyVec(t) });
|
|
78
|
+
return { store, service };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
test("searchMemories fuses BM25: scattered-term queries recall both rows", async () => {
|
|
82
|
+
const { store, service } = setup();
|
|
83
|
+
const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
|
|
84
|
+
const b = store.save({ type: "decision", title: "语言迁移", content: "编译模块迁移到 Rust", importance: 3 });
|
|
85
|
+
store.save({ type: "project", title: "无关", content: "夜间 ETL 脚本", importance: 3 });
|
|
86
|
+
|
|
87
|
+
// "rust 异步" is not a substring of either row — LIKE misses both; BM25
|
|
88
|
+
// must surface both rows in the merged result.
|
|
89
|
+
const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
|
|
90
|
+
const ids = results.map((r) => r.id);
|
|
91
|
+
assert.ok(ids.includes(a.id), "async row must be recalled via BM25");
|
|
92
|
+
assert.ok(ids.includes(b.id), "rust row must be recalled via BM25");
|
|
93
|
+
assert.equal(results.find((r) => r.id === a.id)?.source, "bm25");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("bm25SearchEnabled=false restores the two-path behavior", async () => {
|
|
97
|
+
const { store, service } = setup({ bm25SearchEnabled: false });
|
|
98
|
+
const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
|
|
99
|
+
const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
|
|
100
|
+
assert.ok(!results.some((r) => r.id === a.id), "no BM25 → scattered-term miss is back");
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("search-time semantic dedup drops near-identical embeddings", async () => {
|
|
104
|
+
const { store, service } = setup();
|
|
105
|
+
const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
|
|
106
|
+
const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
|
|
107
|
+
store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
|
|
108
|
+
store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
|
|
109
|
+
|
|
110
|
+
// auto (not keyword): keyword mode is the documented text-only path and is
|
|
111
|
+
// exempt from dedup by design; auto exercises the dedup the way production
|
|
112
|
+
// searches run.
|
|
113
|
+
const results = await service.searchMemories("深色主题", { mode: "auto", topK: 5 });
|
|
114
|
+
const ids = results.map((r) => r.id);
|
|
115
|
+
assert.ok(ids.includes(a.id) !== ids.includes(b.id), "one of the near-duplicate pair is dropped");
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("searchSemanticDedup=false keeps duplicate embeddings", async () => {
|
|
119
|
+
const { store, service } = setup({ searchSemanticDedup: false });
|
|
120
|
+
const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
|
|
121
|
+
const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
|
|
122
|
+
store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
|
|
123
|
+
store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
|
|
124
|
+
const results = await service.searchMemories("深色主题", { mode: "keyword", topK: 5 });
|
|
125
|
+
assert.equal(results.length, 2);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("selective injection re-orders candidates by query similarity", () => {
|
|
129
|
+
const { store, service } = setup();
|
|
130
|
+
const thesis = store.save({ type: "project", title: "湿地论文", content: "毕业论文研究城市湿地公园", importance: 5 });
|
|
131
|
+
const plugin = store.save({ type: "project", title: "插件项目", content: "dsh-mneme 记忆插件开发", importance: 5 });
|
|
132
|
+
store.setEmbedding(thesis.id, toyVec("毕业论文研究城市湿地公园"));
|
|
133
|
+
store.setEmbedding(plugin.id, toyVec("dsh-mneme 记忆插件开发"));
|
|
134
|
+
|
|
135
|
+
// Rule-based order would put both at equal importance; the query vector is
|
|
136
|
+
// about the thesis, so topic ranking must put the thesis memory first.
|
|
137
|
+
const picked = service.injectCandidates({
|
|
138
|
+
query: "论文写作",
|
|
139
|
+
queryVector: toyVec("毕业论文研究城市湿地公园"),
|
|
140
|
+
maxItems: 2,
|
|
141
|
+
threshold: 3
|
|
142
|
+
});
|
|
143
|
+
assert.equal(picked[0].id, thesis.id);
|
|
144
|
+
assert.ok(picked.some((m) => m.id === plugin.id));
|
|
145
|
+
});
|
|
@@ -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,
|
|
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);
|
|
@@ -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
|
-
|
|
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);
|