@modusensus/dsh-mneme 0.6.7 → 0.6.9

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