@modusensus/dsh-mneme 0.6.7 → 0.6.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.
Files changed (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +463 -463
  3. package/cordis.patch.yml +15 -15
  4. package/lib/api.js +783 -783
  5. package/lib/client.js +1757 -1757
  6. package/lib/commands.js +64 -64
  7. package/lib/config.js +288 -288
  8. package/lib/dream/clustering.js +118 -118
  9. package/lib/dream/decisions.js +439 -439
  10. package/lib/dream/sleep.js +561 -554
  11. package/lib/dream/tag-extractor.js +156 -156
  12. package/lib/dream.js +935 -929
  13. package/lib/embedding.js +154 -154
  14. package/lib/entities/extractor.js +242 -242
  15. package/lib/hot-memory.js +53 -53
  16. package/lib/index.js +361 -361
  17. package/lib/inject.js +208 -208
  18. package/lib/local-embedder.js +282 -282
  19. package/lib/mirror.js +170 -170
  20. package/lib/parser/tag.js +59 -59
  21. package/lib/parser/wiki-link.js +38 -38
  22. package/lib/quality-filter.js +123 -123
  23. package/lib/reranker.js +218 -218
  24. package/lib/search/adaptive.js +22 -22
  25. package/lib/search/bm25.js +96 -96
  26. package/lib/search/tag-boost.js +61 -61
  27. package/lib/service.js +1726 -1726
  28. package/lib/settings.js +172 -172
  29. package/lib/store.js +2238 -2238
  30. package/lib/summarize.js +236 -236
  31. package/lib/tools.js +290 -290
  32. package/lib/vector-index.js +116 -116
  33. package/package.json +80 -80
  34. package/scripts/benchmark-embed.js +201 -201
  35. package/scripts/benchmark-recall.js +133 -133
  36. package/scripts/benchmark-rerank.js +166 -166
  37. package/scripts/e2e-dsh.js +218 -218
  38. package/scripts/stress-dsh.js +255 -255
  39. package/scripts/sync-lib.js +52 -52
  40. package/src/api.js +783 -783
  41. package/src/commands.js +64 -64
  42. package/src/config.js +288 -288
  43. package/src/dream/clustering.js +118 -118
  44. package/src/dream/decisions.js +439 -439
  45. package/src/dream/sleep.js +561 -554
  46. package/src/dream/tag-extractor.js +156 -156
  47. package/src/dream.js +935 -929
  48. package/src/embedding.js +154 -154
  49. package/src/entities/extractor.js +242 -242
  50. package/src/hot-memory.js +53 -53
  51. package/src/index.js +361 -361
  52. package/src/inject.js +208 -208
  53. package/src/local-embedder.js +282 -282
  54. package/src/mirror.js +170 -170
  55. package/src/parser/tag.js +59 -59
  56. package/src/parser/wiki-link.js +38 -38
  57. package/src/quality-filter.js +123 -123
  58. package/src/reranker.js +218 -218
  59. package/src/search/adaptive.js +22 -22
  60. package/src/search/bm25.js +96 -96
  61. package/src/search/tag-boost.js +61 -61
  62. package/src/service.js +1726 -1726
  63. package/src/settings.js +172 -172
  64. package/src/store.js +2238 -2238
  65. package/src/summarize.js +236 -236
  66. package/src/tools.js +290 -290
  67. package/src/vector-index.js +116 -116
  68. package/test/api.test.js +594 -594
  69. package/test/audit.test.js +448 -448
  70. package/test/benchmark.test.js +35 -35
  71. package/test/boundary-v0625.test.js +82 -82
  72. package/test/client.test.js +368 -368
  73. package/test/clustering.test.js +100 -100
  74. package/test/commands.test.js +69 -69
  75. package/test/config.test.js +50 -50
  76. package/test/conflict-freeze.test.js +290 -290
  77. package/test/directory.test.js +134 -134
  78. package/test/dream.test.js +903 -901
  79. package/test/entities.test.js +522 -522
  80. package/test/epistemic.test.js +298 -298
  81. package/test/fnew-0112.test.js +311 -311
  82. package/test/fnew-03.test.js +422 -422
  83. package/test/graph-api.test.js +175 -175
  84. package/test/helpers/dream-mock.js +82 -82
  85. package/test/hot-memory.test.js +174 -174
  86. package/test/inject.test.js +103 -103
  87. package/test/llm-audit.test.js +279 -279
  88. package/test/local-embedder.test.js +227 -227
  89. package/test/mirror-dirty.test.js +424 -424
  90. package/test/mirror-edit-digest.test.js +187 -187
  91. package/test/mirror-generation.test.js +499 -499
  92. package/test/mirror.test.js +249 -249
  93. package/test/normalize-decisions.test.js +120 -120
  94. package/test/peer-blockers.test.js +190 -190
  95. package/test/policy-epoch.test.js +259 -259
  96. package/test/provenance.test.js +103 -103
  97. package/test/quality-filter.test.js +118 -118
  98. package/test/reasoning-effort.test.js +199 -199
  99. package/test/recall-evals.test.js +235 -235
  100. package/test/recall-layer.test.js +315 -315
  101. package/test/receipt-chain.test.js +451 -451
  102. package/test/reflection.test.js +226 -226
  103. package/test/reranker.test.js +240 -240
  104. package/test/search-fusion.test.js +90 -90
  105. package/test/semantic.test.js +124 -124
  106. package/test/service-search.test.js +199 -199
  107. package/test/service.test.js +435 -435
  108. package/test/settings.test.js +118 -118
  109. package/test/sleep.test.js +365 -365
  110. package/test/store.test.js +436 -436
  111. package/test/stress.test.js +209 -209
  112. package/test/summarize.test.js +191 -191
  113. package/test/tag-boost.test.js +125 -125
  114. package/test/tag.test.js +312 -312
  115. package/test/tools.test.js +285 -285
  116. package/test/vector-index.test.js +221 -221
  117. package/test/wiki-link.test.js +332 -332
@@ -1,235 +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
- });
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
+ });