@modusensus/dsh-mneme 0.4.4 → 0.4.5
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 +3 -0
- package/lib/config.js +18 -0
- package/lib/dream/decisions.js +43 -2
- package/lib/inject.js +6 -1
- package/lib/service.js +141 -1
- package/lib/store.js +159 -5
- package/package.json +1 -1
- package/src/config.js +18 -0
- package/src/dream/decisions.js +43 -2
- package/src/inject.js +6 -1
- package/src/service.js +141 -1
- package/src/store.js +159 -5
- package/test/epistemic.test.js +298 -0
- package/test/recall-evals.test.js +235 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { createStore } from "../src/store.js";
|
|
8
|
+
import { createService } from "../src/service.js";
|
|
9
|
+
import { createVectorIndex } from "../src/vector-index.js";
|
|
10
|
+
import { createInjector } from "../src/inject.js";
|
|
11
|
+
import { createSettings } from "../src/settings.js";
|
|
12
|
+
import { applyDecisions } from "../src/dream.js";
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------- schema / legacy compat
|
|
15
|
+
|
|
16
|
+
test("default epistemic_status is subjective (legacy-compatible)", () => {
|
|
17
|
+
const store = createStore(":memory:");
|
|
18
|
+
const saved = store.save({ type: "preference", title: "语言", content: "用户用中文交流" });
|
|
19
|
+
assert.equal(saved.epistemic_status, "subjective", "no signal -> default subjective");
|
|
20
|
+
assert.equal(store.getById(saved.id).epistemic_status, "subjective");
|
|
21
|
+
store.close();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("legacy DB without the column is migrated, old rows read back as subjective", () => {
|
|
25
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-epistemic-"));
|
|
26
|
+
const dbPath = join(dir, "memory.db");
|
|
27
|
+
try {
|
|
28
|
+
const old = new DatabaseSync(dbPath);
|
|
29
|
+
old.exec(`
|
|
30
|
+
CREATE TABLE memories (
|
|
31
|
+
id TEXT PRIMARY KEY, type TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL,
|
|
32
|
+
tags TEXT NOT NULL DEFAULT '[]', importance INTEGER NOT NULL DEFAULT 3, forgotten INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
source TEXT, embedding TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
|
34
|
+
);
|
|
35
|
+
INSERT INTO memories (id, type, title, content, tags, importance, forgotten, created_at, updated_at)
|
|
36
|
+
VALUES ('legacy', 'preference', '旧偏好', '用户以前说过', '[]', 3, 0, 't', 't');
|
|
37
|
+
`);
|
|
38
|
+
old.close();
|
|
39
|
+
|
|
40
|
+
const store = createStore(dbPath);
|
|
41
|
+
const cols = store.db.prepare("PRAGMA table_info(memories)").all().map((c) => c.name);
|
|
42
|
+
assert.ok(cols.includes("epistemic_status"), "column added by migration");
|
|
43
|
+
const legacy = store.getById("legacy");
|
|
44
|
+
assert.equal(legacy.title, "旧偏好", "legacy row preserved");
|
|
45
|
+
assert.equal(legacy.epistemic_status, "subjective", "legacy row defaults to subjective");
|
|
46
|
+
// New writes on the migrated DB still work with the column.
|
|
47
|
+
const saved = store.save({ type: "preference", title: "新", content: "实测结果可用" });
|
|
48
|
+
assert.equal(saved.epistemic_status, "observation");
|
|
49
|
+
store.close();
|
|
50
|
+
} finally {
|
|
51
|
+
rmSync(dir, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------- write inference
|
|
56
|
+
|
|
57
|
+
test("content-based inference: subjective markers -> subjective", () => {
|
|
58
|
+
const store = createStore(":memory:");
|
|
59
|
+
const a = store.save({ type: "preference", title: "天气", content: "我推测明天可能会下雨" });
|
|
60
|
+
const b = store.save({ type: "preference", title: "口味", content: "我觉得用户喜欢甜的" });
|
|
61
|
+
assert.equal(a.epistemic_status, "subjective");
|
|
62
|
+
assert.equal(b.epistemic_status, "subjective");
|
|
63
|
+
store.close();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("content-based inference: observation markers -> observation", () => {
|
|
67
|
+
const store = createStore(":memory:");
|
|
68
|
+
const a = store.save({ type: "project", title: "温度", content: "实测温度为35度,数据显示稳定" });
|
|
69
|
+
const b = store.save({ type: "project", title: "观察", content: "观察到用户总是先点保存" });
|
|
70
|
+
assert.equal(a.epistemic_status, "observation");
|
|
71
|
+
assert.equal(b.epistemic_status, "observation");
|
|
72
|
+
store.close();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("content-based inference: inference markers -> inferred", () => {
|
|
76
|
+
const store = createStore(":memory:");
|
|
77
|
+
const a = store.save({ type: "decision", title: "喜好", content: "根据历史记录推断他喜欢猫" });
|
|
78
|
+
const b = store.save({ type: "decision", title: "趋势", content: "综上,结论是可推断的" });
|
|
79
|
+
assert.equal(a.epistemic_status, "inferred");
|
|
80
|
+
assert.equal(b.epistemic_status, "inferred");
|
|
81
|
+
store.close();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("AI-generated types (summary/pattern) are always inferred", () => {
|
|
85
|
+
const store = createStore(":memory:");
|
|
86
|
+
const s = store.save({ type: "summary", title: "总览", content: "实测数据汇总" });
|
|
87
|
+
const p = store.save({ type: "pattern", title: "模式", content: "用户反复这样操作" });
|
|
88
|
+
assert.equal(s.epistemic_status, "inferred");
|
|
89
|
+
assert.equal(p.epistemic_status, "inferred");
|
|
90
|
+
store.close();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("explicit epistemic_status wins over content inference", () => {
|
|
94
|
+
const store = createStore(":memory:");
|
|
95
|
+
const saved = store.save({ type: "preference", title: "x", content: "我觉得可能", epistemic_status: "observation" });
|
|
96
|
+
assert.equal(saved.epistemic_status, "observation", "explicit value respected");
|
|
97
|
+
store.close();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("update re-infers when content changes, keeps status otherwise", () => {
|
|
101
|
+
const store = createStore(":memory:");
|
|
102
|
+
const saved = store.save({ type: "preference", title: "x", content: "我觉得可能" });
|
|
103
|
+
assert.equal(saved.epistemic_status, "subjective");
|
|
104
|
+
// content unchanged -> status kept
|
|
105
|
+
const untouched = store.update(saved.id, { title: "y" });
|
|
106
|
+
assert.equal(untouched.epistemic_status, "subjective");
|
|
107
|
+
// content changed to observation -> status re-inferred
|
|
108
|
+
const reInferred = store.update(saved.id, { content: "实测结果显示没问题" });
|
|
109
|
+
assert.equal(reInferred.epistemic_status, "observation");
|
|
110
|
+
store.close();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("update re-infers when TYPE changes to summary/pattern (regression)", () => {
|
|
114
|
+
const store = createStore(":memory:");
|
|
115
|
+
const saved = store.save({ type: "project", title: "x", content: "我觉得可能" });
|
|
116
|
+
assert.equal(saved.epistemic_status, "subjective");
|
|
117
|
+
// type -> summary: summary/pattern are always inferred, so status must flip
|
|
118
|
+
const asSummary = store.update(saved.id, { type: "summary" });
|
|
119
|
+
assert.equal(asSummary.epistemic_status, "inferred");
|
|
120
|
+
store.close();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------- retrieval ranking
|
|
124
|
+
|
|
125
|
+
const embedder = {
|
|
126
|
+
embedSingle: async () => [1, 0, 0],
|
|
127
|
+
embed: async () => [1, 0, 0],
|
|
128
|
+
schedule: () => {},
|
|
129
|
+
modelHash: "mock#1",
|
|
130
|
+
dimension: 3
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
test("retrieval ranking: switch off leaves scores and order untouched", async () => {
|
|
134
|
+
const store = createStore(":memory:");
|
|
135
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
136
|
+
const a = service.saveWithDedupe({ type: "preference", title: "猫A", content: "我觉得猫很可爱", importance: 5 });
|
|
137
|
+
const b = service.saveWithDedupe({ type: "preference", title: "猫B", content: "实测猫很可爱", importance: 3 });
|
|
138
|
+
assert.equal(a.memory.epistemic_status, "subjective");
|
|
139
|
+
assert.equal(b.memory.epistemic_status, "observation");
|
|
140
|
+
|
|
141
|
+
const rows = await service.searchMemories("猫", { mode: "keyword", topK: 10 });
|
|
142
|
+
assert.equal(rows[0].id, a.memory.id, "subjective first under default importance order");
|
|
143
|
+
assert.equal(rows[0].score, 1.0, "subjective keeps its raw score (1.0) when off");
|
|
144
|
+
assert.equal(rows[1].score, 0.8, "observation keeps its raw score (0.8) when off");
|
|
145
|
+
store.close();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("retrieval ranking: switch on re-weights and re-orders mixed recall", async () => {
|
|
149
|
+
const store = createStore(":memory:");
|
|
150
|
+
const service = createService({ store, mirror: null, config: { trustEpistemicWeighting: true } });
|
|
151
|
+
const vi = createVectorIndex({ store });
|
|
152
|
+
service.setEmbedder(embedder);
|
|
153
|
+
service.setVectorIndex(vi);
|
|
154
|
+
const subj = service.saveWithDedupe({ type: "preference", title: "量子计算", content: "我觉得量子计算很难", importance: 5 });
|
|
155
|
+
const obs = service.saveWithDedupe({ type: "preference", title: "量子计算实践", content: "实测量子计算简单", importance: 3 });
|
|
156
|
+
vi.saveEmbedding(subj.memory.id, [1, 0, 0]);
|
|
157
|
+
vi.saveEmbedding(obs.memory.id, [1, 0, 0]);
|
|
158
|
+
assert.equal(subj.memory.epistemic_status, "subjective");
|
|
159
|
+
assert.equal(obs.memory.epistemic_status, "observation");
|
|
160
|
+
|
|
161
|
+
// hybrid blend (default 0.6/0.4): subjective 1.0*0.6+1.0*0.4=1.0;
|
|
162
|
+
// observation 1.0*0.6+0.8*0.4=0.92. After weighting: 1.0*0.7=0.7 vs 0.92*1.0=0.92.
|
|
163
|
+
const rows = await service.searchMemories("量子计算", { mode: "hybrid", topK: 10 });
|
|
164
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
165
|
+
assert.equal(byId.get(subj.memory.id).score, 0.7, "subjective weighted to 0.7");
|
|
166
|
+
assert.equal(byId.get(obs.memory.id).score, 0.92, "observation weighted to 0.92");
|
|
167
|
+
assert.equal(rows[0].id, obs.memory.id, "observation outranks subjective when weighting is on");
|
|
168
|
+
store.close();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// ---------------------------------------------------------------- injection marking
|
|
172
|
+
|
|
173
|
+
function setupInjector(over = {}) {
|
|
174
|
+
const store = createStore(":memory:");
|
|
175
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
176
|
+
const settings = createSettings(store.db);
|
|
177
|
+
const contexts = [];
|
|
178
|
+
const ctx = {
|
|
179
|
+
systemPrompt: {
|
|
180
|
+
context(def) {
|
|
181
|
+
contexts.push(def);
|
|
182
|
+
return () => {};
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const config = { maxInjectedItems: 3, importanceThreshold: 3, ...over };
|
|
187
|
+
createInjector(ctx, service, settings, config);
|
|
188
|
+
return { store, service, contexts };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
test("injection marks observation memories [verified] only when enabled", () => {
|
|
192
|
+
const { service, contexts } = setupInjector({ trustEpistemicWeighting: true });
|
|
193
|
+
service.saveWithDedupe({ type: "preference", title: "偏好实测", content: "实测用户喜欢用命令行", importance: 5 });
|
|
194
|
+
service.saveWithDedupe({ type: "preference", title: "偏好推测", content: "我觉得用户可能喜欢GUI", importance: 5 });
|
|
195
|
+
const text = contexts[0].text({});
|
|
196
|
+
assert.ok(text.includes("[verified] 偏好实测"), "observation memory is flagged");
|
|
197
|
+
assert.ok(!text.includes("[verified] 偏好推测"), "subjective memory is not flagged");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("injection never adds [verified] when the switch is off", () => {
|
|
201
|
+
const { service, contexts } = setupInjector({});
|
|
202
|
+
service.saveWithDedupe({ type: "preference", title: "偏好实测", content: "实测用户喜欢用命令行", importance: 5 });
|
|
203
|
+
const text = contexts[0].text({});
|
|
204
|
+
assert.ok(text.includes("偏好实测"), "memory still injected");
|
|
205
|
+
assert.ok(!text.includes("[verified]"), "no verified marker when off");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------- decision priority
|
|
209
|
+
|
|
210
|
+
test("merge keepSource prefers observation when enabled", () => {
|
|
211
|
+
const store = createStore(":memory:");
|
|
212
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
213
|
+
const config = { trustEpistemicWeighting: true };
|
|
214
|
+
const a = service.saveWithDedupe({ type: "project", title: "插件甲", content: "我觉得应该用A方案", importance: 3 });
|
|
215
|
+
const b = service.saveWithDedupe({ type: "project", title: "插件乙", content: "实测结果显示B方案更好", importance: 4 });
|
|
216
|
+
assert.equal(a.memory.epistemic_status, "subjective");
|
|
217
|
+
assert.equal(b.memory.epistemic_status, "observation");
|
|
218
|
+
|
|
219
|
+
const { committed } = applyDecisions(
|
|
220
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id], title: "插件总览", content: "合并", keepSource: a.memory.id }],
|
|
221
|
+
service, null, null, config
|
|
222
|
+
);
|
|
223
|
+
assert.equal(committed[0].keepSource, b.memory.id, "keepSource switched to the observation memory");
|
|
224
|
+
assert.equal(store.getById(b.memory.id).archived, false, "observation keeper stays live");
|
|
225
|
+
assert.equal(store.getById(a.memory.id).archived, true, "subjective source archived");
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("merge keepSource keeps the LLM choice when disabled", () => {
|
|
229
|
+
const store = createStore(":memory:");
|
|
230
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
231
|
+
const a = service.saveWithDedupe({ type: "project", title: "插件甲", content: "我觉得应该用A方案", importance: 3 });
|
|
232
|
+
const b = service.saveWithDedupe({ type: "project", title: "插件乙", content: "实测结果显示B方案更好", importance: 4 });
|
|
233
|
+
const { committed } = applyDecisions(
|
|
234
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id], title: "插件总览", content: "合并", keepSource: a.memory.id }],
|
|
235
|
+
service
|
|
236
|
+
);
|
|
237
|
+
assert.equal(committed[0].keepSource, a.memory.id, "LLM keepSource respected when off");
|
|
238
|
+
assert.equal(store.getById(a.memory.id).archived, false);
|
|
239
|
+
assert.equal(store.getById(b.memory.id).archived, true);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("merge never promotes an ARCHIVED observation to keeper when enabled (regression)", () => {
|
|
243
|
+
const store = createStore(":memory:");
|
|
244
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
245
|
+
const config = { trustEpistemicWeighting: true };
|
|
246
|
+
// a = live subjective (LLM's keepSource), b = live observation,
|
|
247
|
+
// c = ARCHIVED observation. Pre-fix pickBestKeeper would pick c (highest
|
|
248
|
+
// priority, no archived check) as keeper, hit the archived-keeper guard in
|
|
249
|
+
// applyMerge and silently drop the merge — the live b never merges.
|
|
250
|
+
const a = service.saveWithDedupe({ type: "project", title: "甲", content: "我觉得A方案", importance: 3 });
|
|
251
|
+
const b = service.saveWithDedupe({ type: "project", title: "乙", content: "实测B方案更好", importance: 4 });
|
|
252
|
+
const c = service.saveWithDedupe({ type: "project", title: "丙", content: "实测C方案最好", importance: 4 });
|
|
253
|
+
service.setArchived(c.memory.id, true);
|
|
254
|
+
|
|
255
|
+
const { committed } = applyDecisions(
|
|
256
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id, c.memory.id], title: "合并", content: "合并", keepSource: a.memory.id }],
|
|
257
|
+
service, null, null, config
|
|
258
|
+
);
|
|
259
|
+
// c (archived) must NOT be promoted; the live observation b becomes keeper,
|
|
260
|
+
// and the merge actually lands.
|
|
261
|
+
assert.equal(committed.length, 1, "merge actually committed (not silently skipped)");
|
|
262
|
+
assert.equal(committed[0].keepSource, b.memory.id, "live observation promoted over archived one");
|
|
263
|
+
assert.equal(store.getById(b.memory.id).archived, false, "observation keeper stays live");
|
|
264
|
+
assert.equal(store.getById(a.memory.id).archived, true, "subjective source archived");
|
|
265
|
+
assert.equal(store.getById(c.memory.id).archived, true, "archived c stays archived");
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
test("conflict resolution prefers the observation side as winner when enabled", () => {
|
|
269
|
+
const store = createStore(":memory:");
|
|
270
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
271
|
+
const config = { trustEpistemicWeighting: true };
|
|
272
|
+
const w = service.saveWithDedupe({ type: "decision", title: "截止1", content: "我觉得截止是8月20日", importance: 4 });
|
|
273
|
+
const l = service.saveWithDedupe({ type: "decision", title: "截止2", content: "实测截止是8月15日", importance: 4 });
|
|
274
|
+
assert.equal(w.memory.epistemic_status, "subjective");
|
|
275
|
+
assert.equal(l.memory.epistemic_status, "observation");
|
|
276
|
+
|
|
277
|
+
const { committed } = applyDecisions(
|
|
278
|
+
[{ action: "conflict", winner: w.memory.id, loser: l.memory.id, reason: "日期更新" }],
|
|
279
|
+
service, null, null, config
|
|
280
|
+
);
|
|
281
|
+
assert.equal(committed[0].winner, l.memory.id, "winner swapped to the observation memory");
|
|
282
|
+
assert.equal(store.getById(l.memory.id).archived, false, "observation winner stays live");
|
|
283
|
+
assert.equal(store.getById(w.memory.id).archived, true, "subjective loser archived");
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("conflict resolution keeps the LLM winner when disabled", () => {
|
|
287
|
+
const store = createStore(":memory:");
|
|
288
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
289
|
+
const w = service.saveWithDedupe({ type: "decision", title: "截止1", content: "我觉得截止是8月20日", importance: 4 });
|
|
290
|
+
const l = service.saveWithDedupe({ type: "decision", title: "截止2", content: "实测截止是8月15日", importance: 4 });
|
|
291
|
+
const { committed } = applyDecisions(
|
|
292
|
+
[{ action: "conflict", winner: w.memory.id, loser: l.memory.id, reason: "日期更新" }],
|
|
293
|
+
service
|
|
294
|
+
);
|
|
295
|
+
assert.equal(committed[0].winner, w.memory.id, "LLM winner respected when off");
|
|
296
|
+
assert.equal(store.getById(w.memory.id).archived, false);
|
|
297
|
+
assert.equal(store.getById(l.memory.id).archived, true);
|
|
298
|
+
});
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { createStore } from "../src/store.js";
|
|
8
|
+
import { createService } from "../src/service.js";
|
|
9
|
+
import { Config } from "../src/config.js";
|
|
10
|
+
|
|
11
|
+
// Mock embedder: every query maps to the fixed vector [1,0,0], so vector recall
|
|
12
|
+
// surfaces any row embedded at [1,0,0] and excludes orthogonal ones.
|
|
13
|
+
const embedder = {
|
|
14
|
+
embedSingle: async () => [1, 0, 0],
|
|
15
|
+
embed: async () => [1, 0, 0],
|
|
16
|
+
schedule: () => {},
|
|
17
|
+
modelHash: "eval#mock",
|
|
18
|
+
dimension: 3
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function setup(config = {}) {
|
|
22
|
+
const store = createStore(":memory:");
|
|
23
|
+
const service = createService({ store, mirror: null, config });
|
|
24
|
+
return { store, service };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function saveMemory(service, title, content) {
|
|
28
|
+
return service.saveWithDedupe({ type: "preference", title, content, importance: 5 }).memory;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------- schema / config
|
|
32
|
+
|
|
33
|
+
test("config: evalPersistTestResults defaults to false (opt-in)", () => {
|
|
34
|
+
assert.equal(Config({}).evalPersistTestResults, false, "off by default");
|
|
35
|
+
assert.equal(Config({ evalPersistTestResults: true }).evalPersistTestResults, true, "explicit opt-in");
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("schema: recall_evals table exists with the expected columns", () => {
|
|
39
|
+
const store = createStore(":memory:");
|
|
40
|
+
const cols = store.db.prepare("PRAGMA table_info(recall_evals)").all().map((c) => c.name);
|
|
41
|
+
for (const col of ["id", "recall_run_id", "query", "expected_ids", "actual_ids", "metrics", "eval_type", "created_at"]) {
|
|
42
|
+
assert.ok(cols.includes(col), `column ${col} present`);
|
|
43
|
+
}
|
|
44
|
+
// FK clause is declared against recall_runs.
|
|
45
|
+
const fks = store.db.prepare("PRAGMA foreign_key_list(recall_evals)").all();
|
|
46
|
+
assert.ok(fks.some((fk) => fk.table === "recall_runs" && fk.from === "recall_run_id"), "FK to recall_runs(id) declared");
|
|
47
|
+
store.close();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("legacy DB without recall_evals is upgraded idempotently on open", () => {
|
|
51
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-recall-evals-"));
|
|
52
|
+
const dbPath = join(dir, "memory.db");
|
|
53
|
+
try {
|
|
54
|
+
const old = new DatabaseSync(dbPath);
|
|
55
|
+
old.exec(`
|
|
56
|
+
CREATE TABLE recall_runs (
|
|
57
|
+
id TEXT PRIMARY KEY, query TEXT NOT NULL, mode TEXT NOT NULL,
|
|
58
|
+
top_k INTEGER, threshold REAL, candidates TEXT NOT NULL, created_at TEXT NOT NULL
|
|
59
|
+
);
|
|
60
|
+
INSERT INTO recall_runs (id, query, mode, candidates, created_at) VALUES ('r1', '旧', 'keyword', '[]', 't');
|
|
61
|
+
`);
|
|
62
|
+
old.close();
|
|
63
|
+
const store = createStore(dbPath);
|
|
64
|
+
const cols = store.db.prepare("PRAGMA table_info(recall_evals)").all().map((c) => c.name);
|
|
65
|
+
assert.ok(cols.includes("id"), "recall_evals created on a legacy DB");
|
|
66
|
+
assert.equal(store.getRecallRun("r1").query, "旧", "legacy recall_runs row preserved");
|
|
67
|
+
store.close();
|
|
68
|
+
} finally {
|
|
69
|
+
rmSync(dir, { recursive: true, force: true });
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------- switch-off / switch-on
|
|
74
|
+
|
|
75
|
+
test("switch off: evaluateRetrieval computes metrics but writes nothing", async () => {
|
|
76
|
+
const { store, service } = setup({}); // evalPersistTestResults defaults false
|
|
77
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
78
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword", topK: 10 });
|
|
79
|
+
assert.ok(res.metrics.precision >= 0 && res.metrics.precision <= 1, "metrics computed");
|
|
80
|
+
assert.deepEqual(res.actualIds, [m.id], "retrieval ran and returned the memory");
|
|
81
|
+
assert.equal(res.persisted, false, "no persistence when switch is off");
|
|
82
|
+
assert.deepEqual(store.listRecallEvals(), [], "recall_evals stays empty");
|
|
83
|
+
store.close();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("switch on: evaluateRetrieval persists a recall_evals snapshot", async () => {
|
|
87
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
88
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
89
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword", topK: 10, evalType: "regression" });
|
|
90
|
+
assert.equal(res.persisted, true, "snapshot persisted");
|
|
91
|
+
const evals = store.listRecallEvals();
|
|
92
|
+
assert.equal(evals.length, 1, "one eval row");
|
|
93
|
+
const row = evals[0];
|
|
94
|
+
assert.equal(row.query, "量子");
|
|
95
|
+
assert.deepEqual(row.expected_ids, [m.id], "expected ids round-trip");
|
|
96
|
+
assert.deepEqual(row.actual_ids, [m.id], "actual ids round-trip");
|
|
97
|
+
assert.equal(row.eval_type, "regression");
|
|
98
|
+
assert.ok(row.metrics && typeof row.metrics.precision === "number", "metrics JSON round-trips");
|
|
99
|
+
assert.ok(typeof row.created_at === "string" && row.created_at.length > 0, "timestamp captured");
|
|
100
|
+
// Idempotent on id: the same logical eval id replays without duplicates.
|
|
101
|
+
store.saveRecallEval({ id: "ev-x", query: "q", expected_ids: [], actual_ids: [], metrics: {}, eval_type: "manual" });
|
|
102
|
+
store.saveRecallEval({ id: "ev-x", query: "q2", expected_ids: [], actual_ids: [], metrics: {}, eval_type: "manual" });
|
|
103
|
+
assert.equal(store.listRecallEvals().filter((e) => e.id === "ev-x").length, 1, "replay overwrites, no duplicate");
|
|
104
|
+
store.close();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("persist override: call-level persist:true writes even with the switch off", async () => {
|
|
108
|
+
const { store, service } = setup({}); // switch off
|
|
109
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
110
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword", persist: true });
|
|
111
|
+
assert.equal(res.persisted, true, "explicit persist override honored");
|
|
112
|
+
assert.equal(store.listRecallEvals().length, 1);
|
|
113
|
+
store.close();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("persist override: call-level persist:false suppresses even with the switch on", async () => {
|
|
117
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
118
|
+
saveMemory(service, "量子计算入门", "叠加态");
|
|
119
|
+
const res = await service.evaluateRetrieval("量子", [], { mode: "keyword", persist: false });
|
|
120
|
+
assert.equal(res.persisted, false, "explicit opt-out honored");
|
|
121
|
+
assert.deepEqual(store.listRecallEvals(), [], "nothing written");
|
|
122
|
+
store.close();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// ---------------------------------------------------------------- metrics correctness
|
|
126
|
+
|
|
127
|
+
test("metrics: computeRetrievalMetrics is exact for known inputs", () => {
|
|
128
|
+
const { service } = setup();
|
|
129
|
+
// a,b,c retrieved; a,x expected → 1 relevant at rank 1.
|
|
130
|
+
assert.deepEqual(
|
|
131
|
+
service.computeRetrievalMetrics(["a", "b", "c"], ["a", "x"]),
|
|
132
|
+
{ precision: 0.3333, recall: 0.5, mrr: 1, hit_count: 1 }
|
|
133
|
+
);
|
|
134
|
+
// relevant at rank 3 → mrr 1/3.
|
|
135
|
+
assert.deepEqual(
|
|
136
|
+
service.computeRetrievalMetrics(["x", "y", "a"], ["a", "b"]),
|
|
137
|
+
{ precision: 0.3333, recall: 0.5, mrr: 0.3333, hit_count: 1 }
|
|
138
|
+
);
|
|
139
|
+
// empty retrieval → zero metrics, no divide-by-zero.
|
|
140
|
+
assert.deepEqual(
|
|
141
|
+
service.computeRetrievalMetrics([], ["a", "b"]),
|
|
142
|
+
{ precision: 0, recall: 0, mrr: 0, hit_count: 0 }
|
|
143
|
+
);
|
|
144
|
+
// everything relevant, nothing missed → perfect scores.
|
|
145
|
+
assert.deepEqual(
|
|
146
|
+
service.computeRetrievalMetrics(["a", "b"], ["a", "b"]),
|
|
147
|
+
{ precision: 1, recall: 1, mrr: 1, hit_count: 2 }
|
|
148
|
+
);
|
|
149
|
+
// extra noise harms precision but not recall.
|
|
150
|
+
assert.deepEqual(
|
|
151
|
+
service.computeRetrievalMetrics(["a", "b", "c", "d"], ["a"]),
|
|
152
|
+
{ precision: 0.25, recall: 1, mrr: 1, hit_count: 1 }
|
|
153
|
+
);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("metrics: integration — partial hit scores precision/recall/mrr from real recall", async () => {
|
|
157
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
158
|
+
const hit = saveMemory(service, "量子计算入门", "叠加态");
|
|
159
|
+
saveMemory(service, "量子纠缠", "贝尔态");
|
|
160
|
+
saveMemory(service, "猫咪饲养", "喂食");
|
|
161
|
+
const res = await service.evaluateRetrieval("量子", [hit.id], { mode: "keyword", topK: 10 });
|
|
162
|
+
// Two literal 量子 hits retrieved, one relevant → precision 1/2, recall 1/1.
|
|
163
|
+
// Title-tied, equal-importance rows order by updated_at DESC, so the later
|
|
164
|
+
// saved 量子纠缠 ranks first and the relevant row is at rank 2 → mrr 1/2.
|
|
165
|
+
assert.equal(res.metrics.hit_count, 1);
|
|
166
|
+
assert.equal(res.metrics.precision, 0.5);
|
|
167
|
+
assert.equal(res.metrics.recall, 1);
|
|
168
|
+
assert.equal(res.metrics.mrr, 0.5);
|
|
169
|
+
const row = store.listRecallEvals()[0];
|
|
170
|
+
assert.equal(row.metrics.precision, 0.5, "persisted metrics match");
|
|
171
|
+
store.close();
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------- FK linkage
|
|
175
|
+
|
|
176
|
+
test("FK: recordRecall=true links the eval to the recall_runs audit row", async () => {
|
|
177
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
178
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
179
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword", topK: 5, recordRecall: true });
|
|
180
|
+
assert.ok(res.recallRunId, "a recall run was recorded for the same scene");
|
|
181
|
+
assert.equal(store.listRecallRuns().length, 1, "exactly one recall_runs row");
|
|
182
|
+
const run = store.getRecallRun(res.recallRunId);
|
|
183
|
+
assert.equal(run.query, "量子");
|
|
184
|
+
const evals = store.listRecallEvals();
|
|
185
|
+
assert.equal(evals.length, 1);
|
|
186
|
+
assert.equal(evals[0].recall_run_id, res.recallRunId, "eval links to the recorded run");
|
|
187
|
+
store.close();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test("FK: explicit recallRunId is preserved — recordRecall never clobbers it (regression)", async () => {
|
|
191
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
192
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
193
|
+
// Pre-existing audit run the evaluator wants to link against.
|
|
194
|
+
const run = store.saveRecallRun({
|
|
195
|
+
query: "量子", mode: "keyword", topK: 5, candidates: [], created_at: new Date().toISOString()
|
|
196
|
+
});
|
|
197
|
+
// recordRecall=true alongside an explicit recallRunId: the explicit link wins,
|
|
198
|
+
// and NO extra recall_runs row is minted.
|
|
199
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword", recordRecall: true, recallRunId: run.id });
|
|
200
|
+
assert.equal(res.recallRunId, run.id, "explicit recallRunId preserved");
|
|
201
|
+
assert.equal(store.listRecallRuns().length, 1, "no duplicate recall_runs row minted");
|
|
202
|
+
const evals = store.listRecallEvals();
|
|
203
|
+
assert.equal(evals[0].recall_run_id, run.id, "eval links to the pre-existing run");
|
|
204
|
+
store.close();
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test("FK: recordRecall=false leaves recall_run_id null and writes no recall_runs row", async () => {
|
|
208
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
209
|
+
const m = saveMemory(service, "量子计算入门", "叠加态");
|
|
210
|
+
const res = await service.evaluateRetrieval("量子", [m.id], { mode: "keyword" });
|
|
211
|
+
assert.equal(res.recallRunId, null, "no run recorded by default");
|
|
212
|
+
assert.deepEqual(store.listRecallRuns(), [], "recall_runs untouched by evals");
|
|
213
|
+
const row = store.listRecallEvals()[0];
|
|
214
|
+
assert.ok(!row.recall_run_id, "eval row has no recall_run_id");
|
|
215
|
+
store.close();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// ---------------------------------------------------------------- production isolation
|
|
219
|
+
|
|
220
|
+
test("production search never writes recall_evals, even with the switch on", async () => {
|
|
221
|
+
const { store, service } = setup({ evalPersistTestResults: true });
|
|
222
|
+
// Mimic src/index.js wiring: the recall recorder persists to recall_runs.
|
|
223
|
+
service.setRecallRecorder((recall) => {
|
|
224
|
+
store.saveRecallRun({
|
|
225
|
+
query: recall.query, mode: recall.mode, topK: recall.topK, threshold: recall.threshold ?? null,
|
|
226
|
+
candidates: recall.candidates ?? [], created_at: recall.createdAt
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
saveMemory(service, "量子计算入门", "叠加态");
|
|
230
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
231
|
+
assert.ok(rows.length >= 1, "search returned results");
|
|
232
|
+
assert.equal(store.listRecallRuns().length, 1, "production audit lands in recall_runs");
|
|
233
|
+
assert.deepEqual(store.listRecallEvals(), [], "recall_evals stays untouched by production search");
|
|
234
|
+
store.close();
|
|
235
|
+
});
|