@modusensus/dsh-mneme 0.2.6 → 0.2.8
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 -3
- package/lib/config.js +4 -0
- package/lib/dream/decisions.js +3 -3
- package/lib/dream.js +123 -6
- package/lib/index.js +17 -0
- package/lib/service.js +47 -9
- package/lib/store.js +237 -7
- package/package.json +1 -1
- package/src/config.js +4 -0
- package/src/dream/decisions.js +3 -3
- package/src/dream.js +123 -6
- package/src/index.js +17 -0
- package/src/service.js +47 -9
- package/src/store.js +237 -7
- package/test/audit.test.js +158 -0
- package/test/dream.test.js +21 -0
- package/test/policy-epoch.test.js +259 -0
- package/test/recall-layer.test.js +314 -0
- package/test/receipt-chain.test.js +451 -0
|
@@ -0,0 +1,259 @@
|
|
|
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 { Config } from "../src/config.js";
|
|
8
|
+
import { createStore } from "../src/store.js";
|
|
9
|
+
import { createService } from "../src/service.js";
|
|
10
|
+
import { createDreamScheduler, parseReceipt } from "../src/dream.js";
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------- helpers
|
|
13
|
+
|
|
14
|
+
function openMemory() {
|
|
15
|
+
return createStore(":memory:");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Minimal valid dream_runs row for store-level tests.
|
|
19
|
+
function run(id, policyEpoch, createdAt) {
|
|
20
|
+
const r = {
|
|
21
|
+
id,
|
|
22
|
+
created_at: createdAt,
|
|
23
|
+
status: "ok",
|
|
24
|
+
snapshot_hash: `hash-${id}`,
|
|
25
|
+
input_count: 1,
|
|
26
|
+
decisions: [{ action: "keep", ids: ["x"] }],
|
|
27
|
+
outcome: { byId: { x: "keep" } },
|
|
28
|
+
applied: 0,
|
|
29
|
+
summary_stored: false,
|
|
30
|
+
receipt: `dsh-mneme:run:${id}:ok:${`hash-${id}`.slice(0, 12)}:1:0:0`
|
|
31
|
+
};
|
|
32
|
+
if (policyEpoch !== undefined) r.policy_epoch = policyEpoch;
|
|
33
|
+
return r;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Minimal DSH-like ctx whose LLM distinguishes the two dream calls by the user
|
|
38
|
+
* prompt shape: consolidation prompts start with "id=…", summary prompts with
|
|
39
|
+
* "- title: content". Mirrors audit.test.js.
|
|
40
|
+
*/
|
|
41
|
+
function mockCtx({ onConsolidation, summaryText = "记忆库总览:用户偏好中文。" } = {}) {
|
|
42
|
+
return {
|
|
43
|
+
logger: { warn: () => {} },
|
|
44
|
+
agentDefaultModel: { currentSelection: () => ({ provider: "mock", model: "mock-model" }) },
|
|
45
|
+
llm: {
|
|
46
|
+
async *stream(options) {
|
|
47
|
+
const userText = options.messages.find((m) => m.role === "user")?.content?.[0]?.text ?? "";
|
|
48
|
+
if (userText.startsWith("id=")) {
|
|
49
|
+
yield { type: "block-start", index: 0, blockType: "text" };
|
|
50
|
+
yield { type: "text-delta", index: 0, text: onConsolidation ? onConsolidation(userText) : "[]" };
|
|
51
|
+
yield { type: "block-end", index: 0, block: { type: "text" } };
|
|
52
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (typeof summaryText === "string") {
|
|
56
|
+
yield { type: "text-delta", index: 0, text: summaryText };
|
|
57
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
58
|
+
} else {
|
|
59
|
+
throw summaryText instanceof Error ? summaryText : new Error(String(summaryText));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------- config
|
|
67
|
+
|
|
68
|
+
test("policyEpoch defaults to 0 when config omits it", () => {
|
|
69
|
+
const cfg = Config({});
|
|
70
|
+
assert.equal(cfg.policyEpoch, 0);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("policyEpoch accepts in-range integers including both boundaries", () => {
|
|
74
|
+
assert.equal(Config({ policyEpoch: 42 }).policyEpoch, 42, "mid-range accepted");
|
|
75
|
+
assert.equal(Config({ policyEpoch: 0 }).policyEpoch, 0, "min boundary accepted");
|
|
76
|
+
assert.equal(Config({ policyEpoch: 1000000 }).policyEpoch, 1000000, "max boundary accepted");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("policyEpoch rejects out-of-range / non-integer / wrong-type values", () => {
|
|
80
|
+
assert.throws(() => Config({ policyEpoch: -1 }), /expected number >= 0/, "below min rejected");
|
|
81
|
+
assert.throws(() => Config({ policyEpoch: 1000001 }), /expected number <= 1000000/, "above max rejected");
|
|
82
|
+
assert.throws(() => Config({ policyEpoch: 1.5 }), /expected number multiple of 1/, "non-integer rejected");
|
|
83
|
+
assert.throws(() => Config({ policyEpoch: "5" }), /expected number/, "string type rejected");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------- store
|
|
87
|
+
|
|
88
|
+
test("saveDreamRun stores policy_epoch and getDreamRun reads it back", () => {
|
|
89
|
+
const store = openMemory();
|
|
90
|
+
const saved = store.saveDreamRun(run("r-epoch-7", 7));
|
|
91
|
+
assert.equal(saved.policy_epoch, 7, "write path returns epoch");
|
|
92
|
+
assert.equal(store.getDreamRun("r-epoch-7").policy_epoch, 7, "read path returns epoch");
|
|
93
|
+
store.close();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("saveDreamRun without policy_epoch defaults to 0", () => {
|
|
97
|
+
const store = openMemory();
|
|
98
|
+
const saved = store.saveDreamRun(run("r-no-epoch"));
|
|
99
|
+
assert.equal(saved.policy_epoch, 0);
|
|
100
|
+
assert.equal(store.getDreamRun("r-no-epoch").policy_epoch, 0);
|
|
101
|
+
store.close();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("saveDreamRun falls back to 0 for non-integer policy_epoch", () => {
|
|
105
|
+
const store = openMemory();
|
|
106
|
+
for (const bad of [1.5, undefined, "7", null]) {
|
|
107
|
+
store.saveDreamRun(run(`r-bad-${String(bad)}`, bad));
|
|
108
|
+
assert.equal(store.getDreamRun(`r-bad-${String(bad)}`).policy_epoch, 0, `policy_epoch=${String(bad)} coerced to 0`);
|
|
109
|
+
}
|
|
110
|
+
store.close();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("migration: legacy dream_runs without policy_epoch column gets it backfilled to 0", () => {
|
|
114
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-epoch-migrate-"));
|
|
115
|
+
const dbPath = join(dir, "legacy.db");
|
|
116
|
+
try {
|
|
117
|
+
// Legacy dream_runs DDL (pre-policy_epoch) + one existing row.
|
|
118
|
+
const legacy = new DatabaseSync(dbPath);
|
|
119
|
+
legacy.exec(`CREATE TABLE dream_runs (
|
|
120
|
+
id TEXT PRIMARY KEY, created_at TEXT NOT NULL, status TEXT NOT NULL, error TEXT,
|
|
121
|
+
provider TEXT, model TEXT, snapshot_hash TEXT NOT NULL, input_count INTEGER NOT NULL,
|
|
122
|
+
input TEXT, decisions TEXT, outcome TEXT, applied INTEGER NOT NULL DEFAULT 0,
|
|
123
|
+
summary_stored INTEGER NOT NULL DEFAULT 0, receipt TEXT NOT NULL
|
|
124
|
+
);`);
|
|
125
|
+
legacy.exec(`CREATE INDEX idx_dream_runs_created ON dream_runs(created_at);`);
|
|
126
|
+
legacy.prepare(
|
|
127
|
+
`INSERT INTO dream_runs (id, created_at, status, snapshot_hash, input_count, receipt)
|
|
128
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
129
|
+
).run("legacy-run", "2026-08-01T00:00:00.000Z", "ok", "h", 1, "dsh-mneme:run:legacy-run:ok:h:1:0:0");
|
|
130
|
+
legacy.close();
|
|
131
|
+
|
|
132
|
+
const store = createStore(dbPath);
|
|
133
|
+
const cols = store.db.prepare("PRAGMA table_info(dream_runs)").all().map((c) => c.name);
|
|
134
|
+
assert.ok(cols.includes("policy_epoch"), "policy_epoch column added");
|
|
135
|
+
assert.equal(store.getDreamRun("legacy-run").policy_epoch, 0, "existing row backfilled to default 0");
|
|
136
|
+
store.close();
|
|
137
|
+
} finally {
|
|
138
|
+
rmSync(dir, { recursive: true, force: true });
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("migration is idempotent: reopening a migrated store does not error or lose data", () => {
|
|
143
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-epoch-idem-"));
|
|
144
|
+
const dbPath = join(dir, "epoch.db");
|
|
145
|
+
try {
|
|
146
|
+
const s1 = createStore(dbPath);
|
|
147
|
+
s1.saveDreamRun(run("r1", 5));
|
|
148
|
+
s1.close();
|
|
149
|
+
// Reopen over the already-migrated schema — must not re-ALTER or throw.
|
|
150
|
+
const s2 = createStore(dbPath);
|
|
151
|
+
assert.equal(s2.getDreamRun("r1").policy_epoch, 5, "data intact across reopen");
|
|
152
|
+
const cols = s2.db.prepare("PRAGMA table_info(dream_runs)").all().map((c) => c.name);
|
|
153
|
+
assert.equal(cols.filter((c) => c === "policy_epoch").length, 1, "column not duplicated");
|
|
154
|
+
s2.close();
|
|
155
|
+
} finally {
|
|
156
|
+
rmSync(dir, { recursive: true, force: true });
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("getLatestPolicyEpoch returns the newest run's epoch by created_at", () => {
|
|
161
|
+
const store = openMemory();
|
|
162
|
+
store.saveDreamRun(run("epoch-1", 1, "2026-08-01T00:00:00.000Z"));
|
|
163
|
+
assert.equal(store.getLatestPolicyEpoch(), 1, "only row wins");
|
|
164
|
+
store.saveDreamRun(run("epoch-2", 2, "2026-08-02T00:00:00.000Z"));
|
|
165
|
+
assert.equal(store.getLatestPolicyEpoch(), 2, "newer row wins");
|
|
166
|
+
store.saveDreamRun(run("epoch-5", 5, "2026-08-03T00:00:00.000Z"));
|
|
167
|
+
assert.equal(store.getLatestPolicyEpoch(), 5, "newest row wins over mixed epochs");
|
|
168
|
+
store.close();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("getLatestPolicyEpoch returns 0 on an empty store", () => {
|
|
172
|
+
const store = openMemory();
|
|
173
|
+
assert.equal(store.getLatestPolicyEpoch(), 0);
|
|
174
|
+
store.close();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------- dream
|
|
178
|
+
|
|
179
|
+
function dreamSetup() {
|
|
180
|
+
const store = createStore(":memory:");
|
|
181
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
182
|
+
const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
|
|
183
|
+
return { store, service, dream };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
test("runDream writes audit row with policy_epoch when config.policyEpoch=5", async () => {
|
|
187
|
+
const { store, service, dream } = dreamSetup();
|
|
188
|
+
const a = service.saveWithDedupe({ type: "project", title: "旧1", content: "内容A" });
|
|
189
|
+
const b = service.saveWithDedupe({ type: "project", title: "旧2", content: "内容B" });
|
|
190
|
+
const ctx = mockCtx({
|
|
191
|
+
onConsolidation: () => JSON.stringify([
|
|
192
|
+
{ action: "merge", ids: [a.memory.id, b.memory.id], title: "合并", content: "合并内容", importance: 4, keepSource: a.memory.id }
|
|
193
|
+
])
|
|
194
|
+
});
|
|
195
|
+
const result = await dream.runDream(ctx, service, { policyEpoch: 5 });
|
|
196
|
+
assert.equal(result.ok, true);
|
|
197
|
+
const run = store.getDreamRun(result.runId);
|
|
198
|
+
assert.equal(run.policy_epoch, 5, "audit row carries configured epoch");
|
|
199
|
+
store.close();
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("runDream writes audit row with policy_epoch 0 when config omits it", async () => {
|
|
203
|
+
const { store, service, dream } = dreamSetup();
|
|
204
|
+
const a = service.saveWithDedupe({ type: "project", title: "旧1", content: "内容A" });
|
|
205
|
+
const b = service.saveWithDedupe({ type: "project", title: "旧2", content: "内容B" });
|
|
206
|
+
const ctx = mockCtx({
|
|
207
|
+
onConsolidation: () => JSON.stringify([
|
|
208
|
+
{ action: "merge", ids: [a.memory.id, b.memory.id], title: "合并", content: "合并内容", importance: 4, keepSource: a.memory.id }
|
|
209
|
+
])
|
|
210
|
+
});
|
|
211
|
+
const result = await dream.runDream(ctx, service, {});
|
|
212
|
+
assert.equal(result.ok, true);
|
|
213
|
+
const run = store.getDreamRun(result.runId);
|
|
214
|
+
assert.equal(run.policy_epoch, 0, "default epoch written when config omits policyEpoch");
|
|
215
|
+
store.close();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("compat: receipt stays 8 segments with an epoch in use", async () => {
|
|
219
|
+
const { store, service, dream } = dreamSetup();
|
|
220
|
+
const a = service.saveWithDedupe({ type: "project", title: "旧1", content: "内容A" });
|
|
221
|
+
const b = service.saveWithDedupe({ type: "project", title: "旧2", content: "内容B" });
|
|
222
|
+
const ctx = mockCtx({
|
|
223
|
+
onConsolidation: () => JSON.stringify([
|
|
224
|
+
{ action: "merge", ids: [a.memory.id, b.memory.id], title: "合并", content: "合并内容", importance: 4, keepSource: a.memory.id }
|
|
225
|
+
])
|
|
226
|
+
});
|
|
227
|
+
const result = await dream.runDream(ctx, service, { policyEpoch: 5 });
|
|
228
|
+
const run = store.getDreamRun(result.runId);
|
|
229
|
+
assert.equal(run.receipt.split(":").length, 8, "receipt format unchanged (8 segments)");
|
|
230
|
+
const parsed = parseReceipt(run.receipt);
|
|
231
|
+
assert.deepEqual(parsed, {
|
|
232
|
+
runId: run.id,
|
|
233
|
+
status: "ok",
|
|
234
|
+
snapshotHash: run.snapshot_hash.slice(0, 12),
|
|
235
|
+
inputCount: 2,
|
|
236
|
+
applied: 1,
|
|
237
|
+
summaryStored: true
|
|
238
|
+
}, "receipt round-trips with an epoch in use");
|
|
239
|
+
store.close();
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// ---------------------------------------------------------------- semantic
|
|
243
|
+
|
|
244
|
+
test("semantic: runs from different epochs stay distinguishable and the newer epoch wins", () => {
|
|
245
|
+
const store = openMemory();
|
|
246
|
+
// epoch 1 = old ruling-rule version (historical evidence after upgrade)
|
|
247
|
+
store.saveDreamRun(run("v1-run", 1, "2026-08-01T00:00:00.000Z"));
|
|
248
|
+
// epoch 2 = new ruling-rule version
|
|
249
|
+
store.saveDreamRun(run("v2-run", 2, "2026-08-02T00:00:00.000Z"));
|
|
250
|
+
assert.equal(store.getDreamRun("v1-run").policy_epoch, 1, "old run keeps its epoch (historical evidence)");
|
|
251
|
+
assert.equal(store.getDreamRun("v2-run").policy_epoch, 2, "new run keeps its epoch");
|
|
252
|
+
assert.notEqual(
|
|
253
|
+
store.getDreamRun("v1-run").policy_epoch,
|
|
254
|
+
store.getDreamRun("v2-run").policy_epoch,
|
|
255
|
+
"epochs are distinguishable per run"
|
|
256
|
+
);
|
|
257
|
+
assert.equal(store.getLatestPolicyEpoch(), 2, "effective rule version reflects the upgrade");
|
|
258
|
+
store.close();
|
|
259
|
+
});
|
|
@@ -0,0 +1,314 @@
|
|
|
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 { createVectorIndex } from "../src/vector-index.js";
|
|
6
|
+
|
|
7
|
+
// Mock embedder: every query maps to the fixed vector [1,0,0], so vector recall
|
|
8
|
+
// surfaces any row embedded at [1,0,0] (cosine 1) and excludes orthogonal ones
|
|
9
|
+
// (cosine 0) once the search passes a threshold > 0.
|
|
10
|
+
const embedder = {
|
|
11
|
+
embedSingle: async () => [1, 0, 0],
|
|
12
|
+
embed: async () => [1, 0, 0],
|
|
13
|
+
modelHash: "recall#mock",
|
|
14
|
+
dimension: 3
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Real store + service wired with the mock embedder and a vector index over the
|
|
18
|
+
// same store (the service's vector path prefers vectorIndex when set).
|
|
19
|
+
function setup() {
|
|
20
|
+
const store = createStore(":memory:");
|
|
21
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
22
|
+
const vectorIndex = createVectorIndex({ store });
|
|
23
|
+
service.setEmbedder(embedder);
|
|
24
|
+
service.setVectorIndex(vectorIndex);
|
|
25
|
+
return { store, service, vectorIndex };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function saveMemory(service, vectorIndex, { title, content, embedding }) {
|
|
29
|
+
const mem = service.saveWithDedupe({ type: "preference", title, content, importance: 5 });
|
|
30
|
+
if (embedding) vectorIndex.saveEmbedding(mem.memory.id, embedding);
|
|
31
|
+
return mem.memory;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test("recordRecall=true invokes the recorder once with the full recall scene", async () => {
|
|
35
|
+
const { service } = setup();
|
|
36
|
+
const seen = [];
|
|
37
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
38
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
39
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", topK: 5, threshold: 0.4, recordRecall: true });
|
|
40
|
+
|
|
41
|
+
assert.equal(seen.length, 1, "recorder called exactly once");
|
|
42
|
+
const rec = seen[0];
|
|
43
|
+
assert.equal(rec.query, "量子");
|
|
44
|
+
assert.equal(rec.mode, "keyword");
|
|
45
|
+
assert.equal(rec.topK, 5);
|
|
46
|
+
assert.equal(rec.threshold, 0.4);
|
|
47
|
+
assert.ok(typeof rec.createdAt === "string" && rec.createdAt.length > 0, "createdAt is an ISO string");
|
|
48
|
+
assert.equal(rec.candidates.length, rows.length, "candidates mirror the returned rows");
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("recorded candidates carry id/title/content/score/source and match the return value", async () => {
|
|
52
|
+
const { service } = setup();
|
|
53
|
+
const seen = [];
|
|
54
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
55
|
+
const a = saveMemory(service, null, { title: "量子计算入门", content: "叠加态" });
|
|
56
|
+
const b = saveMemory(service, null, { title: "量子纠缠", content: "贝尔态" });
|
|
57
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", topK: 5, recordRecall: true });
|
|
58
|
+
|
|
59
|
+
const cands = seen[0].candidates;
|
|
60
|
+
assert.deepEqual(cands.map((c) => c.id), rows.map((r) => r.id), "candidate ids equal returned ids");
|
|
61
|
+
for (const c of cands) {
|
|
62
|
+
assert.ok(typeof c.id === "string" && c.id, "id present");
|
|
63
|
+
assert.ok("title" in c && "content" in c, "title/content present");
|
|
64
|
+
assert.equal(typeof c.score, "number", "score is numeric");
|
|
65
|
+
assert.equal(c.source, "keyword", "keyword-mode candidates are marked 'keyword'");
|
|
66
|
+
}
|
|
67
|
+
// Exact candidate rows must deep-equal the returned memory rows.
|
|
68
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
69
|
+
for (const c of cands) {
|
|
70
|
+
const row = byId.get(c.id);
|
|
71
|
+
assert.equal(c.title, row.title);
|
|
72
|
+
assert.equal(c.content, row.content);
|
|
73
|
+
assert.equal(c.score, row.score);
|
|
74
|
+
}
|
|
75
|
+
assert.ok(cands.some((c) => c.id === a.id), "first memory recorded");
|
|
76
|
+
assert.ok(cands.some((c) => c.id === b.id), "second memory recorded");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("recordRecall defaults to off — recorder is not called", async () => {
|
|
80
|
+
const { service } = setup();
|
|
81
|
+
let calls = 0;
|
|
82
|
+
service.setRecallRecorder(() => calls++);
|
|
83
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
84
|
+
await service.searchMemories("量子", { mode: "keyword" });
|
|
85
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: false });
|
|
86
|
+
assert.equal(calls, 0, "no recorder call when recordRecall is unset or false");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("recordRecall=true with no recorder installed is safe and returns normally", async () => {
|
|
90
|
+
const { service } = setup();
|
|
91
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
92
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
93
|
+
assert.ok(Array.isArray(rows) && rows.length === 1, "search still returns results");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("a throwing recorder never breaks the search", async () => {
|
|
97
|
+
const { service } = setup();
|
|
98
|
+
service.setRecallRecorder(() => { throw new Error("recorder exploded"); });
|
|
99
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
100
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
101
|
+
assert.equal(rows.length, 1, "search unaffected by recorder failure");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("an empty result set still records a run with an empty candidate list", async () => {
|
|
105
|
+
const { service } = setup();
|
|
106
|
+
const seen = [];
|
|
107
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
108
|
+
const rows = await service.searchMemories("不存在的记忆xyz", { mode: "keyword", recordRecall: true });
|
|
109
|
+
assert.deepEqual(rows, [], "no matches");
|
|
110
|
+
assert.equal(seen.length, 1, "receipt emitted even for empty recall");
|
|
111
|
+
assert.deepEqual(seen[0].candidates, [], "candidates empty");
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("an empty query short-circuits before the recorder", async () => {
|
|
115
|
+
const { service } = setup();
|
|
116
|
+
const seen = [];
|
|
117
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
118
|
+
const rows = await service.searchMemories(" ", { mode: "keyword", recordRecall: true });
|
|
119
|
+
assert.deepEqual(rows, [], "blank query returns nothing");
|
|
120
|
+
assert.equal(seen.length, 0, "no receipt for blank query");
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("consecutive recordRecall=true searches emit one receipt each", async () => {
|
|
124
|
+
const { service } = setup();
|
|
125
|
+
const seen = [];
|
|
126
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
127
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
128
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
129
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
130
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
131
|
+
assert.equal(seen.length, 3, "no misses, no duplicates");
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("reinstalling a recorder replaces the previous one", async () => {
|
|
135
|
+
const { service } = setup();
|
|
136
|
+
const first = [];
|
|
137
|
+
const second = [];
|
|
138
|
+
service.setRecallRecorder((r) => first.push(r));
|
|
139
|
+
service.setRecallRecorder((r) => second.push(r));
|
|
140
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
141
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
142
|
+
assert.equal(first.length, 0, "old recorder dropped");
|
|
143
|
+
assert.equal(second.length, 1, "new recorder receives the receipt");
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("vector mode marks candidates with source 'vector' (mock embedder)", async () => {
|
|
147
|
+
const { service, vectorIndex } = setup();
|
|
148
|
+
const seen = [];
|
|
149
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
150
|
+
saveMemory(service, vectorIndex, { title: "猫", content: "喜欢猫", embedding: [1, 0, 0] });
|
|
151
|
+
const rows = await service.searchMemories("猫", { mode: "vector", threshold: 0.5, useRerank: false, recordRecall: true });
|
|
152
|
+
assert.ok(rows.length >= 1, "vector recall hits the embedded row");
|
|
153
|
+
const cands = seen[0].candidates;
|
|
154
|
+
for (const c of cands) assert.equal(c.source, "vector", "vector-mode candidate source");
|
|
155
|
+
assert.ok(cands.every((c) => typeof c.score === "number"), "vector scores numeric");
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("keyword mode marks candidates with source 'keyword' even when an embedder is installed", async () => {
|
|
159
|
+
const { service, vectorIndex } = setup();
|
|
160
|
+
const seen = [];
|
|
161
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
162
|
+
saveMemory(service, vectorIndex, { title: "量子计算", content: "入门", embedding: [1, 0, 0] });
|
|
163
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", useRerank: false, recordRecall: true });
|
|
164
|
+
assert.ok(rows.length >= 1, "keyword recall hits the literal match");
|
|
165
|
+
for (const c of seen[0].candidates) assert.equal(c.source, "keyword");
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test("hybrid mode marks vector-only / keyword-only / both candidates correctly", async () => {
|
|
169
|
+
const { service, vectorIndex } = setup();
|
|
170
|
+
const seen = [];
|
|
171
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
172
|
+
// vector-only: no literal match, embedded exactly at the query vector.
|
|
173
|
+
const vec = saveMemory(service, vectorIndex, { title: "猫", content: "喜欢猫", embedding: [1, 0, 0] });
|
|
174
|
+
// keyword-only: literal match, embedding far from [1,0,0] -> excluded by threshold.
|
|
175
|
+
const kw = saveMemory(service, vectorIndex, { title: "量子计算", content: "入门", embedding: [0, 1, 0] });
|
|
176
|
+
// both: literal match AND embedded at [1,0,0].
|
|
177
|
+
const both = saveMemory(service, vectorIndex, { title: "量子计算笔记", content: "量子实践", embedding: [1, 0, 0] });
|
|
178
|
+
|
|
179
|
+
await service.searchMemories("量子", { mode: "hybrid", threshold: 0.5, useRerank: false, topK: 10, recordRecall: true });
|
|
180
|
+
const cands = seen[0].candidates;
|
|
181
|
+
const byId = new Map(cands.map((c) => [c.id, c]));
|
|
182
|
+
assert.equal(byId.get(vec.id).source, "vector", "vector-only hit marked 'vector'");
|
|
183
|
+
assert.equal(byId.get(kw.id).source, "keyword", "keyword-only hit marked 'keyword'");
|
|
184
|
+
// Shared memory: vector leads the blend, so the merged row keeps the vector mark.
|
|
185
|
+
assert.equal(byId.get(both.id).source, "vector", "both-path hit marked 'vector'");
|
|
186
|
+
assert.equal(cands.length, 3, "all three rows in the receipt");
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("rerank overwrites the candidate source to 'rerank'", async () => {
|
|
190
|
+
const { service } = setup();
|
|
191
|
+
const seen = [];
|
|
192
|
+
service.setRecallRecorder((r) => seen.push(r));
|
|
193
|
+
service.setReranker({
|
|
194
|
+
rerank: async (q, cands) => cands.map((c, i) => ({ id: c.id, score: i }))
|
|
195
|
+
});
|
|
196
|
+
saveMemory(service, null, { title: "量子计算", content: "入门" });
|
|
197
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: true });
|
|
198
|
+
assert.equal(seen[0].candidates[0].source, "rerank", "reranked candidates are marked 'rerank'");
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
test("store: saveRecallRun round-trips through getRecallRun with candidates intact", async () => {
|
|
202
|
+
const store = createStore(":memory:");
|
|
203
|
+
const cands = [
|
|
204
|
+
{ id: "a", title: "量子计算", content: "入门\n第二行", score: 0.9, source: "vector" },
|
|
205
|
+
{ id: "b", title: "猫", content: "喜欢猫 \"quoted\"", score: null, source: "keyword" }
|
|
206
|
+
];
|
|
207
|
+
const saved = store.saveRecallRun({
|
|
208
|
+
id: "run-1", query: "量子", mode: "hybrid", topK: 5, threshold: 0.4,
|
|
209
|
+
candidates: cands, created_at: "2026-08-16T01:00:00.000Z"
|
|
210
|
+
});
|
|
211
|
+
assert.equal(saved.id, "run-1", "save returns the persisted run");
|
|
212
|
+
const got = store.getRecallRun("run-1");
|
|
213
|
+
assert.equal(got.query, "量子");
|
|
214
|
+
assert.equal(got.mode, "hybrid");
|
|
215
|
+
assert.equal(got.topK, 5);
|
|
216
|
+
assert.equal(got.threshold, 0.4);
|
|
217
|
+
assert.equal(got.created_at, "2026-08-16T01:00:00.000Z");
|
|
218
|
+
assert.deepEqual(got.candidates, cands, "candidates JSON survives round-trip");
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test("store: getRecallRun returns undefined for a missing id", async () => {
|
|
222
|
+
const store = createStore(":memory:");
|
|
223
|
+
assert.equal(store.getRecallRun("nope"), undefined);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
test("store: saveRecallRun is idempotent on the run id (replay overwrites)", async () => {
|
|
227
|
+
const store = createStore(":memory:");
|
|
228
|
+
store.saveRecallRun({ id: "r", query: "量子", mode: "keyword", topK: 5, candidates: [{ id: "a" }] });
|
|
229
|
+
store.saveRecallRun({ id: "r", query: "量子", mode: "keyword", topK: 10, candidates: [{ id: "a" }, { id: "b" }] });
|
|
230
|
+
const runs = store.listRecallRuns();
|
|
231
|
+
assert.equal(runs.length, 1, "one row for a replayed id");
|
|
232
|
+
assert.equal(runs[0].topK, 10, "replay overwrites the previous values");
|
|
233
|
+
assert.equal(runs[0].candidates.length, 2);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test("store: saveRecallRun without an id assigns a unique id per run", async () => {
|
|
237
|
+
const store = createStore(":memory:");
|
|
238
|
+
const a = store.saveRecallRun({ query: "q1", mode: "keyword", topK: 5, candidates: [] });
|
|
239
|
+
const b = store.saveRecallRun({ query: "q2", mode: "keyword", topK: 5, candidates: [] });
|
|
240
|
+
assert.ok(a.id && b.id && a.id !== b.id, "distinct generated ids");
|
|
241
|
+
assert.equal(store.listRecallRuns().length, 2, "both persisted, none overwritten");
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("store: listRecallRuns orders by created_at descending", async () => {
|
|
245
|
+
const store = createStore(":memory:");
|
|
246
|
+
store.saveRecallRun({ id: "old", query: "旧查询", mode: "keyword", topK: 5, candidates: [], created_at: "2026-08-16T01:00:00.000Z" });
|
|
247
|
+
store.saveRecallRun({ id: "new", query: "新查询", mode: "vector", topK: 5, candidates: [], created_at: "2026-08-16T03:00:00.000Z" });
|
|
248
|
+
store.saveRecallRun({ id: "mid", query: "中间", mode: "hybrid", topK: 5, candidates: [], created_at: "2026-08-16T02:00:00.000Z" });
|
|
249
|
+
const runs = store.listRecallRuns();
|
|
250
|
+
assert.deepEqual(runs.map((r) => r.id), ["new", "mid", "old"], "newest first");
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test("store: listRecallRuns filters by query substring", async () => {
|
|
254
|
+
const store = createStore(":memory:");
|
|
255
|
+
store.saveRecallRun({ id: "1", query: "量子计算", mode: "keyword", topK: 5, candidates: [] });
|
|
256
|
+
store.saveRecallRun({ id: "2", query: "猫咪饲养", mode: "keyword", topK: 5, candidates: [] });
|
|
257
|
+
store.saveRecallRun({ id: "3", query: "量子纠缠", mode: "keyword", topK: 5, candidates: [] });
|
|
258
|
+
const runs = store.listRecallRuns({ query: "量子" });
|
|
259
|
+
assert.deepEqual(runs.map((r) => r.id), ["3", "1"], "only matching queries, newest first");
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
test("store: listRecallRuns honors limit/offset paging", async () => {
|
|
263
|
+
const store = createStore(":memory:");
|
|
264
|
+
for (let i = 0; i < 5; i++) {
|
|
265
|
+
store.saveRecallRun({ id: `r${i}`, query: `查询${i}`, mode: "keyword", topK: 5, candidates: [], created_at: `2026-08-16T0${i + 1}:00:00.000Z` });
|
|
266
|
+
}
|
|
267
|
+
const page = store.listRecallRuns({ limit: 2, offset: 1 });
|
|
268
|
+
assert.equal(page.length, 2, "page size honored");
|
|
269
|
+
assert.deepEqual(page.map((r) => r.id), ["r3", "r2"], "ordered desc, offset applied");
|
|
270
|
+
assert.deepEqual(store.listRecallRuns({ limit: 100, offset: 100 }), [], "offset past the end is empty");
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
test("e2e: index.js wiring — recordRecall search lands a row listRecallRuns can read back", async () => {
|
|
274
|
+
const store = createStore(":memory:");
|
|
275
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
276
|
+
// Simulate src/index.js: the recorder persists each receipt to recall_runs.
|
|
277
|
+
service.setRecallRecorder((recall) => {
|
|
278
|
+
store.saveRecallRun({
|
|
279
|
+
query: recall.query,
|
|
280
|
+
mode: recall.mode,
|
|
281
|
+
topK: recall.topK,
|
|
282
|
+
threshold: recall.threshold ?? null,
|
|
283
|
+
candidates: recall.candidates ?? [],
|
|
284
|
+
created_at: recall.createdAt
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
service.saveWithDedupe({ type: "preference", title: "量子计算入门", content: "叠加态" });
|
|
288
|
+
|
|
289
|
+
const rows = await service.searchMemories("量子", { mode: "keyword", topK: 3, recordRecall: true });
|
|
290
|
+
const runs = store.listRecallRuns();
|
|
291
|
+
assert.equal(runs.length, 1, "exactly one recall run persisted");
|
|
292
|
+
const run = runs[0];
|
|
293
|
+
assert.equal(run.query, "量子");
|
|
294
|
+
assert.equal(run.mode, "keyword");
|
|
295
|
+
assert.equal(run.topK, 3);
|
|
296
|
+
assert.equal(run.threshold, null);
|
|
297
|
+
assert.deepEqual(run.candidates.map((c) => c.id), rows.map((r) => r.id), "candidates match the response");
|
|
298
|
+
assert.ok(run.created_at, "timestamp captured");
|
|
299
|
+
// The receipt is available immediately after the awaited search returns.
|
|
300
|
+
assert.equal(store.getRecallRun(run.id).query, "量子", "row readable right away");
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
test("e2e: without recordRecall the recall_runs table gains no rows", async () => {
|
|
304
|
+
const store = createStore(":memory:");
|
|
305
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
306
|
+
service.setRecallRecorder((recall) => store.saveRecallRun({
|
|
307
|
+
query: recall.query, mode: recall.mode, topK: recall.topK, threshold: recall.threshold ?? null,
|
|
308
|
+
candidates: recall.candidates ?? [], created_at: recall.createdAt
|
|
309
|
+
}));
|
|
310
|
+
service.saveWithDedupe({ type: "preference", title: "量子计算入门", content: "叠加态" });
|
|
311
|
+
await service.searchMemories("量子", { mode: "keyword" });
|
|
312
|
+
await service.searchMemories("量子", { mode: "keyword", recordRecall: false });
|
|
313
|
+
assert.deepEqual(store.listRecallRuns(), [], "no rows without recordRecall=true");
|
|
314
|
+
});
|