@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,174 +1,174 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { createHotMemory, estimateTokens } from "../src/hot-memory.js";
4
- import { createStore } from "../src/store.js";
5
- import { createService } from "../src/service.js";
6
- import { createVectorIndex } from "../src/vector-index.js";
7
-
8
- // --- hot memory buffer ---
9
-
10
- test("hot memory keeps the latest rounds within maxRounds", () => {
11
- const hot = createHotMemory({ maxRounds: 2, maxTokens: 10000 });
12
- hot.add({ query: "第一轮", response: "答一" });
13
- hot.add({ query: "第二轮", response: "答二" });
14
- hot.add({ query: "第三轮", response: "答三" });
15
- assert.equal(hot.rounds().length, 2);
16
- assert.ok(hot.getContext().includes("第三轮"));
17
- assert.ok(!hot.getContext().includes("第一轮"));
18
- });
19
-
20
- test("hot memory enforces the token budget", () => {
21
- const hot = createHotMemory({ maxRounds: 10, maxTokens: 30 });
22
- hot.add({ query: "很长的第一轮问题".repeat(10), response: "很长的回答".repeat(10) });
23
- hot.add({ query: "第二轮", response: "答二" });
24
- // The first round alone blows the budget; the newest round survives and
25
- // the buffer never empties completely.
26
- const rounds = hot.rounds();
27
- assert.ok(rounds.length >= 1);
28
- assert.equal(rounds[rounds.length - 1].query, "第二轮");
29
- });
30
-
31
- test("hot memory getContext uses the Q/A round format", () => {
32
- const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
33
- hot.add({ query: "Q1", response: "A1" });
34
- hot.add({ query: "Q2", response: "A2" });
35
- assert.equal(hot.getContext(), "Q: Q1\nA: A1\n\nQ: Q2\nA: A2");
36
- });
37
-
38
- test("hot memory ignores empty rounds and clears", () => {
39
- const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
40
- hot.add({ query: "", response: "x" });
41
- hot.add(null);
42
- assert.equal(hot.rounds().length, 0);
43
- hot.add({ query: "q" });
44
- hot.clear();
45
- assert.equal(hot.getContext(), "");
46
- });
47
-
48
- test("estimateTokens counts CJK heavier than ASCII", () => {
49
- assert.ok(estimateTokens("中文内容") > estimateTokens("abcd"));
50
- });
51
-
52
- // --- entry defense: non-positive / non-integer bounds fall back to defaults ---
53
- // Bug: createHotMemory({ maxRounds: -1 }) made the eviction while-loop
54
- // `while (buffer.length > maxRounds)` unbounded — after the buffer emptied,
55
- // `0 > -1` stayed true and buffer.shift() on an empty array is a no-op, so
56
- // every add() spun forever. Non-integer values (1.5, NaN, null) were also
57
- // silently wrong. The fix clamps them to the 5/2000 defaults at the door.
58
-
59
- test("hot memory falls back to maxRounds=5 for non-positive/invalid values", () => {
60
- for (const bad of [0, -1, 1.5, NaN, null]) {
61
- const hot = createHotMemory({ maxRounds: bad, maxTokens: 10000 });
62
- for (let i = 0; i < 8; i++) hot.add({ query: `第${i}轮`, response: "x" });
63
- assert.equal(hot.rounds().length, 5, `maxRounds=${bad} must fall back to 5, no infinite loop`);
64
- assert.ok(hot.getContext().includes("第7轮"), `maxRounds=${bad}: newest round survives`);
65
- assert.ok(!hot.getContext().includes("第0轮"), `maxRounds=${bad}: oldest round evicted`);
66
- }
67
- });
68
-
69
- test("hot memory falls back to maxTokens=2000 for non-positive/infinite values", () => {
70
- for (const bad of [0, -1, Infinity]) {
71
- const hot = createHotMemory({ maxRounds: 50, maxTokens: bad });
72
- // 50 rounds at ~74 tokens each blow a 2000-token budget; the fallback must
73
- // evict into (1, 50). A broken budget of 0/-1 would squeeze to 1 round and
74
- // Infinity would keep all 50 — both are the pre-fix behavior.
75
- for (let i = 0; i < 50; i++) hot.add({ query: `第${i}轮`, response: "长回答".repeat(40) });
76
- const n = hot.rounds().length;
77
- assert.ok(n > 1 && n < 50, `maxTokens=${bad} falls back to 2000 (kept ${n} rounds)`);
78
- }
79
- });
80
-
81
- // --- service-level: BM25 fusion + semantic dedup + selective injection ---
82
-
83
- function toyVec(text) {
84
- const v = new Array(64).fill(0);
85
- for (const t of String(text).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean)) {
86
- let h = 0;
87
- for (const ch of t) h = (h * 31 + ch.codePointAt(0)) >>> 0;
88
- v[h % 64] += 1;
89
- }
90
- const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
91
- return v.map((x) => x / norm);
92
- }
93
-
94
- function setup(overrides = {}) {
95
- const store = createStore(":memory:");
96
- const config = {
97
- entitySearchEnabled: false,
98
- bm25SearchEnabled: true,
99
- adaptiveThresholdEnabled: false,
100
- searchSemanticDedup: true,
101
- selectiveInjectEnabled: true,
102
- ...overrides
103
- };
104
- const service = createService({ store, mirror: null, config, logger: null });
105
- service.setVectorIndex(createVectorIndex({ store, logger: null }));
106
- service.setEmbedder({ embedSingle: async (t) => toyVec(t) });
107
- return { store, service };
108
- }
109
-
110
- test("searchMemories fuses BM25: scattered-term queries recall both rows", async () => {
111
- const { store, service } = setup();
112
- const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
113
- const b = store.save({ type: "decision", title: "语言迁移", content: "编译模块迁移到 Rust", importance: 3 });
114
- store.save({ type: "project", title: "无关", content: "夜间 ETL 脚本", importance: 3 });
115
-
116
- // "rust 异步" is not a substring of either row — LIKE misses both; BM25
117
- // must surface both rows in the merged result.
118
- const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
119
- const ids = results.map((r) => r.id);
120
- assert.ok(ids.includes(a.id), "async row must be recalled via BM25");
121
- assert.ok(ids.includes(b.id), "rust row must be recalled via BM25");
122
- assert.equal(results.find((r) => r.id === a.id)?.source, "bm25");
123
- });
124
-
125
- test("bm25SearchEnabled=false restores the two-path behavior", async () => {
126
- const { store, service } = setup({ bm25SearchEnabled: false });
127
- const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
128
- const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
129
- assert.ok(!results.some((r) => r.id === a.id), "no BM25 → scattered-term miss is back");
130
- });
131
-
132
- test("search-time semantic dedup drops near-identical embeddings", async () => {
133
- const { store, service } = setup();
134
- const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
135
- const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
136
- store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
137
- store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
138
-
139
- // auto (not keyword): keyword mode is the documented text-only path and is
140
- // exempt from dedup by design; auto exercises the dedup the way production
141
- // searches run.
142
- const results = await service.searchMemories("深色主题", { mode: "auto", topK: 5 });
143
- const ids = results.map((r) => r.id);
144
- assert.ok(ids.includes(a.id) !== ids.includes(b.id), "one of the near-duplicate pair is dropped");
145
- });
146
-
147
- test("searchSemanticDedup=false keeps duplicate embeddings", async () => {
148
- const { store, service } = setup({ searchSemanticDedup: false });
149
- const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
150
- const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
151
- store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
152
- store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
153
- const results = await service.searchMemories("深色主题", { mode: "keyword", topK: 5 });
154
- assert.equal(results.length, 2);
155
- });
156
-
157
- test("selective injection re-orders candidates by query similarity", () => {
158
- const { store, service } = setup();
159
- const thesis = store.save({ type: "project", title: "湿地论文", content: "毕业论文研究城市湿地公园", importance: 5 });
160
- const plugin = store.save({ type: "project", title: "插件项目", content: "dsh-mneme 记忆插件开发", importance: 5 });
161
- store.setEmbedding(thesis.id, toyVec("毕业论文研究城市湿地公园"));
162
- store.setEmbedding(plugin.id, toyVec("dsh-mneme 记忆插件开发"));
163
-
164
- // Rule-based order would put both at equal importance; the query vector is
165
- // about the thesis, so topic ranking must put the thesis memory first.
166
- const picked = service.injectCandidates({
167
- query: "论文写作",
168
- queryVector: toyVec("毕业论文研究城市湿地公园"),
169
- maxItems: 2,
170
- threshold: 3
171
- });
172
- assert.equal(picked[0].id, thesis.id);
173
- assert.ok(picked.some((m) => m.id === plugin.id));
174
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHotMemory, estimateTokens } from "../src/hot-memory.js";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createVectorIndex } from "../src/vector-index.js";
7
+
8
+ // --- hot memory buffer ---
9
+
10
+ test("hot memory keeps the latest rounds within maxRounds", () => {
11
+ const hot = createHotMemory({ maxRounds: 2, maxTokens: 10000 });
12
+ hot.add({ query: "第一轮", response: "答一" });
13
+ hot.add({ query: "第二轮", response: "答二" });
14
+ hot.add({ query: "第三轮", response: "答三" });
15
+ assert.equal(hot.rounds().length, 2);
16
+ assert.ok(hot.getContext().includes("第三轮"));
17
+ assert.ok(!hot.getContext().includes("第一轮"));
18
+ });
19
+
20
+ test("hot memory enforces the token budget", () => {
21
+ const hot = createHotMemory({ maxRounds: 10, maxTokens: 30 });
22
+ hot.add({ query: "很长的第一轮问题".repeat(10), response: "很长的回答".repeat(10) });
23
+ hot.add({ query: "第二轮", response: "答二" });
24
+ // The first round alone blows the budget; the newest round survives and
25
+ // the buffer never empties completely.
26
+ const rounds = hot.rounds();
27
+ assert.ok(rounds.length >= 1);
28
+ assert.equal(rounds[rounds.length - 1].query, "第二轮");
29
+ });
30
+
31
+ test("hot memory getContext uses the Q/A round format", () => {
32
+ const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
33
+ hot.add({ query: "Q1", response: "A1" });
34
+ hot.add({ query: "Q2", response: "A2" });
35
+ assert.equal(hot.getContext(), "Q: Q1\nA: A1\n\nQ: Q2\nA: A2");
36
+ });
37
+
38
+ test("hot memory ignores empty rounds and clears", () => {
39
+ const hot = createHotMemory({ maxRounds: 5, maxTokens: 10000 });
40
+ hot.add({ query: "", response: "x" });
41
+ hot.add(null);
42
+ assert.equal(hot.rounds().length, 0);
43
+ hot.add({ query: "q" });
44
+ hot.clear();
45
+ assert.equal(hot.getContext(), "");
46
+ });
47
+
48
+ test("estimateTokens counts CJK heavier than ASCII", () => {
49
+ assert.ok(estimateTokens("中文内容") > estimateTokens("abcd"));
50
+ });
51
+
52
+ // --- entry defense: non-positive / non-integer bounds fall back to defaults ---
53
+ // Bug: createHotMemory({ maxRounds: -1 }) made the eviction while-loop
54
+ // `while (buffer.length > maxRounds)` unbounded — after the buffer emptied,
55
+ // `0 > -1` stayed true and buffer.shift() on an empty array is a no-op, so
56
+ // every add() spun forever. Non-integer values (1.5, NaN, null) were also
57
+ // silently wrong. The fix clamps them to the 5/2000 defaults at the door.
58
+
59
+ test("hot memory falls back to maxRounds=5 for non-positive/invalid values", () => {
60
+ for (const bad of [0, -1, 1.5, NaN, null]) {
61
+ const hot = createHotMemory({ maxRounds: bad, maxTokens: 10000 });
62
+ for (let i = 0; i < 8; i++) hot.add({ query: `第${i}轮`, response: "x" });
63
+ assert.equal(hot.rounds().length, 5, `maxRounds=${bad} must fall back to 5, no infinite loop`);
64
+ assert.ok(hot.getContext().includes("第7轮"), `maxRounds=${bad}: newest round survives`);
65
+ assert.ok(!hot.getContext().includes("第0轮"), `maxRounds=${bad}: oldest round evicted`);
66
+ }
67
+ });
68
+
69
+ test("hot memory falls back to maxTokens=2000 for non-positive/infinite values", () => {
70
+ for (const bad of [0, -1, Infinity]) {
71
+ const hot = createHotMemory({ maxRounds: 50, maxTokens: bad });
72
+ // 50 rounds at ~74 tokens each blow a 2000-token budget; the fallback must
73
+ // evict into (1, 50). A broken budget of 0/-1 would squeeze to 1 round and
74
+ // Infinity would keep all 50 — both are the pre-fix behavior.
75
+ for (let i = 0; i < 50; i++) hot.add({ query: `第${i}轮`, response: "长回答".repeat(40) });
76
+ const n = hot.rounds().length;
77
+ assert.ok(n > 1 && n < 50, `maxTokens=${bad} falls back to 2000 (kept ${n} rounds)`);
78
+ }
79
+ });
80
+
81
+ // --- service-level: BM25 fusion + semantic dedup + selective injection ---
82
+
83
+ function toyVec(text) {
84
+ const v = new Array(64).fill(0);
85
+ for (const t of String(text).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean)) {
86
+ let h = 0;
87
+ for (const ch of t) h = (h * 31 + ch.codePointAt(0)) >>> 0;
88
+ v[h % 64] += 1;
89
+ }
90
+ const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
91
+ return v.map((x) => x / norm);
92
+ }
93
+
94
+ function setup(overrides = {}) {
95
+ const store = createStore(":memory:");
96
+ const config = {
97
+ entitySearchEnabled: false,
98
+ bm25SearchEnabled: true,
99
+ adaptiveThresholdEnabled: false,
100
+ searchSemanticDedup: true,
101
+ selectiveInjectEnabled: true,
102
+ ...overrides
103
+ };
104
+ const service = createService({ store, mirror: null, config, logger: null });
105
+ service.setVectorIndex(createVectorIndex({ store, logger: null }));
106
+ service.setEmbedder({ embedSingle: async (t) => toyVec(t) });
107
+ return { store, service };
108
+ }
109
+
110
+ test("searchMemories fuses BM25: scattered-term queries recall both rows", async () => {
111
+ const { store, service } = setup();
112
+ const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
113
+ const b = store.save({ type: "decision", title: "语言迁移", content: "编译模块迁移到 Rust", importance: 3 });
114
+ store.save({ type: "project", title: "无关", content: "夜间 ETL 脚本", importance: 3 });
115
+
116
+ // "rust 异步" is not a substring of either row — LIKE misses both; BM25
117
+ // must surface both rows in the merged result.
118
+ const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
119
+ const ids = results.map((r) => r.id);
120
+ assert.ok(ids.includes(a.id), "async row must be recalled via BM25");
121
+ assert.ok(ids.includes(b.id), "rust row must be recalled via BM25");
122
+ assert.equal(results.find((r) => r.id === a.id)?.source, "bm25");
123
+ });
124
+
125
+ test("bm25SearchEnabled=false restores the two-path behavior", async () => {
126
+ const { store, service } = setup({ bm25SearchEnabled: false });
127
+ const a = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
128
+ const results = await service.searchMemories("rust 异步", { mode: "auto", topK: 5 });
129
+ assert.ok(!results.some((r) => r.id === a.id), "no BM25 → scattered-term miss is back");
130
+ });
131
+
132
+ test("search-time semantic dedup drops near-identical embeddings", async () => {
133
+ const { store, service } = setup();
134
+ const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
135
+ const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
136
+ store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
137
+ store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
138
+
139
+ // auto (not keyword): keyword mode is the documented text-only path and is
140
+ // exempt from dedup by design; auto exercises the dedup the way production
141
+ // searches run.
142
+ const results = await service.searchMemories("深色主题", { mode: "auto", topK: 5 });
143
+ const ids = results.map((r) => r.id);
144
+ assert.ok(ids.includes(a.id) !== ids.includes(b.id), "one of the near-duplicate pair is dropped");
145
+ });
146
+
147
+ test("searchSemanticDedup=false keeps duplicate embeddings", async () => {
148
+ const { store, service } = setup({ searchSemanticDedup: false });
149
+ const a = store.save({ type: "project", title: "偏好 A", content: "用户喜欢深色主题编辑器", importance: 3 });
150
+ const b = store.save({ type: "project", title: "偏好 A 备份", content: "用户喜欢深色主题编辑器(备份)", importance: 3 });
151
+ store.setEmbedding(a.id, toyVec("用户喜欢深色主题编辑器"));
152
+ store.setEmbedding(b.id, toyVec("用户喜欢深色主题编辑器"));
153
+ const results = await service.searchMemories("深色主题", { mode: "keyword", topK: 5 });
154
+ assert.equal(results.length, 2);
155
+ });
156
+
157
+ test("selective injection re-orders candidates by query similarity", () => {
158
+ const { store, service } = setup();
159
+ const thesis = store.save({ type: "project", title: "湿地论文", content: "毕业论文研究城市湿地公园", importance: 5 });
160
+ const plugin = store.save({ type: "project", title: "插件项目", content: "dsh-mneme 记忆插件开发", importance: 5 });
161
+ store.setEmbedding(thesis.id, toyVec("毕业论文研究城市湿地公园"));
162
+ store.setEmbedding(plugin.id, toyVec("dsh-mneme 记忆插件开发"));
163
+
164
+ // Rule-based order would put both at equal importance; the query vector is
165
+ // about the thesis, so topic ranking must put the thesis memory first.
166
+ const picked = service.injectCandidates({
167
+ query: "论文写作",
168
+ queryVector: toyVec("毕业论文研究城市湿地公园"),
169
+ maxItems: 2,
170
+ threshold: 3
171
+ });
172
+ assert.equal(picked[0].id, thesis.id);
173
+ assert.ok(picked.some((m) => m.id === plugin.id));
174
+ });
@@ -1,103 +1,103 @@
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 { createInjector } from "../src/inject.js";
6
- import { createSettings } from "../src/settings.js";
7
-
8
- function setup(over = {}) {
9
- const store = createStore(":memory:");
10
- const service = createService({ store, mirror: null, config: {} });
11
- const settings = createSettings(store.db);
12
- const contexts = [];
13
- const disposers = [];
14
- const ctx = {
15
- systemPrompt: {
16
- context(def) {
17
- contexts.push(def);
18
- const dispose = () => disposers.push(def.name);
19
- return dispose;
20
- }
21
- }
22
- };
23
- const config = { maxInjectedItems: 3, importanceThreshold: 3, ...over };
24
- const injector = createInjector(ctx, service, settings, config);
25
- return { store, service, contexts, injector, settings };
26
- }
27
-
28
- test("registers memory and user-settings contexts", () => {
29
- const { contexts } = setup();
30
- assert.equal(contexts.length, 2);
31
- assert.equal(contexts[0].name, "memory");
32
- assert.equal(contexts[1].name, "user-settings");
33
- });
34
-
35
- test("context text renders injected memories as markdown block", () => {
36
- const { contexts, service } = setup();
37
- service.saveWithDedupe({ type: "preference", title: "语言", content: "用户用中文交流", importance: 5 });
38
- service.saveWithDedupe({ type: "project", title: "记忆插件", content: "SQLite+Markdown", importance: 4 });
39
- const text = contexts[0].text({});
40
- assert.ok(text.includes("[记忆库]"), "has header");
41
- assert.ok(text.includes("语言"), "includes preference");
42
- assert.ok(text.includes("记忆插件"), "includes high-importance project");
43
- });
44
-
45
- test("returns empty text when nothing qualifies", () => {
46
- const { contexts } = setup();
47
- const text = contexts[0].text({});
48
- assert.equal(text, "");
49
- });
50
-
51
- test("renders summary block first when summary candidate exists", () => {
52
- const { contexts, service } = setup();
53
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "这是总览摘要", importance: 5 });
54
- service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
55
- const text = contexts[0].text({});
56
- const summaryIdx = text.indexOf("这是总览摘要");
57
- const prefIdx = text.indexOf("语言");
58
- assert.ok(summaryIdx !== -1, "summary present");
59
- assert.ok(prefIdx !== -1, "preference present");
60
- assert.ok(summaryIdx < prefIdx, "summary rendered first");
61
- });
62
-
63
- test("user-settings context renders profile and rules, empty when unset", () => {
64
- const { contexts, settings } = setup();
65
- const settingsCtx = contexts.find((c) => c.name === "user-settings");
66
- assert.ok(settingsCtx, "user-settings context registered");
67
- assert.equal(settingsCtx.text({}), "", "empty when no profile/rules");
68
- settings.setProfile("我叫小明,是一名前端开发者");
69
- settings.setRules(["回答时先给结论", "使用简体中文"]);
70
- const text = settingsCtx.text({});
71
- assert.ok(text.includes("用户画像"), "has profile header");
72
- assert.ok(text.includes("前端开发者"), "includes profile");
73
- assert.ok(text.includes("先给结论"), "includes rule");
74
- assert.ok(text.includes("简体中文"), "includes second rule");
75
- });
76
-
77
- test("user-settings context precedes memory block (order 85 < 90)", () => {
78
- const { contexts, settings } = setup();
79
- settings.setProfile("画像");
80
- const settingsCtx = contexts.find((c) => c.name === "user-settings");
81
- assert.ok(settingsCtx.order < contexts.find((c) => c.name === "memory").order);
82
- });
83
-
84
- test("Bug6: long content is truncated to ~300 chars with an ellipsis", () => {
85
- const { contexts, service } = setup();
86
- const longContent = "这是一段非常长的记忆正文".repeat(200); // ~2600 chars
87
- service.saveWithDedupe({ type: "preference", title: "长记忆", content: longContent, importance: 5 });
88
- const text = contexts[0].text({});
89
- assert.ok(text.includes("长记忆"), "memory still rendered");
90
- assert.ok(text.includes("…"), "ellipsis marks the truncation");
91
- assert.ok(!text.includes(longContent.slice(300)), "full body not injected verbatim");
92
- });
93
-
94
- test("Bug6: injected block stays within the ~1500 char budget, later entries collapse", () => {
95
- const { contexts, service } = setup({ maxInjectedItems: 8 });
96
- for (let i = 0; i < 8; i++) {
97
- service.saveWithDedupe({ type: "preference", title: `长标题记忆${i}`, content: "这是一段".repeat(100), importance: 5 });
98
- }
99
- const text = contexts[0].text({});
100
- assert.ok(text.length <= 1600, `memory block bounded near budget, got ${text.length} chars`);
101
- // The first entries render full bodies; every entry is present by title.
102
- for (let i = 0; i < 8; i++) assert.ok(text.includes(`长标题记忆${i}`), `entry ${i} present`);
103
- });
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 { createInjector } from "../src/inject.js";
6
+ import { createSettings } from "../src/settings.js";
7
+
8
+ function setup(over = {}) {
9
+ const store = createStore(":memory:");
10
+ const service = createService({ store, mirror: null, config: {} });
11
+ const settings = createSettings(store.db);
12
+ const contexts = [];
13
+ const disposers = [];
14
+ const ctx = {
15
+ systemPrompt: {
16
+ context(def) {
17
+ contexts.push(def);
18
+ const dispose = () => disposers.push(def.name);
19
+ return dispose;
20
+ }
21
+ }
22
+ };
23
+ const config = { maxInjectedItems: 3, importanceThreshold: 3, ...over };
24
+ const injector = createInjector(ctx, service, settings, config);
25
+ return { store, service, contexts, injector, settings };
26
+ }
27
+
28
+ test("registers memory and user-settings contexts", () => {
29
+ const { contexts } = setup();
30
+ assert.equal(contexts.length, 2);
31
+ assert.equal(contexts[0].name, "memory");
32
+ assert.equal(contexts[1].name, "user-settings");
33
+ });
34
+
35
+ test("context text renders injected memories as markdown block", () => {
36
+ const { contexts, service } = setup();
37
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "用户用中文交流", importance: 5 });
38
+ service.saveWithDedupe({ type: "project", title: "记忆插件", content: "SQLite+Markdown", importance: 4 });
39
+ const text = contexts[0].text({});
40
+ assert.ok(text.includes("[记忆库]"), "has header");
41
+ assert.ok(text.includes("语言"), "includes preference");
42
+ assert.ok(text.includes("记忆插件"), "includes high-importance project");
43
+ });
44
+
45
+ test("returns empty text when nothing qualifies", () => {
46
+ const { contexts } = setup();
47
+ const text = contexts[0].text({});
48
+ assert.equal(text, "");
49
+ });
50
+
51
+ test("renders summary block first when summary candidate exists", () => {
52
+ const { contexts, service } = setup();
53
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "这是总览摘要", importance: 5 });
54
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
55
+ const text = contexts[0].text({});
56
+ const summaryIdx = text.indexOf("这是总览摘要");
57
+ const prefIdx = text.indexOf("语言");
58
+ assert.ok(summaryIdx !== -1, "summary present");
59
+ assert.ok(prefIdx !== -1, "preference present");
60
+ assert.ok(summaryIdx < prefIdx, "summary rendered first");
61
+ });
62
+
63
+ test("user-settings context renders profile and rules, empty when unset", () => {
64
+ const { contexts, settings } = setup();
65
+ const settingsCtx = contexts.find((c) => c.name === "user-settings");
66
+ assert.ok(settingsCtx, "user-settings context registered");
67
+ assert.equal(settingsCtx.text({}), "", "empty when no profile/rules");
68
+ settings.setProfile("我叫小明,是一名前端开发者");
69
+ settings.setRules(["回答时先给结论", "使用简体中文"]);
70
+ const text = settingsCtx.text({});
71
+ assert.ok(text.includes("用户画像"), "has profile header");
72
+ assert.ok(text.includes("前端开发者"), "includes profile");
73
+ assert.ok(text.includes("先给结论"), "includes rule");
74
+ assert.ok(text.includes("简体中文"), "includes second rule");
75
+ });
76
+
77
+ test("user-settings context precedes memory block (order 85 < 90)", () => {
78
+ const { contexts, settings } = setup();
79
+ settings.setProfile("画像");
80
+ const settingsCtx = contexts.find((c) => c.name === "user-settings");
81
+ assert.ok(settingsCtx.order < contexts.find((c) => c.name === "memory").order);
82
+ });
83
+
84
+ test("Bug6: long content is truncated to ~300 chars with an ellipsis", () => {
85
+ const { contexts, service } = setup();
86
+ const longContent = "这是一段非常长的记忆正文".repeat(200); // ~2600 chars
87
+ service.saveWithDedupe({ type: "preference", title: "长记忆", content: longContent, importance: 5 });
88
+ const text = contexts[0].text({});
89
+ assert.ok(text.includes("长记忆"), "memory still rendered");
90
+ assert.ok(text.includes("…"), "ellipsis marks the truncation");
91
+ assert.ok(!text.includes(longContent.slice(300)), "full body not injected verbatim");
92
+ });
93
+
94
+ test("Bug6: injected block stays within the ~1500 char budget, later entries collapse", () => {
95
+ const { contexts, service } = setup({ maxInjectedItems: 8 });
96
+ for (let i = 0; i < 8; i++) {
97
+ service.saveWithDedupe({ type: "preference", title: `长标题记忆${i}`, content: "这是一段".repeat(100), importance: 5 });
98
+ }
99
+ const text = contexts[0].text({});
100
+ assert.ok(text.length <= 1600, `memory block bounded near budget, got ${text.length} chars`);
101
+ // The first entries render full bodies; every entry is present by title.
102
+ for (let i = 0; i < 8; i++) assert.ok(text.includes(`长标题记忆${i}`), `entry ${i} present`);
103
+ });