@modusensus/dsh-mneme 0.4.4 → 0.4.6
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 +27 -0
- package/lib/api.js +40 -2
- package/lib/config.js +53 -0
- package/lib/dream/decisions.js +43 -2
- package/lib/dream.js +86 -6
- package/lib/embedding.js +59 -2
- package/lib/index.js +68 -1
- package/lib/inject.js +84 -4
- package/lib/quality-filter.js +123 -0
- package/lib/service.js +355 -14
- package/lib/store.js +366 -5
- package/lib/summarize.js +65 -7
- package/lib/vector-index.js +12 -2
- package/package.json +1 -1
- package/src/api.js +40 -2
- package/src/config.js +53 -0
- package/src/dream/decisions.js +43 -2
- package/src/dream.js +86 -6
- package/src/embedding.js +59 -2
- package/src/index.js +68 -1
- package/src/inject.js +84 -4
- package/src/quality-filter.js +123 -0
- package/src/service.js +355 -14
- package/src/store.js +366 -5
- package/src/summarize.js +65 -7
- package/src/vector-index.js +12 -2
- package/test/api.test.js +84 -0
- package/test/dream.test.js +52 -0
- package/test/epistemic.test.js +298 -0
- package/test/inject.test.js +21 -0
- package/test/llm-audit.test.js +279 -0
- package/test/mirror-edit-digest.test.js +3 -1
- package/test/quality-filter.test.js +118 -0
- package/test/recall-evals.test.js +235 -0
- package/test/service.test.js +133 -2
- package/test/vector-index.test.js +22 -6
|
@@ -0,0 +1,279 @@
|
|
|
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 { createDreamScheduler } from "../src/dream.js";
|
|
7
|
+
import { createSummarizer } from "../src/summarize.js";
|
|
8
|
+
import { createApi } from "../src/api.js";
|
|
9
|
+
import { createSettings } from "../src/settings.js";
|
|
10
|
+
import { mockCtx } from "./helpers/dream-mock.js";
|
|
11
|
+
|
|
12
|
+
// Bug8: LLM audit trail. Every background LLM call (autoDream consolidation +
|
|
13
|
+
// summary, autoSummarize compression) records tokens/time/status into
|
|
14
|
+
// llm_audit_logs. Failures are captured as status='error' and never block the
|
|
15
|
+
// calling feature. Read back through the API (/llm-audit + /llm-audit/stats).
|
|
16
|
+
// Gating: runDream treats llmAudit.enabled === false as off; summarize treats
|
|
17
|
+
// llmAudit.enabled !== false as on.
|
|
18
|
+
|
|
19
|
+
function dreamSetup(over = {}) {
|
|
20
|
+
const store = createStore(":memory:");
|
|
21
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
22
|
+
return {
|
|
23
|
+
store,
|
|
24
|
+
service,
|
|
25
|
+
config: { dreamProvider: "deepseek", dreamModel: "deepseek-chat", llmAudit: { enabled: true }, ...over }
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
test("autoDream writes llm_audit_logs rows for consolidation and summary", async () => {
|
|
30
|
+
const { store, service, config } = dreamSetup();
|
|
31
|
+
service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
|
|
32
|
+
service.saveWithDedupe({ type: "project", title: "旧2", content: "第二段内容" });
|
|
33
|
+
const ctx = mockCtx({
|
|
34
|
+
onConsolidation: (listText) => {
|
|
35
|
+
const ids = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=\w+\s*\|\s*importance=\d+/g)].map((m) => m[1]);
|
|
36
|
+
return JSON.stringify(ids.map((id) => ({ action: "keep", ids: [id] })));
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
40
|
+
const result = await dream.runDream(ctx, service, config);
|
|
41
|
+
assert.equal(result.ok, true);
|
|
42
|
+
|
|
43
|
+
const rows = service.listLlmAudits();
|
|
44
|
+
assert.equal(rows.length, 2, "one consolidation + one summary audit row");
|
|
45
|
+
const consolidate = rows.find((r) => r.operation_type === "dream_consolidate");
|
|
46
|
+
const summarize = rows.find((r) => r.operation_type === "dream_summarize");
|
|
47
|
+
assert.ok(consolidate, "dream_consolidate row present");
|
|
48
|
+
assert.ok(summarize, "dream_summarize row present");
|
|
49
|
+
assert.equal(consolidate.trigger_source, "autoDream");
|
|
50
|
+
assert.equal(summarize.trigger_source, "autoDream");
|
|
51
|
+
assert.equal(consolidate.status, "success");
|
|
52
|
+
assert.equal(summarize.status, "success");
|
|
53
|
+
// mockCtx resolves the route from agentDefaultModel (mock:stress-model), not
|
|
54
|
+
// the config fallback — assert the actually-used route.
|
|
55
|
+
assert.equal(consolidate.model_id, "mock:stress-model");
|
|
56
|
+
assert.equal(summarize.model_id, "mock:stress-model");
|
|
57
|
+
assert.ok(Array.isArray(consolidate.related_memory_ids) && consolidate.related_memory_ids.length === 2,
|
|
58
|
+
"consolidation audit records the snapshot ids");
|
|
59
|
+
assert.ok(consolidate.total_tokens >= 0 && summarize.total_tokens >= 0);
|
|
60
|
+
assert.ok(typeof consolidate.duration_ms === "number" && consolidate.duration_ms >= 0);
|
|
61
|
+
store.close();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("autoDream LLM failure is audited as status=error and never blocks the run", async () => {
|
|
65
|
+
const { store, service, config } = dreamSetup();
|
|
66
|
+
service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
|
|
67
|
+
// Consolidation stream finishes with kind "error" → streamText returns
|
|
68
|
+
// undefined → the run fails safe; runAuditedLlm must still leave an
|
|
69
|
+
// error audit row before the failure propagates.
|
|
70
|
+
const ctx = {
|
|
71
|
+
logger: { warn: () => {} },
|
|
72
|
+
llm: {
|
|
73
|
+
async *stream() {
|
|
74
|
+
yield { type: "text-delta", index: 0, text: "" };
|
|
75
|
+
yield { type: "finish", reason: { kind: "error" } };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
80
|
+
const result = await dream.runDream(ctx, service, config);
|
|
81
|
+
assert.equal(result.ok, false, "aborted/errored stream fails the run");
|
|
82
|
+
const rows = service.listLlmAudits();
|
|
83
|
+
assert.equal(rows.length, 1, "failed consolidation still audited");
|
|
84
|
+
assert.equal(rows[0].operation_type, "dream_consolidate");
|
|
85
|
+
assert.equal(rows[0].status, "error");
|
|
86
|
+
assert.ok(rows[0].error_message, "error message recorded");
|
|
87
|
+
// the audit write did not block the failure path
|
|
88
|
+
assert.equal(result.error, "llm failed");
|
|
89
|
+
store.close();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("autoDream throwing LLM is audited as status=error", async () => {
|
|
93
|
+
const { store, service, config } = dreamSetup();
|
|
94
|
+
service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
|
|
95
|
+
const ctx = {
|
|
96
|
+
logger: { warn: () => {} },
|
|
97
|
+
llm: {
|
|
98
|
+
async *stream() {
|
|
99
|
+
throw new Error("network down");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
104
|
+
const result = await dream.runDream(ctx, service, config);
|
|
105
|
+
assert.equal(result.ok, false);
|
|
106
|
+
const rows = service.listLlmAudits();
|
|
107
|
+
assert.equal(rows.length, 1, "throwing call still audited");
|
|
108
|
+
assert.equal(rows[0].status, "error");
|
|
109
|
+
assert.match(rows[0].error_message, /network down/);
|
|
110
|
+
store.close();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("autoDream audit is skipped when llmAudit.enabled === false", async () => {
|
|
114
|
+
const { store, service, config } = dreamSetup({ llmAudit: { enabled: false } });
|
|
115
|
+
service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
|
|
116
|
+
const ctx = mockCtx();
|
|
117
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
118
|
+
await dream.runDream(ctx, service, config);
|
|
119
|
+
assert.equal(service.listLlmAudits().length, 0, "no audit rows when disabled");
|
|
120
|
+
store.close();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("autoSummarize writes an llm_audit_logs row (trigger_source autoSummarize)", async () => {
|
|
124
|
+
const store = createStore(":memory:");
|
|
125
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
126
|
+
const events = [];
|
|
127
|
+
const ctx = {
|
|
128
|
+
on(name, fn) {
|
|
129
|
+
events.push({ name, fn });
|
|
130
|
+
return () => {};
|
|
131
|
+
},
|
|
132
|
+
logger: { warn: () => {} },
|
|
133
|
+
llm: {
|
|
134
|
+
async *stream() {
|
|
135
|
+
yield { type: "text-delta", index: 0, text: JSON.stringify([
|
|
136
|
+
{ type: "decision", title: "选型", content: "确定用 node:sqlite", importance: 4 }
|
|
137
|
+
]) };
|
|
138
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const config = {
|
|
143
|
+
autoSummarize: true,
|
|
144
|
+
summarizeProvider: "deepseek",
|
|
145
|
+
summarizeModel: "deepseek-chat",
|
|
146
|
+
llmAudit: { enabled: true }
|
|
147
|
+
};
|
|
148
|
+
createSummarizer(ctx, service, config);
|
|
149
|
+
const handler = events.find((e) => e.name === "session/event").fn;
|
|
150
|
+
const session = {
|
|
151
|
+
id: "s1",
|
|
152
|
+
requestHeader: () => ({ config: {} }),
|
|
153
|
+
events: [
|
|
154
|
+
{ type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "帮我选型" }] } },
|
|
155
|
+
{ seq: 2, type: "turn/end" }
|
|
156
|
+
]
|
|
157
|
+
};
|
|
158
|
+
await handler(session, { seq: 2, type: "turn/end" });
|
|
159
|
+
const rows = service.listLlmAudits();
|
|
160
|
+
assert.equal(rows.length, 1, "one autoSummarize audit row");
|
|
161
|
+
assert.equal(rows[0].trigger_source, "autoSummarize");
|
|
162
|
+
assert.equal(rows[0].operation_type, "summarize_compress");
|
|
163
|
+
assert.equal(rows[0].model_id, "deepseek:deepseek-chat");
|
|
164
|
+
assert.equal(rows[0].status, "success");
|
|
165
|
+
store.close();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// --- API surface ------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
class FakeRes extends EventEmitter {
|
|
171
|
+
constructor() { super(); this.statusCode = 200; this.body = ""; }
|
|
172
|
+
writeHead(code, headers) { this.statusCode = code; this.headers = headers; return this; }
|
|
173
|
+
end(text) { this.body = text ?? ""; this.emit("end"); return this; }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function req(path) {
|
|
177
|
+
const r = new EventEmitter();
|
|
178
|
+
r.url = path;
|
|
179
|
+
r.method = "GET";
|
|
180
|
+
r.headers = {};
|
|
181
|
+
return r;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function apiSetup() {
|
|
185
|
+
const store = createStore(":memory:");
|
|
186
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
187
|
+
const settings = createSettings(store.db);
|
|
188
|
+
const routes = [];
|
|
189
|
+
const ctx = {
|
|
190
|
+
webServer: {
|
|
191
|
+
register(route) {
|
|
192
|
+
routes.push(route);
|
|
193
|
+
return () => {};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
createApi(ctx, service, settings, { add: () => {}, remove: () => false, list: () => [] });
|
|
198
|
+
return { store, service, routes };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
test("GET /api/dsh-mneme/semantic/llm-audit paginates and filters by source", async () => {
|
|
202
|
+
const { store, service, routes } = apiSetup();
|
|
203
|
+
for (let i = 0; i < 3; i++) {
|
|
204
|
+
service.saveLlmAudit({
|
|
205
|
+
trigger_source: "autoDream",
|
|
206
|
+
operation_type: "dream_consolidate",
|
|
207
|
+
model_id: "deepseek:deepseek-chat",
|
|
208
|
+
input_tokens: 10, output_tokens: 5, status: "success"
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
service.saveLlmAudit({
|
|
212
|
+
trigger_source: "autoSummarize",
|
|
213
|
+
operation_type: "summarize_compress",
|
|
214
|
+
model_id: "deepseek:deepseek-chat",
|
|
215
|
+
input_tokens: 3, output_tokens: 1, status: "success"
|
|
216
|
+
});
|
|
217
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit");
|
|
218
|
+
|
|
219
|
+
// full page
|
|
220
|
+
let res = new FakeRes();
|
|
221
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=1&pageSize=2"), res);
|
|
222
|
+
let data = JSON.parse(res.body);
|
|
223
|
+
assert.equal(res.statusCode, 200);
|
|
224
|
+
assert.equal(data.total, 4);
|
|
225
|
+
assert.equal(data.page, 1);
|
|
226
|
+
assert.equal(data.pageSize, 2);
|
|
227
|
+
assert.equal(data.items.length, 2);
|
|
228
|
+
|
|
229
|
+
// second page
|
|
230
|
+
res = new FakeRes();
|
|
231
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=2&pageSize=2"), res);
|
|
232
|
+
data = JSON.parse(res.body);
|
|
233
|
+
assert.equal(data.items.length, 2, "page 2 has the remaining rows");
|
|
234
|
+
assert.equal(data.total, 4);
|
|
235
|
+
|
|
236
|
+
// source filter
|
|
237
|
+
res = new FakeRes();
|
|
238
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit?source=autoSummarize"), res);
|
|
239
|
+
data = JSON.parse(res.body);
|
|
240
|
+
assert.equal(data.total, 1);
|
|
241
|
+
assert.equal(data.items[0].trigger_source, "autoSummarize");
|
|
242
|
+
store.close();
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
test("GET /api/dsh-mneme/semantic/llm-audit/stats aggregates by source and status", async () => {
|
|
246
|
+
const { store, service, routes } = apiSetup();
|
|
247
|
+
service.saveLlmAudit({
|
|
248
|
+
timestamp: new Date().toISOString(),
|
|
249
|
+
trigger_source: "autoDream", operation_type: "dream_consolidate",
|
|
250
|
+
model_id: "m", input_tokens: 100, output_tokens: 40, duration_ms: 25, status: "success"
|
|
251
|
+
});
|
|
252
|
+
service.saveLlmAudit({
|
|
253
|
+
timestamp: new Date().toISOString(),
|
|
254
|
+
trigger_source: "autoDream", operation_type: "dream_summarize",
|
|
255
|
+
model_id: "m", input_tokens: 30, output_tokens: 10, duration_ms: 8, status: "success"
|
|
256
|
+
});
|
|
257
|
+
service.saveLlmAudit({
|
|
258
|
+
timestamp: new Date().toISOString(),
|
|
259
|
+
trigger_source: "autoSummarize", operation_type: "summarize_compress",
|
|
260
|
+
model_id: "m", input_tokens: 5, output_tokens: 2, duration_ms: 4, status: "error"
|
|
261
|
+
});
|
|
262
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit/stats");
|
|
263
|
+
const res = new FakeRes();
|
|
264
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit/stats?days=7"), res);
|
|
265
|
+
const stats = JSON.parse(res.body);
|
|
266
|
+
assert.equal(res.statusCode, 200);
|
|
267
|
+
assert.equal(stats.days, 7);
|
|
268
|
+
assert.equal(stats.total_calls, 3);
|
|
269
|
+
assert.equal(stats.input_tokens, 135);
|
|
270
|
+
assert.equal(stats.output_tokens, 52);
|
|
271
|
+
assert.equal(stats.total_tokens, 187);
|
|
272
|
+
assert.equal(stats.total_duration_ms, 37);
|
|
273
|
+
const bySource = stats.by_source.find((s) => s.source === "autoDream");
|
|
274
|
+
assert.equal(bySource.c, 2);
|
|
275
|
+
assert.equal(bySource.total_tokens, 180);
|
|
276
|
+
const errStatus = stats.by_status.find((s) => s.status === "error");
|
|
277
|
+
assert.equal(errStatus.c, 1);
|
|
278
|
+
store.close();
|
|
279
|
+
});
|
|
@@ -75,7 +75,9 @@ test("digest 匹配:saveWithDedupe 同标题 merge 后新值落地、无伪冲
|
|
|
75
75
|
assert.equal(result.action, "merged");
|
|
76
76
|
assert.equal(store.count(), 1, "同标题合并不新增条目");
|
|
77
77
|
const m = service.getById(result.memory.id);
|
|
78
|
-
|
|
78
|
+
// Bug5: 同标题合并不是覆盖,而是追加(旧内容 + --- 分隔 + 新内容)
|
|
79
|
+
assert.ok(m.content.includes("旧内容"), "合并后旧内容保留在追加正文");
|
|
80
|
+
assert.ok(m.content.includes("新内容"), "合并后新值必须落地");
|
|
79
81
|
assert.ok(!m.content.includes(CONFLICT_MARKER), "不得出现伪冲突 marker");
|
|
80
82
|
const file = readFileSync(mirrorFile(dir, "preference"), "utf8");
|
|
81
83
|
assert.match(file, /新内容/, "镜像已重渲染为新值");
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { createStore } from "../src/store.js";
|
|
4
|
+
import { createService } from "../src/service.js";
|
|
5
|
+
import {
|
|
6
|
+
evaluateMemoryQuality,
|
|
7
|
+
META_MEMORY_RE,
|
|
8
|
+
textSimilarity,
|
|
9
|
+
dedupRatio
|
|
10
|
+
} from "../src/quality-filter.js";
|
|
11
|
+
|
|
12
|
+
// Bug7: rule-based memory quality filter. Gated on
|
|
13
|
+
// config.memoryQualityFilter.enabled === true — raw configs (`{}`) keep the
|
|
14
|
+
// legacy behavior. Score bands:
|
|
15
|
+
// >= 60 stored normally
|
|
16
|
+
// 30 .. < 60 quality_score persisted, injection ranked by importance × score/100
|
|
17
|
+
// < 30 archived + tagged low_quality (explicit search still recalls it)
|
|
18
|
+
|
|
19
|
+
function setup(over = {}) {
|
|
20
|
+
const store = createStore(":memory:");
|
|
21
|
+
const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true }, ...over } });
|
|
22
|
+
return { store, service };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test("evaluateMemoryQuality: meta-memory scores below 60 (degraded, not archived)", () => {
|
|
26
|
+
const { score, tags } = evaluateMemoryQuality({
|
|
27
|
+
type: "history",
|
|
28
|
+
title: "对话总结",
|
|
29
|
+
content: "总结一下刚才的对话,需要记住以下要点"
|
|
30
|
+
});
|
|
31
|
+
assert.ok(score >= 30 && score < 60, `meta memory should be degraded (30..60), got ${score}`);
|
|
32
|
+
assert.ok(tags.includes("meta"), "tagged meta");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("evaluateMemoryQuality: short content is archived (< 30)", () => {
|
|
36
|
+
const { score, tags } = evaluateMemoryQuality({ type: "preference", title: "语言", content: "短" });
|
|
37
|
+
assert.ok(score < 30, `short content should be archived, got ${score}`);
|
|
38
|
+
assert.ok(tags.includes("short_content"));
|
|
39
|
+
assert.ok(tags.includes("low_quality"));
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("evaluateMemoryQuality: near-duplicate of a recent memory is archived", () => {
|
|
43
|
+
const { score, tags } = evaluateMemoryQuality(
|
|
44
|
+
{ type: "preference", title: "重复", content: "猫咪喜欢在阳台晒太阳并打盹" },
|
|
45
|
+
{ recentContents: ["猫咪喜欢在阳台晒太阳并打盹"] }
|
|
46
|
+
);
|
|
47
|
+
assert.ok(score < 30, `duplicate should be archived, got ${score}`);
|
|
48
|
+
assert.ok(tags.includes("duplicate"));
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("saveWithDedupe: meta memory persists quality_score < 60 and is not archived", () => {
|
|
52
|
+
const { store, service } = setup();
|
|
53
|
+
const { memory } = service.saveWithDedupe({
|
|
54
|
+
type: "history",
|
|
55
|
+
title: "对话总结",
|
|
56
|
+
content: "总结一下刚才的对话,需要记住以下要点"
|
|
57
|
+
});
|
|
58
|
+
const got = store.getById(memory.id);
|
|
59
|
+
assert.ok(got.quality_score !== undefined && got.quality_score < 60,
|
|
60
|
+
`meta memory should store quality_score < 60, got ${got.quality_score}`);
|
|
61
|
+
assert.equal(got.archived, false, "degraded memory stays un-archived");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("saveWithDedupe: short text is archived + tagged low_quality", () => {
|
|
65
|
+
const { store, service } = setup();
|
|
66
|
+
const { memory } = service.saveWithDedupe({
|
|
67
|
+
type: "preference",
|
|
68
|
+
title: "语言",
|
|
69
|
+
content: "短"
|
|
70
|
+
});
|
|
71
|
+
const got = store.getById(memory.id);
|
|
72
|
+
assert.equal(got.archived, true, "short text archived");
|
|
73
|
+
assert.ok(got.tags.includes("low_quality"), "tagged low_quality");
|
|
74
|
+
assert.ok(got.quality_score < 30, `score below archive threshold, got ${got.quality_score}`);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("saveWithDedupe: near-duplicate content is archived", () => {
|
|
78
|
+
const { store, service } = setup();
|
|
79
|
+
service.saveWithDedupe({ type: "preference", title: "习惯一", content: "猫咪喜欢在阳台晒太阳并打盹" });
|
|
80
|
+
const { memory: dup } = service.saveWithDedupe({ type: "preference", title: "习惯二", content: "猫咪喜欢在阳台晒太阳并打盹" });
|
|
81
|
+
const got = store.getById(dup.id);
|
|
82
|
+
assert.equal(got.archived, true, "near-duplicate archived");
|
|
83
|
+
assert.ok(got.tags.includes("low_quality"));
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("saveWithDedupe: filter disabled (raw config) skips scoring entirely", () => {
|
|
87
|
+
const store = createStore(":memory:");
|
|
88
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
89
|
+
const { memory } = service.saveWithDedupe({ type: "preference", title: "语言", content: "短" });
|
|
90
|
+
const got = store.getById(memory.id);
|
|
91
|
+
assert.equal(got.archived, false, "nothing archived when filter off");
|
|
92
|
+
assert.equal(got.quality_score, undefined, "no quality_score when filter off");
|
|
93
|
+
assert.ok(!got.tags.includes("low_quality"));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("injectCandidates: degraded memory ranks below a healthy preference", () => {
|
|
97
|
+
const { service } = setup();
|
|
98
|
+
// Healthy preference: score 100 → weight 1.0 → 3 * 1.0 = 3.0.
|
|
99
|
+
service.saveWithDedupe({ type: "preference", title: "健康偏好", content: "用户平时习惯用中文交流", importance: 3 });
|
|
100
|
+
// Degraded (meta-memory) preference: score ~55 → weight 0.55 → 5 * 0.55 = 2.75.
|
|
101
|
+
service.saveWithDedupe({ type: "preference", title: "元记忆偏好", content: "总结一下刚才的对话内容吧", importance: 5 });
|
|
102
|
+
const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
|
|
103
|
+
const titles = candidates.map((c) => c.title);
|
|
104
|
+
assert.ok(titles.includes("健康偏好"), "healthy preference present");
|
|
105
|
+
assert.ok(titles.includes("元记忆偏好"), "degraded preference present");
|
|
106
|
+
assert.ok(titles.indexOf("健康偏好") < titles.indexOf("元记忆偏好"),
|
|
107
|
+
"degraded memory is demoted below the healthy one");
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("exported helpers behave (meta regex, similarity, dedup ratio)", () => {
|
|
111
|
+
assert.ok(META_MEMORY_RE.test("总结一下刚才的对话"));
|
|
112
|
+
assert.ok(META_MEMORY_RE.test("作为AI助手,我需要记住"));
|
|
113
|
+
assert.ok(!META_MEMORY_RE.test("用户喜欢喝咖啡"));
|
|
114
|
+
assert.equal(textSimilarity("猫咪喜欢晒太阳", "猫咪喜欢晒太阳"), 1);
|
|
115
|
+
assert.ok(textSimilarity("猫咪喜欢晒太阳", "完全不同的内容") < 0.3);
|
|
116
|
+
assert.ok(dedupRatio("哈哈哈哈哈哈") < 0.3, "repetitive filler has low dedup ratio");
|
|
117
|
+
assert.ok(dedupRatio("一句信息量足够的话") > 0.3);
|
|
118
|
+
});
|
|
@@ -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
|
+
});
|