@modusensus/dsh-mneme 0.8.14 → 0.8.16

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 (279) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +660 -654
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +691 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -151
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +275 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/DISTILL.md +162 -0
  12. package/docs/ENTITIES.md +245 -0
  13. package/docs/LOCAL_MODEL.md +222 -0
  14. package/docs/SEMANTIC.md +256 -0
  15. package/docs/SLEEP.md +164 -0
  16. package/docs/STORAGE.md +98 -0
  17. package/lib/api-standalone.js +656 -673
  18. package/lib/api.js +1605 -1433
  19. package/lib/bootstrap.js +211 -211
  20. package/lib/client.js +6354 -5296
  21. package/lib/commands.js +95 -95
  22. package/lib/config.js +947 -843
  23. package/lib/content-hash.js +54 -54
  24. package/lib/continuity.js +220 -220
  25. package/lib/document-index.js +94 -94
  26. package/lib/document.js +303 -303
  27. package/lib/dream/clustering.js +118 -118
  28. package/lib/dream/decisions.js +694 -674
  29. package/lib/dream/narratives.js +44 -44
  30. package/lib/dream/sleep.js +819 -819
  31. package/lib/dream.js +1503 -1501
  32. package/lib/embedding.js +177 -177
  33. package/lib/entities/extractor.js +252 -252
  34. package/lib/graph/anchoring.js +179 -179
  35. package/lib/guide.js +74 -74
  36. package/lib/heat.js +144 -144
  37. package/lib/hot-memory.js +108 -46
  38. package/lib/index.js +552 -503
  39. package/lib/inject.js +428 -450
  40. package/lib/lang.js +248 -229
  41. package/lib/local-embedder.js +358 -358
  42. package/lib/maintenance.js +162 -142
  43. package/lib/mirror.js +330 -330
  44. package/lib/organize.js +450 -450
  45. package/lib/peak-hours.js +117 -117
  46. package/lib/placement.js +13 -0
  47. package/lib/pre-inject-gate.js +340 -0
  48. package/lib/quality-filter.js +126 -126
  49. package/lib/recall-stats.js +190 -175
  50. package/lib/reclaim-http.js +150 -0
  51. package/lib/reranker.js +269 -269
  52. package/lib/runtime/adopt.js +176 -176
  53. package/lib/runtime/closure.js +172 -172
  54. package/lib/runtime/download.js +247 -247
  55. package/lib/runtime/layout.js +265 -265
  56. package/lib/runtime/loader.js +252 -252
  57. package/lib/runtime/model-fetch.js +361 -361
  58. package/lib/runtime/provision.js +237 -237
  59. package/lib/runtime/tarball.js +130 -130
  60. package/lib/runtime/verify.js +223 -204
  61. package/lib/safe-slice.js +18 -0
  62. package/lib/scope.js +146 -146
  63. package/lib/search/adaptive.js +60 -60
  64. package/lib/search/bm25.js +96 -96
  65. package/lib/semantic.js +229 -229
  66. package/lib/sensitive-scan.js +209 -209
  67. package/lib/serve.js +215 -215
  68. package/lib/service.js +2688 -2605
  69. package/lib/settings.js +528 -511
  70. package/lib/store.js +3196 -3007
  71. package/lib/summarize.js +1039 -856
  72. package/lib/tools.js +743 -737
  73. package/lib/vector-index.js +110 -110
  74. package/lib/version-check.js +122 -122
  75. package/lib/write-admission.js +402 -402
  76. package/locale/en.json +6 -6
  77. package/locale/zh.json +6 -6
  78. package/package.json +118 -118
  79. package/runtime-manifest.json +526 -526
  80. package/scripts/benchmark-embed.js +201 -201
  81. package/scripts/benchmark-recall.js +249 -249
  82. package/scripts/benchmark-rerank.js +166 -166
  83. package/scripts/build-runtime-manifest.mjs +224 -224
  84. package/scripts/changelog-prep.mjs +36 -36
  85. package/scripts/check-sync.js +42 -42
  86. package/scripts/e2e-dsh.js +220 -220
  87. package/scripts/mneme-runtime.mjs +277 -277
  88. package/scripts/stress-dsh.js +255 -255
  89. package/scripts/sync-lib.js +47 -47
  90. package/scripts/sync-test-badge.mjs +69 -69
  91. package/scripts/test-count-sync.mjs +44 -44
  92. package/src/api-standalone.js +656 -673
  93. package/src/api.js +1605 -1433
  94. package/src/bootstrap.js +211 -211
  95. package/src/commands.js +95 -95
  96. package/src/config.js +947 -843
  97. package/src/content-hash.js +54 -54
  98. package/src/continuity.js +220 -220
  99. package/src/document-index.js +94 -94
  100. package/src/document.js +303 -303
  101. package/src/dream/clustering.js +118 -118
  102. package/src/dream/decisions.js +694 -674
  103. package/src/dream/narratives.js +44 -44
  104. package/src/dream/sleep.js +819 -819
  105. package/src/dream.js +1503 -1501
  106. package/src/embedding.js +177 -177
  107. package/src/entities/extractor.js +252 -252
  108. package/src/graph/anchoring.js +179 -179
  109. package/src/guide.js +74 -74
  110. package/src/heat.js +144 -144
  111. package/src/hot-memory.js +108 -46
  112. package/src/index.js +552 -503
  113. package/src/inject.js +428 -450
  114. package/src/lang.js +248 -229
  115. package/src/local-embedder.js +358 -358
  116. package/src/maintenance.js +162 -142
  117. package/src/mirror.js +330 -330
  118. package/src/organize.js +450 -450
  119. package/src/peak-hours.js +117 -117
  120. package/src/placement.js +13 -0
  121. package/src/pre-inject-gate.js +340 -0
  122. package/src/quality-filter.js +126 -126
  123. package/src/recall-stats.js +190 -175
  124. package/src/reclaim-http.js +150 -0
  125. package/src/reranker.js +269 -269
  126. package/src/runtime/adopt.js +176 -176
  127. package/src/runtime/closure.js +172 -172
  128. package/src/runtime/download.js +247 -247
  129. package/src/runtime/layout.js +265 -265
  130. package/src/runtime/loader.js +252 -252
  131. package/src/runtime/model-fetch.js +361 -361
  132. package/src/runtime/provision.js +237 -237
  133. package/src/runtime/tarball.js +130 -130
  134. package/src/runtime/verify.js +223 -204
  135. package/src/safe-slice.js +18 -0
  136. package/src/scope.js +146 -146
  137. package/src/search/adaptive.js +60 -60
  138. package/src/search/bm25.js +96 -96
  139. package/src/semantic.js +229 -229
  140. package/src/sensitive-scan.js +209 -209
  141. package/src/serve.js +215 -215
  142. package/src/service.js +2688 -2605
  143. package/src/settings.js +528 -511
  144. package/src/store.js +3196 -3007
  145. package/src/summarize.js +1039 -856
  146. package/src/tools.js +743 -737
  147. package/src/vector-index.js +110 -110
  148. package/src/version-check.js +122 -122
  149. package/src/write-admission.js +402 -402
  150. package/test/adaptive-inject-budget.test.js +85 -85
  151. package/test/api-routes-gaps.test.js +899 -218
  152. package/test/api.test.js +1725 -1690
  153. package/test/audit.test.js +448 -448
  154. package/test/baseline-persist.test.js +248 -248
  155. package/test/benchmark.test.js +94 -94
  156. package/test/bootstrap.test.js +220 -220
  157. package/test/changelog-prep.test.js +60 -60
  158. package/test/client.test.js +1582 -1169
  159. package/test/clustering.test.js +100 -100
  160. package/test/commands.test.js +106 -106
  161. package/test/config.test.js +66 -66
  162. package/test/conflict-freeze.test.js +300 -300
  163. package/test/content-hash.test.js +204 -204
  164. package/test/continuity.test.js +333 -333
  165. package/test/contrast.test.js +314 -0
  166. package/test/document-dir.test.js +233 -233
  167. package/test/document.test.js +671 -671
  168. package/test/dream-archive-guardrail.test.js +116 -116
  169. package/test/dream-candidate-hybrid.test.js +281 -281
  170. package/test/dream-coverage-degrade.test.js +86 -86
  171. package/test/dream-failure-backoff.test.js +173 -173
  172. package/test/dream-merge-guardrail.test.js +219 -0
  173. package/test/dream-peak-hours.test.js +194 -194
  174. package/test/dream.test.js +1385 -1383
  175. package/test/embedding-ready.test.js +196 -196
  176. package/test/entities.test.js +627 -547
  177. package/test/entity-recall.test.js +179 -179
  178. package/test/epistemic.test.js +325 -325
  179. package/test/fnew-0112.test.js +311 -311
  180. package/test/fnew-03.test.js +422 -422
  181. package/test/graph-anchoring.test.js +184 -184
  182. package/test/graph-api.test.js +175 -175
  183. package/test/graph-inject-budget.test.js +103 -103
  184. package/test/graph-passive-confirm.test.js +91 -91
  185. package/test/graph-weight-evolution.test.js +104 -104
  186. package/test/heat.test.js +175 -175
  187. package/test/helpers/dream-mock.js +82 -82
  188. package/test/helpers/peer-worker.mjs +25 -25
  189. package/test/helpers/runtime-source.js +60 -60
  190. package/test/helpers/tar-builder.js +80 -80
  191. package/test/helpers/write-admission-samples.js +308 -308
  192. package/test/hot-memory.test.js +211 -145
  193. package/test/inject-content-cap.test.js +91 -91
  194. package/test/inject-first-round-bm25.test.js +89 -89
  195. package/test/inject-heat.test.js +77 -77
  196. package/test/inject-parent-gate.test.js +106 -106
  197. package/test/inject-pools.test.js +194 -194
  198. package/test/inject-recall.test.js +144 -105
  199. package/test/inject-rotation.test.js +161 -161
  200. package/test/inject.test.js +443 -420
  201. package/test/lang.test.js +87 -87
  202. package/test/lastrunat-persist.test.js +101 -101
  203. package/test/lib-smoke.test.js +96 -96
  204. package/test/llm-audit.test.js +696 -598
  205. package/test/llm-message-source.test.js +207 -207
  206. package/test/local-embedder.test.js +292 -292
  207. package/test/maintenance.test.js +501 -391
  208. package/test/mcp-stdio.test.js +385 -385
  209. package/test/mirror-dirty.test.js +424 -424
  210. package/test/mirror-edit-digest.test.js +187 -187
  211. package/test/mirror-generation.test.js +499 -499
  212. package/test/mirror-types.test.js +208 -208
  213. package/test/mirror.test.js +249 -249
  214. package/test/narrative-bars.test.js +162 -162
  215. package/test/organize.test.js +418 -418
  216. package/test/peer-blockers.test.js +193 -193
  217. package/test/placement.test.js +36 -0
  218. package/test/policy-epoch.test.js +259 -259
  219. package/test/pre-inject-gate.test.js +444 -0
  220. package/test/quality-filter.test.js +186 -186
  221. package/test/reasoning-effort.test.js +752 -752
  222. package/test/recall-anti-update.test.js +82 -82
  223. package/test/recall-evals.test.js +253 -253
  224. package/test/recall-layer.test.js +326 -326
  225. package/test/recall-stats.test.js +274 -189
  226. package/test/receipt-chain.test.js +451 -451
  227. package/test/reclaim-http.test.js +209 -0
  228. package/test/reflection.test.js +226 -226
  229. package/test/reindex-backfill.test.js +62 -62
  230. package/test/reranker-single-logit.test.js +73 -73
  231. package/test/reranker.test.js +197 -197
  232. package/test/resident-status.test.js +83 -83
  233. package/test/runtime-adopt.test.js +206 -206
  234. package/test/runtime-cli.test.js +89 -89
  235. package/test/runtime-closure.test.js +193 -193
  236. package/test/runtime-download.test.js +302 -302
  237. package/test/runtime-layout.test.js +163 -163
  238. package/test/runtime-loader.test.js +255 -255
  239. package/test/runtime-manifest.test.js +159 -159
  240. package/test/runtime-model-fetch.test.js +348 -348
  241. package/test/runtime-provision.test.js +101 -101
  242. package/test/runtime-tarball.test.js +81 -81
  243. package/test/runtime-verify.test.js +319 -279
  244. package/test/scope-candidates.test.js +239 -239
  245. package/test/scope-explicit.test.js +452 -452
  246. package/test/scope-inject-soft.test.js +106 -106
  247. package/test/scope-retrieval.test.js +197 -197
  248. package/test/scope-storage.test.js +255 -255
  249. package/test/scope-strict.test.js +367 -367
  250. package/test/search-fusion.test.js +90 -90
  251. package/test/semantic.test.js +124 -124
  252. package/test/sensitive-scan.test.js +207 -207
  253. package/test/serve-bin.test.js +121 -121
  254. package/test/serve.test.js +196 -196
  255. package/test/service-search.test.js +174 -174
  256. package/test/service.test.js +410 -405
  257. package/test/settings.test.js +269 -261
  258. package/test/skip-invalid-restore.test.js +262 -262
  259. package/test/sleep-action-set.test.js +422 -422
  260. package/test/sleep-heat.test.js +126 -126
  261. package/test/sleep-scheduler-rearm.test.js +89 -89
  262. package/test/sleep.test.js +527 -527
  263. package/test/standalone-api.test.js +751 -751
  264. package/test/store-vector-cache.test.js +98 -98
  265. package/test/store.test.js +504 -396
  266. package/test/stress.test.js +209 -209
  267. package/test/summarize-occurred-at.test.js +127 -0
  268. package/test/summarize-reasoning-effort.test.js +189 -189
  269. package/test/summarize.test.js +1639 -1465
  270. package/test/supersede-state-tracking.test.js +394 -0
  271. package/test/test-count-sync.test.js +60 -60
  272. package/test/tools-dto-schema-matrix.test.js +325 -325
  273. package/test/tools-memory-get-schema.test.js +65 -65
  274. package/test/tools.test.js +428 -374
  275. package/test/updated-at-semantics.test.js +113 -113
  276. package/test/vector-index.test.js +221 -221
  277. package/test/version-check.test.js +152 -152
  278. package/test/webServer-optional.test.js +82 -82
  279. package/test/write-admission.test.js +668 -668
@@ -1,405 +1,410 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { createStore } from "../src/store.js";
7
- import { createService } from "../src/service.js";
8
- import { createMirror } from "../src/mirror.js";
9
-
10
- function setup() {
11
- const store = createStore(":memory:");
12
- const service = createService({ store, mirror: null, config: {} });
13
- return { store, service };
14
- }
15
-
16
- test("saveWithDedupe adds new memory when no similar exists", () => {
17
- const { store, service } = setup();
18
- const result = service.saveWithDedupe({
19
- type: "project",
20
- title: "记忆插件",
21
- content: "正在开发 dsh-mneme,SQLite+Markdown",
22
- importance: 4
23
- });
24
- assert.equal(result.action, "created");
25
- assert.equal(store.count(), 1);
26
- });
27
-
28
- test("saveWithDedupe merges into existing on exact title match", () => {
29
- const { store, service } = setup();
30
- service.saveWithDedupe({ type: "project", title: "记忆插件", content: "旧内容", importance: 3 });
31
- const result = service.saveWithDedupe({ type: "project", title: "记忆插件", content: "新内容", importance: 5 });
32
- assert.equal(result.action, "merged");
33
- assert.equal(store.count(), 1);
34
- const all = store.all();
35
- // Bug5: same-title merge appends under a timestamped `---` separator instead
36
- // of overwriting; the previous content is archived into content_history.
37
- assert.ok(all[0].content.includes("旧内容"), "old content preserved in appended body");
38
- assert.ok(all[0].content.includes("新内容"), "new content appended");
39
- assert.ok(all[0].content.includes("---"), "timestamped separator present");
40
- assert.equal(all[0].importance, 5, "importance takes the max of both");
41
- assert.equal(all[0].content_history.length, 1, "old content archived to history");
42
- assert.equal(all[0].content_history[0].content, "旧内容");
43
- assert.equal(all[0].content_history[0].source, "auto_merge");
44
- });
45
-
46
- test("injectCandidates returns preferences + high-importance items within limit", () => {
47
- const { service } = setup();
48
- for (let i = 0; i < 3; i++) service.saveWithDedupe({ type: "preference", title: `p${i}`, content: "偏好" });
49
- service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
50
- service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
51
- service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
52
- const candidates = service.injectCandidates({ maxItems: 5, threshold: 4 });
53
- const types = candidates.map((c) => c.type);
54
- assert.ok(types.includes("preference"), "preferences included");
55
- assert.ok(types.includes("project"), "high-importance project included");
56
- assert.ok(!types.includes("history"), "history excluded by default");
57
- assert.ok(candidates.length <= 5, "respects maxItems");
58
- });
59
-
60
- test("mergeHumanEdits applies human content over machine", () => {
61
- const { store, service } = setup();
62
- const saved = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
63
- const edits = [{ id: saved.memory.id, title: "语言", content: "人类编辑内容" }];
64
- service.mergeHumanEdits("preference", edits);
65
- const got = store.getById(saved.memory.id);
66
- assert.equal(got.content, "人类编辑内容");
67
- });
68
-
69
- test("toApiList maps store rows to wire DTOs", () => {
70
- const { service } = setup();
71
- const saved = service.saveWithDedupe({ type: "decision", title: "选型", content: "node:sqlite", importance: 3 });
72
- const dto = service.toApiList([saved.memory]);
73
- assert.deepEqual(Object.keys(dto[0]).sort(), ["id", "type", "title", "content", "tags", "importance", "source", "created_at", "updated_at"].sort());
74
- assert.equal(dto[0].id, saved.memory.id);
75
- assert.equal(dto[0].type, "decision");
76
- assert.equal(dto[0].title, "选型");
77
- assert.equal(dto[0].content, "node:sqlite");
78
- assert.equal(dto[0].importance, 3);
79
- });
80
-
81
- test("mergeHumanEdits skips edits without id and keeps applying the rest", () => {
82
- const { store, service } = setup();
83
- const first = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
84
- const second = service.saveWithDedupe({ type: "preference", title: "主题", content: "机器内容" });
85
- const edits = [
86
- { content: "缺少 id 的损坏条目" },
87
- { id: first.memory.id, title: "语言", content: "人类编辑内容" },
88
- { id: second.memory.id, title: "主题", content: "第二个人类编辑" }
89
- ];
90
- const applied = service.mergeHumanEdits("preference", edits);
91
- assert.equal(applied, 2, "returns count of applied edits, not input length");
92
- assert.equal(store.getById(first.memory.id).content, "人类编辑内容");
93
- assert.equal(store.getById(second.memory.id).content, "第二个人类编辑");
94
- });
95
-
96
- test("mutations through passthroughs sync mirror; forgotten entries stay out of it", () => {
97
- const store = createStore(":memory:");
98
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
99
- const mirror = createMirror(dir);
100
- const service = createService({ store, mirror, config: {} });
101
- try {
102
- const saved = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
103
- assert.ok(existsSync(join(dir, "projects.md")), "mirror written on save");
104
-
105
- service.update(saved.memory.id, { content: "a2" });
106
- assert.match(readFileSync(join(dir, "projects.md"), "utf8"), /a2/, "update re-syncs mirror");
107
-
108
- service.setForget(saved.memory.id, true);
109
- assert.ok(!existsSync(join(dir, "projects.md")), "forgotten entry removed from mirror");
110
-
111
- const second = service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
112
- assert.ok(existsSync(join(dir, "projects.md")), "mirror rewritten after re-save");
113
- service.remove(second.memory.id);
114
- assert.ok(!existsSync(join(dir, "projects.md")), "remove re-syncs mirror");
115
- } finally {
116
- rmSync(dir, { recursive: true, force: true });
117
- }
118
- });
119
-
120
- test("saveWithDedupe created branch keeps forgotten entries out of mirror", () => {
121
- const store = createStore(":memory:");
122
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
123
- const mirror = createMirror(dir);
124
- const service = createService({ store, mirror, config: {} });
125
- try {
126
- const a = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
127
- service.setForget(a.memory.id, true);
128
- service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
129
- const text = readFileSync(join(dir, "projects.md"), "utf8");
130
- assert.ok(!text.includes(a.memory.id), "forgotten A must not reappear in mirror");
131
- assert.ok(!text.includes("## A"), "forgotten A entry absent from mirror");
132
- assert.match(text, /## B/, "non-forgotten B present in mirror");
133
- } finally {
134
- rmSync(dir, { recursive: true, force: true });
135
- }
136
- });
137
-
138
- test("injectCandidates excludes archived entries", () => {
139
- const { store, service } = setup();
140
- const saved = service.saveWithDedupe({ type: "preference", title: "旧偏好", content: "old", importance: 5 });
141
- store.setArchived(saved.memory.id, true);
142
- const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
143
- assert.ok(!candidates.some((c) => c.id === saved.memory.id), "archived excluded");
144
- });
145
-
146
- test("summary memory is a candidate at top priority", () => {
147
- const { service } = setup();
148
- service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
149
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览内容", importance: 5 });
150
- const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
151
- assert.equal(candidates[0]?.type, "summary", "summary first even with competing high-importance preference");
152
- });
153
-
154
- test("write methods invoke onWrite hook when provided", () => {
155
- const { store } = setup();
156
- let called = 0;
157
- const svc = createService({ store, mirror: null, config: {}, onWrite: () => { called++; } });
158
- svc.saveWithDedupe({ type: "project", title: "a", content: "x" });
159
- assert.equal(called, 1, "saveWithDedupe hooks");
160
- svc.update(svc.all()[0].id, { content: "y" });
161
- assert.equal(called, 2, "update hooks");
162
- svc.setArchived(svc.all()[0].id, true);
163
- assert.equal(called, 2, "setArchived does not hook (not a content write)");
164
- });
165
-
166
- // --- transactions (item ②) + compare-and-set (item ①/③) --------------------
167
-
168
- test("service.transaction rolls back every step when the body throws", () => {
169
- const { store, service } = setup();
170
- let threw = false;
171
- try {
172
- service.transaction(() => {
173
- service.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
174
- service.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
175
- throw new Error("boom");
176
- });
177
- } catch { threw = true; }
178
- assert.equal(threw, true, "error propagates");
179
- assert.equal(store.count(), 0, "no partial writes after rollback");
180
- assert.ok(!store.all().some((m) => m.title === "原子A"), "step A rolled back");
181
- assert.ok(!store.all().some((m) => m.title === "原子B"), "step B rolled back");
182
- store.close();
183
- });
184
-
185
- test("service.transaction commits all steps atomically on success", () => {
186
- const { store, service } = setup();
187
- service.transaction(() => {
188
- service.saveWithDedupe({ type: "project", title: "甲", content: "x" });
189
- service.saveWithDedupe({ type: "project", title: "乙", content: "y" });
190
- });
191
- assert.equal(store.count(), 2, "both steps committed");
192
- store.close();
193
- });
194
-
195
- test("service.compareAndUpdate rejects a stale version token (no lost update)", () => {
196
- const { store, service } = setup();
197
- const { memory: m } = service.saveWithDedupe({ type: "history", title: "计数器", content: "count=0" });
198
- const baseline = service.getById(m.id);
199
- const first = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=1" });
200
- assert.ok(first, "current version CAS succeeds");
201
- const stale = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=2" });
202
- assert.equal(stale, undefined, "stale version CAS misses without writing");
203
- assert.equal(service.getById(m.id).content, "count=1", "increment not lost");
204
- store.close();
205
- });
206
-
207
- // --- Bug4: injectCandidates semantic-first recall (query) --------------------
208
-
209
- test("Bug4: injectCandidates with an empty query keeps the legacy rule-based selection", () => {
210
- const { service } = setup();
211
- service.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
212
- service.saveWithDedupe({ type: "preference", title: "p1", content: "偏好" });
213
- service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
214
- service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
215
- service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
216
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
217
- const legacy = service.injectCandidates({ maxItems: 5, threshold: 4 });
218
- const noQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: "" });
219
- const blankQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: " " });
220
- assert.deepEqual(noQuery.map((c) => c.id), legacy.map((c) => c.id), "empty query behaves identically to the old logic");
221
- assert.deepEqual(blankQuery.map((c) => c.id), legacy.map((c) => c.id), "whitespace-only query degrades too");
222
- assert.equal(legacy[0].type, "summary", "summary still leads");
223
- assert.ok(!legacy.some((c) => c.type === "history"), "history still excluded");
224
- });
225
-
226
- test("Bug4: injectCandidates ignores the query when hybridInject is disabled", () => {
227
- const { store } = setup();
228
- const svc = createService({ store, mirror: null, config: { hybridInject: false } });
229
- svc.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
230
- svc.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
231
- const noQuery = svc.injectCandidates({ maxItems: 5, threshold: 3 });
232
- const withQuery = svc.injectCandidates({ maxItems: 5, threshold: 3, query: "中文" });
233
- assert.deepEqual(withQuery.map((c) => c.id), noQuery.map((c) => c.id), "hybridInject off keeps rule-based ordering");
234
- });
235
-
236
- // --- Bug5: content_history FIFO + human-edited direct overwrite --------------
237
-
238
- test("Bug5: content_history grows FIFO across repeated same-title merges (capped at 20)", () => {
239
- const { store, service } = setup();
240
- service.saveWithDedupe({ type: "project", title: "流水", content: "v0" });
241
- for (let i = 1; i <= 25; i++) {
242
- service.saveWithDedupe({ type: "project", title: "流水", content: `v${i}` });
243
- }
244
- const row = store.all()[0];
245
- assert.ok(Array.isArray(row.content_history), "content_history is an array");
246
- assert.equal(row.content_history.length, 20, "FIFO cap of 20 respected");
247
- assert.ok(row.content_history[0].content.includes("v24"), "newest archived body kept at index 0");
248
- assert.ok(row.content_history[19].content.includes("v5"), "oldest kept entry");
249
- assert.ok(!row.content_history[19].content.includes("v6"), "entries older than the cap dropped");
250
- assert.ok(row.content.includes("v25"), "latest merge still appended to the live body");
251
- });
252
-
253
- test("Bug5: _humanEdited overwrite replaces content directly and archives the old version", () => {
254
- const { store, service } = setup();
255
- service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
256
- const result = service.saveWithDedupe({ type: "preference", title: "语言", content: "人工修正", _humanEdited: true });
257
- const row = store.getById(result.memory.id);
258
- assert.equal(row.content, "人工修正", "direct overwrite, no appended --- block");
259
- assert.ok(!row.content.includes("机器内容"), "old content not in the live body");
260
- assert.equal(row.content_history.length, 1);
261
- assert.equal(row.content_history[0].content, "机器内容");
262
- assert.equal(row.content_history[0].source, "human_override");
263
- });
264
-
265
- // --- Bug7: memory quality filter ---------------------------------------------
266
-
267
- function qualitySetup(config = {}) {
268
- const store = createStore(":memory:");
269
- const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true, ...config } } });
270
- return { store, service };
271
- }
272
-
273
- test("Bug7: meta-memory is scored below the degrade threshold but still stored", () => {
274
- const { store, service } = qualitySetup();
275
- const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
276
- assert.equal(result.action, "created");
277
- assert.ok(result.memory.quality_score < 60, `meta-memory degraded, got ${result.memory.quality_score}`);
278
- assert.ok(result.memory.quality_score >= 30, "still above the archive threshold");
279
- assert.equal(result.memory.archived, false, "not archived");
280
- assert.equal(store.count(), 1, "still stored and searchable");
281
- });
282
-
283
- test("Bug7: short content is archived and tagged low_quality", () => {
284
- const { store, service } = qualitySetup();
285
- const result = service.saveWithDedupe({ type: "project", title: "备忘", content: "x" });
286
- const row = store.getById(result.memory.id);
287
- assert.equal(row.archived, true, "short content archived");
288
- assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
289
- assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
290
- });
291
-
292
- test("Bug7: near-duplicate content is archived and tagged low_quality", () => {
293
- const { store, service } = qualitySetup();
294
- const base = "今天下午去操场跑步三圈然后回来洗澡";
295
- service.saveWithDedupe({ type: "history", title: "记录A", content: base });
296
- const result = service.saveWithDedupe({ type: "history", title: "记录B", content: `${base}${base}${base}` });
297
- const row = store.getById(result.memory.id);
298
- assert.equal(row.archived, true, "near-duplicate archived");
299
- assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
300
- assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
301
- });
302
-
303
- test("Bug7: repetitive (dedup<0.3) content is scored into the degraded band", () => {
304
- const { store, service } = qualitySetup();
305
- const result = service.saveWithDedupe({ type: "history", title: "唠叨", content: "好好好好好好好好好好好好好好好好好好" });
306
- const row = store.getById(result.memory.id);
307
- assert.ok(row.quality_score >= 30 && row.quality_score < 60, `repetitive-only degraded, got ${row.quality_score}`);
308
- assert.equal(row.archived, false, "not archived (only a single non-meta signal)");
309
- });
310
-
311
- test("Bug7: memoryQualityFilter.enabled=false skips scoring entirely", () => {
312
- const store = createStore(":memory:");
313
- const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: false } } });
314
- const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
315
- const row = store.getById(result.memory.id);
316
- assert.ok(row.quality_score == null, "no quality_score written");
317
- assert.equal(row.archived, false, "not archived");
318
- assert.ok(!(row.tags ?? []).includes("low_quality"), "no low_quality tag");
319
- });
320
-
321
- test("Bug7: injection ranking re-weights by quality_score (degraded memories rank lower)", () => {
322
- const { store } = setup();
323
- const svc = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true } } });
324
- svc.saveWithDedupe({ type: "preference", title: "高质量", content: "用户喜欢读科幻小说和散文" });
325
- svc.saveWithDedupe({ type: "preference", title: "元记忆", content: "我需要记住用户偏好的完整清单防止忘记" });
326
- const candidates = svc.injectCandidates({ maxItems: 5, threshold: 3 });
327
- assert.equal(candidates[0].title, "高质量", "100-quality preference leads the degraded one");
328
- assert.equal(candidates[1].title, "元记忆");
329
- });
330
-
331
- // v0.8.0 冲突集中处理:resolveConflictPending 盖章 + 处置落地(与 dream 非冻结
332
- // conflict 同款:胜者正文追加已否决注记、败者归档),以及队列视图的联表形状。
333
- test("resolveConflictPending applies the dream-style disposition on human confirmation", () => {
334
- const { store, service } = setup();
335
- const a = store.save({ type: "history", title: "界面暗色偏好", content: "用户当前使用暗色界面主题", importance: 3 });
336
- const b = store.save({ type: "history", title: "界面亮色切换", content: "用户界面亮色切换计划", importance: 3 });
337
- const pending = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "主题偏好前后矛盾" });
338
- // store 会把 pair 按 id 字典序归一(防重复入队),A/B 只是排序位——
339
- // 人工确认前先从队列行反查「界面亮色切换」(keeper,恒为 b)落在哪一侧,
340
- // 再选那一侧保留;loser 恒为 a(「界面暗色偏好」),与侧位字母无关。
341
- const queued = service.listConflictQueue().find((q) => q.id === pending.id);
342
- const winnerSide = queued.memory_a.id === b.id ? "a" : "b";
343
- const loserId = a.id;
344
-
345
- const resolved = service.resolveConflictPending(pending.id, { winner: winnerSide, apply: true });
346
- assert.ok(resolved, "returns the stamped row");
347
- assert.ok(resolved.resolved_at, "stamps resolved_at");
348
- assert.equal(resolved.resolved_winner, b.id, "resolved_winner records the chosen memory id");
349
- assert.equal(resolved.disposition?.ok, true, "disposition landed");
350
-
351
- // 败者归档 + 胜者保留——与 dream applyConflict 同款(胜者正文由
352
- // applyDecisions 追加已否决注记)。
353
- assert.equal(store.getById(loserId).archived, true, "loser archived");
354
- assert.equal(store.getById(b.id).archived, false, "winner kept active");
355
- assert.notEqual(store.getById(b.id).content, b.content, "winner content carries the veto note");
356
- // 处置后队列不再返回该冲突。
357
- assert.equal(service.listConflictQueue().length, 0);
358
- });
359
-
360
- test("resolveConflictPending with winner=null only stamps (mark reviewed)", () => {
361
- const { store, service } = setup();
362
- const a = store.save({ type: "project", title: "甲", content: "内容甲" });
363
- const b = store.save({ type: "project", title: "乙", content: "内容乙" });
364
- const pending = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "r" });
365
- const resolved = service.resolveConflictPending(pending.id, { winner: null });
366
- assert.ok(resolved.resolved_at);
367
- assert.equal(resolved.disposition, null, "no disposition applied");
368
- assert.equal(store.getById(a.id).archived, false);
369
- assert.equal(store.getById(b.id).archived, false);
370
- });
371
-
372
- test("resolveConflictPending unknown id returns undefined", () => {
373
- const { service } = setup();
374
- assert.equal(service.resolveConflictPending("nope", { winner: "a" }), undefined);
375
- });
376
-
377
- // Review 守卫(#166 时序修复):盖章必须先于处置的**反面**契约——处置失败时
378
- // 不得盖章。单线程下 casGuard 的 snapshot 与读取之间没有异步介入点,CAS 冲突
379
- // 实际不可达(这是原 PR 没测它的原因),但它一旦因未来改动可达(异步 store、
380
- // update/archive 抛错),先盖章会让行已 resolved、从队列消失却未处置。这条源码
381
- // 断言把顺序固化下来(与 client.test.js 断言 ConflictsQueue 存在同一惯例),
382
- // 防止未来有人再把盖章挪回处置之前。
383
- test("resolveConflictPending stamps only after disposition succeeds (review ordering guard)", () => {
384
- const source = readFileSync(new URL("../src/service.js", import.meta.url), "utf8");
385
- const fn = source.slice(source.indexOf("function resolveConflictPending"));
386
- const applyAt = fn.indexOf("applyDecisions(");
387
- const stampAt = fn.indexOf("store.resolveConflictPending(");
388
- assert.ok(applyAt !== -1, "resolveConflictPending must call applyDecisions");
389
- assert.ok(stampAt !== -1, "resolveConflictPending must call store.resolveConflictPending");
390
- assert.ok(stampAt > applyAt, "stamp must happen after applyDecisions — a failed disposition must not mark the conflict resolved");
391
- assert.ok(fn.includes("if (failures.length)"), "apply failures must short-circuit before stamping");
392
- });
393
-
394
- test("listConflictQueue joins both sides and tolerates missing memories", () => {
395
- const { store, service } = setup();
396
- const a = store.save({ type: "decision", title: "现存方", content: "现存内容", importance: 4 });
397
- const pending = store.saveConflictPending({ memory_a: a.id, memory_b: "ghost-id", reason: "对方已被删除" });
398
- const queue = service.listConflictQueue();
399
- assert.equal(queue.length, 1);
400
- assert.equal(queue[0].id, pending.id);
401
- assert.equal(queue[0].memory_a?.title, "现存方", "side A joined from the store");
402
- assert.equal(queue[0].memory_a?.archived, false);
403
- assert.equal(queue[0].memory_b?.missing, true, "ghost side marked missing");
404
- assert.equal(queue[0].reason, "对方已被删除");
405
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createStore } from "../src/store.js";
7
+ import { createService } from "../src/service.js";
8
+ import { createMirror } from "../src/mirror.js";
9
+
10
+ function setup() {
11
+ const store = createStore(":memory:");
12
+ const service = createService({ store, mirror: null, config: {} });
13
+ return { store, service };
14
+ }
15
+
16
+ test("saveWithDedupe adds new memory when no similar exists", () => {
17
+ const { store, service } = setup();
18
+ const result = service.saveWithDedupe({
19
+ type: "project",
20
+ title: "记忆插件",
21
+ content: "正在开发 dsh-mneme,SQLite+Markdown",
22
+ importance: 4
23
+ });
24
+ assert.equal(result.action, "created");
25
+ assert.equal(store.count(), 1);
26
+ });
27
+
28
+ test("saveWithDedupe merges into existing on exact title match", () => {
29
+ const { store, service } = setup();
30
+ service.saveWithDedupe({ type: "project", title: "记忆插件", content: "旧内容", importance: 3 });
31
+ const result = service.saveWithDedupe({ type: "project", title: "记忆插件", content: "新内容", importance: 5 });
32
+ assert.equal(result.action, "merged");
33
+ assert.equal(store.count(), 1);
34
+ const all = store.all();
35
+ // Bug5: same-title merge appends under a timestamped `---` separator instead
36
+ // of overwriting; the previous content is archived into content_history.
37
+ assert.ok(all[0].content.includes("旧内容"), "old content preserved in appended body");
38
+ assert.ok(all[0].content.includes("新内容"), "new content appended");
39
+ assert.ok(all[0].content.includes("---"), "timestamped separator present");
40
+ assert.equal(all[0].importance, 5, "importance takes the max of both");
41
+ assert.equal(all[0].content_history.length, 1, "old content archived to history");
42
+ assert.equal(all[0].content_history[0].content, "旧内容");
43
+ assert.equal(all[0].content_history[0].source, "auto_merge");
44
+ });
45
+
46
+ test("injectCandidates returns preferences + high-importance items within limit", () => {
47
+ const { service } = setup();
48
+ for (let i = 0; i < 3; i++) service.saveWithDedupe({ type: "preference", title: `p${i}`, content: "偏好" });
49
+ service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
50
+ service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
51
+ service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
52
+ const candidates = service.injectCandidates({ maxItems: 5, threshold: 4 });
53
+ const types = candidates.map((c) => c.type);
54
+ assert.ok(types.includes("preference"), "preferences included");
55
+ assert.ok(types.includes("project"), "high-importance project included");
56
+ // #369:history 曾被注入白名单挡在门外,现按「注入侧收编」进池(理由与实测数字
57
+ // 见 src/service.js 的 INJECT_TYPES 注释)。这里从「锁排除」改成「锁收编」——
58
+ // 白名单日后若被收窄,这条会红,而不是静默把两成条目关回不可注入。
59
+ assert.ok(types.includes("history"), "history included since #369");
60
+ assert.ok(candidates.length <= 5, "respects maxItems");
61
+ });
62
+
63
+ test("mergeHumanEdits applies human content over machine", () => {
64
+ const { store, service } = setup();
65
+ const saved = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
66
+ const edits = [{ id: saved.memory.id, title: "语言", content: "人类编辑内容" }];
67
+ service.mergeHumanEdits("preference", edits);
68
+ const got = store.getById(saved.memory.id);
69
+ assert.equal(got.content, "人类编辑内容");
70
+ });
71
+
72
+ test("toApiList maps store rows to wire DTOs", () => {
73
+ const { service } = setup();
74
+ const saved = service.saveWithDedupe({ type: "decision", title: "选型", content: "node:sqlite", importance: 3 });
75
+ const dto = service.toApiList([saved.memory]);
76
+ assert.deepEqual(Object.keys(dto[0]).sort(), ["id", "type", "title", "content", "tags", "importance", "source", "created_at", "updated_at"].sort());
77
+ assert.equal(dto[0].id, saved.memory.id);
78
+ assert.equal(dto[0].type, "decision");
79
+ assert.equal(dto[0].title, "选型");
80
+ assert.equal(dto[0].content, "node:sqlite");
81
+ assert.equal(dto[0].importance, 3);
82
+ });
83
+
84
+ test("mergeHumanEdits skips edits without id and keeps applying the rest", () => {
85
+ const { store, service } = setup();
86
+ const first = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
87
+ const second = service.saveWithDedupe({ type: "preference", title: "主题", content: "机器内容" });
88
+ const edits = [
89
+ { content: "缺少 id 的损坏条目" },
90
+ { id: first.memory.id, title: "语言", content: "人类编辑内容" },
91
+ { id: second.memory.id, title: "主题", content: "第二个人类编辑" }
92
+ ];
93
+ const applied = service.mergeHumanEdits("preference", edits);
94
+ assert.equal(applied, 2, "returns count of applied edits, not input length");
95
+ assert.equal(store.getById(first.memory.id).content, "人类编辑内容");
96
+ assert.equal(store.getById(second.memory.id).content, "第二个人类编辑");
97
+ });
98
+
99
+ test("mutations through passthroughs sync mirror; forgotten entries stay out of it", () => {
100
+ const store = createStore(":memory:");
101
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
102
+ const mirror = createMirror(dir);
103
+ const service = createService({ store, mirror, config: {} });
104
+ try {
105
+ const saved = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
106
+ assert.ok(existsSync(join(dir, "projects.md")), "mirror written on save");
107
+
108
+ service.update(saved.memory.id, { content: "a2" });
109
+ assert.match(readFileSync(join(dir, "projects.md"), "utf8"), /a2/, "update re-syncs mirror");
110
+
111
+ service.setForget(saved.memory.id, true);
112
+ assert.ok(!existsSync(join(dir, "projects.md")), "forgotten entry removed from mirror");
113
+
114
+ const second = service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
115
+ assert.ok(existsSync(join(dir, "projects.md")), "mirror rewritten after re-save");
116
+ service.remove(second.memory.id);
117
+ assert.ok(!existsSync(join(dir, "projects.md")), "remove re-syncs mirror");
118
+ } finally {
119
+ rmSync(dir, { recursive: true, force: true });
120
+ }
121
+ });
122
+
123
+ test("saveWithDedupe created branch keeps forgotten entries out of mirror", () => {
124
+ const store = createStore(":memory:");
125
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
126
+ const mirror = createMirror(dir);
127
+ const service = createService({ store, mirror, config: {} });
128
+ try {
129
+ const a = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
130
+ service.setForget(a.memory.id, true);
131
+ service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
132
+ const text = readFileSync(join(dir, "projects.md"), "utf8");
133
+ assert.ok(!text.includes(a.memory.id), "forgotten A must not reappear in mirror");
134
+ assert.ok(!text.includes("## A"), "forgotten A entry absent from mirror");
135
+ assert.match(text, /## B/, "non-forgotten B present in mirror");
136
+ } finally {
137
+ rmSync(dir, { recursive: true, force: true });
138
+ }
139
+ });
140
+
141
+ test("injectCandidates excludes archived entries", () => {
142
+ const { store, service } = setup();
143
+ const saved = service.saveWithDedupe({ type: "preference", title: "旧偏好", content: "old", importance: 5 });
144
+ store.setArchived(saved.memory.id, true);
145
+ const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
146
+ assert.ok(!candidates.some((c) => c.id === saved.memory.id), "archived excluded");
147
+ });
148
+
149
+ test("summary memory is a candidate at top priority", () => {
150
+ const { service } = setup();
151
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
152
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览内容", importance: 5 });
153
+ const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
154
+ assert.equal(candidates[0]?.type, "summary", "summary first even with competing high-importance preference");
155
+ });
156
+
157
+ test("write methods invoke onWrite hook when provided", () => {
158
+ const { store } = setup();
159
+ let called = 0;
160
+ const svc = createService({ store, mirror: null, config: {}, onWrite: () => { called++; } });
161
+ svc.saveWithDedupe({ type: "project", title: "a", content: "x" });
162
+ assert.equal(called, 1, "saveWithDedupe hooks");
163
+ svc.update(svc.all()[0].id, { content: "y" });
164
+ assert.equal(called, 2, "update hooks");
165
+ svc.setArchived(svc.all()[0].id, true);
166
+ assert.equal(called, 2, "setArchived does not hook (not a content write)");
167
+ });
168
+
169
+ // --- transactions (item ②) + compare-and-set (item ①/③) --------------------
170
+
171
+ test("service.transaction rolls back every step when the body throws", () => {
172
+ const { store, service } = setup();
173
+ let threw = false;
174
+ try {
175
+ service.transaction(() => {
176
+ service.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
177
+ service.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
178
+ throw new Error("boom");
179
+ });
180
+ } catch { threw = true; }
181
+ assert.equal(threw, true, "error propagates");
182
+ assert.equal(store.count(), 0, "no partial writes after rollback");
183
+ assert.ok(!store.all().some((m) => m.title === "原子A"), "step A rolled back");
184
+ assert.ok(!store.all().some((m) => m.title === "原子B"), "step B rolled back");
185
+ store.close();
186
+ });
187
+
188
+ test("service.transaction commits all steps atomically on success", () => {
189
+ const { store, service } = setup();
190
+ service.transaction(() => {
191
+ service.saveWithDedupe({ type: "project", title: "甲", content: "x" });
192
+ service.saveWithDedupe({ type: "project", title: "乙", content: "y" });
193
+ });
194
+ assert.equal(store.count(), 2, "both steps committed");
195
+ store.close();
196
+ });
197
+
198
+ test("service.compareAndUpdate rejects a stale version token (no lost update)", () => {
199
+ const { store, service } = setup();
200
+ const { memory: m } = service.saveWithDedupe({ type: "history", title: "计数器", content: "count=0" });
201
+ const baseline = service.getById(m.id);
202
+ const first = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=1" });
203
+ assert.ok(first, "current version CAS succeeds");
204
+ const stale = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=2" });
205
+ assert.equal(stale, undefined, "stale version CAS misses without writing");
206
+ assert.equal(service.getById(m.id).content, "count=1", "increment not lost");
207
+ store.close();
208
+ });
209
+
210
+ // --- Bug4: injectCandidates semantic-first recall (query) --------------------
211
+
212
+ test("Bug4: injectCandidates with an empty query keeps the legacy rule-based selection", () => {
213
+ const { service } = setup();
214
+ service.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
215
+ service.saveWithDedupe({ type: "preference", title: "p1", content: "偏好" });
216
+ service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
217
+ service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
218
+ service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
219
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
220
+ const legacy = service.injectCandidates({ maxItems: 5, threshold: 4 });
221
+ const noQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: "" });
222
+ const blankQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: " " });
223
+ assert.deepEqual(noQuery.map((c) => c.id), legacy.map((c) => c.id), "empty query behaves identically to the old logic");
224
+ assert.deepEqual(blankQuery.map((c) => c.id), legacy.map((c) => c.id), "whitespace-only query degrades too");
225
+ assert.equal(legacy[0].type, "summary", "summary still leads");
226
+ // #369 收编后 history 可进池;本用例的重心是「空查询与旧规则路逐字节同序」,
227
+ // 这条只确认收编没有撼动优先级分层——summary 仍打头。
228
+ assert.ok(legacy.some((c) => c.type === "history"), "history included since #369");
229
+ });
230
+
231
+ test("Bug4: injectCandidates ignores the query when hybridInject is disabled", () => {
232
+ const { store } = setup();
233
+ const svc = createService({ store, mirror: null, config: { hybridInject: false } });
234
+ svc.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
235
+ svc.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
236
+ const noQuery = svc.injectCandidates({ maxItems: 5, threshold: 3 });
237
+ const withQuery = svc.injectCandidates({ maxItems: 5, threshold: 3, query: "中文" });
238
+ assert.deepEqual(withQuery.map((c) => c.id), noQuery.map((c) => c.id), "hybridInject off keeps rule-based ordering");
239
+ });
240
+
241
+ // --- Bug5: content_history FIFO + human-edited direct overwrite --------------
242
+
243
+ test("Bug5: content_history grows FIFO across repeated same-title merges (capped at 20)", () => {
244
+ const { store, service } = setup();
245
+ service.saveWithDedupe({ type: "project", title: "流水", content: "v0" });
246
+ for (let i = 1; i <= 25; i++) {
247
+ service.saveWithDedupe({ type: "project", title: "流水", content: `v${i}` });
248
+ }
249
+ const row = store.all()[0];
250
+ assert.ok(Array.isArray(row.content_history), "content_history is an array");
251
+ assert.equal(row.content_history.length, 20, "FIFO cap of 20 respected");
252
+ assert.ok(row.content_history[0].content.includes("v24"), "newest archived body kept at index 0");
253
+ assert.ok(row.content_history[19].content.includes("v5"), "oldest kept entry");
254
+ assert.ok(!row.content_history[19].content.includes("v6"), "entries older than the cap dropped");
255
+ assert.ok(row.content.includes("v25"), "latest merge still appended to the live body");
256
+ });
257
+
258
+ test("Bug5: _humanEdited overwrite replaces content directly and archives the old version", () => {
259
+ const { store, service } = setup();
260
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
261
+ const result = service.saveWithDedupe({ type: "preference", title: "语言", content: "人工修正", _humanEdited: true });
262
+ const row = store.getById(result.memory.id);
263
+ assert.equal(row.content, "人工修正", "direct overwrite, no appended --- block");
264
+ assert.ok(!row.content.includes("机器内容"), "old content not in the live body");
265
+ assert.equal(row.content_history.length, 1);
266
+ assert.equal(row.content_history[0].content, "机器内容");
267
+ assert.equal(row.content_history[0].source, "human_override");
268
+ });
269
+
270
+ // --- Bug7: memory quality filter ---------------------------------------------
271
+
272
+ function qualitySetup(config = {}) {
273
+ const store = createStore(":memory:");
274
+ const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true, ...config } } });
275
+ return { store, service };
276
+ }
277
+
278
+ test("Bug7: meta-memory is scored below the degrade threshold but still stored", () => {
279
+ const { store, service } = qualitySetup();
280
+ const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
281
+ assert.equal(result.action, "created");
282
+ assert.ok(result.memory.quality_score < 60, `meta-memory degraded, got ${result.memory.quality_score}`);
283
+ assert.ok(result.memory.quality_score >= 30, "still above the archive threshold");
284
+ assert.equal(result.memory.archived, false, "not archived");
285
+ assert.equal(store.count(), 1, "still stored and searchable");
286
+ });
287
+
288
+ test("Bug7: short content is archived and tagged low_quality", () => {
289
+ const { store, service } = qualitySetup();
290
+ const result = service.saveWithDedupe({ type: "project", title: "备忘", content: "x" });
291
+ const row = store.getById(result.memory.id);
292
+ assert.equal(row.archived, true, "short content archived");
293
+ assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
294
+ assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
295
+ });
296
+
297
+ test("Bug7: near-duplicate content is archived and tagged low_quality", () => {
298
+ const { store, service } = qualitySetup();
299
+ const base = "今天下午去操场跑步三圈然后回来洗澡";
300
+ service.saveWithDedupe({ type: "history", title: "记录A", content: base });
301
+ const result = service.saveWithDedupe({ type: "history", title: "记录B", content: `${base}${base}${base}` });
302
+ const row = store.getById(result.memory.id);
303
+ assert.equal(row.archived, true, "near-duplicate archived");
304
+ assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
305
+ assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
306
+ });
307
+
308
+ test("Bug7: repetitive (dedup<0.3) content is scored into the degraded band", () => {
309
+ const { store, service } = qualitySetup();
310
+ const result = service.saveWithDedupe({ type: "history", title: "唠叨", content: "好好好好好好好好好好好好好好好好好好" });
311
+ const row = store.getById(result.memory.id);
312
+ assert.ok(row.quality_score >= 30 && row.quality_score < 60, `repetitive-only degraded, got ${row.quality_score}`);
313
+ assert.equal(row.archived, false, "not archived (only a single non-meta signal)");
314
+ });
315
+
316
+ test("Bug7: memoryQualityFilter.enabled=false skips scoring entirely", () => {
317
+ const store = createStore(":memory:");
318
+ const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: false } } });
319
+ const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
320
+ const row = store.getById(result.memory.id);
321
+ assert.ok(row.quality_score == null, "no quality_score written");
322
+ assert.equal(row.archived, false, "not archived");
323
+ assert.ok(!(row.tags ?? []).includes("low_quality"), "no low_quality tag");
324
+ });
325
+
326
+ test("Bug7: injection ranking re-weights by quality_score (degraded memories rank lower)", () => {
327
+ const { store } = setup();
328
+ const svc = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true } } });
329
+ svc.saveWithDedupe({ type: "preference", title: "高质量", content: "用户喜欢读科幻小说和散文" });
330
+ svc.saveWithDedupe({ type: "preference", title: "元记忆", content: "我需要记住用户偏好的完整清单防止忘记" });
331
+ const candidates = svc.injectCandidates({ maxItems: 5, threshold: 3 });
332
+ assert.equal(candidates[0].title, "高质量", "100-quality preference leads the degraded one");
333
+ assert.equal(candidates[1].title, "元记忆");
334
+ });
335
+
336
+ // v0.8.0 冲突集中处理:resolveConflictPending 盖章 + 处置落地(与 dream 非冻结
337
+ // conflict 同款:胜者正文追加已否决注记、败者归档),以及队列视图的联表形状。
338
+ test("resolveConflictPending applies the dream-style disposition on human confirmation", () => {
339
+ const { store, service } = setup();
340
+ const a = store.save({ type: "history", title: "界面暗色偏好", content: "用户当前使用暗色界面主题", importance: 3 });
341
+ const b = store.save({ type: "history", title: "界面亮色切换", content: "用户界面亮色切换计划", importance: 3 });
342
+ const pending = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "主题偏好前后矛盾" });
343
+ // store 会把 pair 按 id 字典序归一(防重复入队),A/B 只是排序位——
344
+ // 人工确认前先从队列行反查「界面亮色切换」(keeper,恒为 b)落在哪一侧,
345
+ // 再选那一侧保留;loser 恒为 a(「界面暗色偏好」),与侧位字母无关。
346
+ const queued = service.listConflictQueue().find((q) => q.id === pending.id);
347
+ const winnerSide = queued.memory_a.id === b.id ? "a" : "b";
348
+ const loserId = a.id;
349
+
350
+ const resolved = service.resolveConflictPending(pending.id, { winner: winnerSide, apply: true });
351
+ assert.ok(resolved, "returns the stamped row");
352
+ assert.ok(resolved.resolved_at, "stamps resolved_at");
353
+ assert.equal(resolved.resolved_winner, b.id, "resolved_winner records the chosen memory id");
354
+ assert.equal(resolved.disposition?.ok, true, "disposition landed");
355
+
356
+ // 败者归档 + 胜者保留——与 dream applyConflict 同款(胜者正文由
357
+ // applyDecisions 追加已否决注记)。
358
+ assert.equal(store.getById(loserId).archived, true, "loser archived");
359
+ assert.equal(store.getById(b.id).archived, false, "winner kept active");
360
+ assert.notEqual(store.getById(b.id).content, b.content, "winner content carries the veto note");
361
+ // 处置后队列不再返回该冲突。
362
+ assert.equal(service.listConflictQueue().length, 0);
363
+ });
364
+
365
+ test("resolveConflictPending with winner=null only stamps (mark reviewed)", () => {
366
+ const { store, service } = setup();
367
+ const a = store.save({ type: "project", title: "甲", content: "内容甲" });
368
+ const b = store.save({ type: "project", title: "乙", content: "内容乙" });
369
+ const pending = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "r" });
370
+ const resolved = service.resolveConflictPending(pending.id, { winner: null });
371
+ assert.ok(resolved.resolved_at);
372
+ assert.equal(resolved.disposition, null, "no disposition applied");
373
+ assert.equal(store.getById(a.id).archived, false);
374
+ assert.equal(store.getById(b.id).archived, false);
375
+ });
376
+
377
+ test("resolveConflictPending unknown id returns undefined", () => {
378
+ const { service } = setup();
379
+ assert.equal(service.resolveConflictPending("nope", { winner: "a" }), undefined);
380
+ });
381
+
382
+ // Review 守卫(#166 时序修复):盖章必须先于处置的**反面**契约——处置失败时
383
+ // 不得盖章。单线程下 casGuard 的 snapshot 与读取之间没有异步介入点,CAS 冲突
384
+ // 实际不可达(这是原 PR 没测它的原因),但它一旦因未来改动可达(异步 store、
385
+ // update/archive 抛错),先盖章会让行已 resolved、从队列消失却未处置。这条源码
386
+ // 断言把顺序固化下来(与 client.test.js 断言 ConflictsQueue 存在同一惯例),
387
+ // 防止未来有人再把盖章挪回处置之前。
388
+ test("resolveConflictPending stamps only after disposition succeeds (review ordering guard)", () => {
389
+ const source = readFileSync(new URL("../src/service.js", import.meta.url), "utf8");
390
+ const fn = source.slice(source.indexOf("function resolveConflictPending"));
391
+ const applyAt = fn.indexOf("applyDecisions(");
392
+ const stampAt = fn.indexOf("store.resolveConflictPending(");
393
+ assert.ok(applyAt !== -1, "resolveConflictPending must call applyDecisions");
394
+ assert.ok(stampAt !== -1, "resolveConflictPending must call store.resolveConflictPending");
395
+ assert.ok(stampAt > applyAt, "stamp must happen after applyDecisions — a failed disposition must not mark the conflict resolved");
396
+ assert.ok(fn.includes("if (failures.length)"), "apply failures must short-circuit before stamping");
397
+ });
398
+
399
+ test("listConflictQueue joins both sides and tolerates missing memories", () => {
400
+ const { store, service } = setup();
401
+ const a = store.save({ type: "decision", title: "现存方", content: "现存内容", importance: 4 });
402
+ const pending = store.saveConflictPending({ memory_a: a.id, memory_b: "ghost-id", reason: "对方已被删除" });
403
+ const queue = service.listConflictQueue();
404
+ assert.equal(queue.length, 1);
405
+ assert.equal(queue[0].id, pending.id);
406
+ assert.equal(queue[0].memory_a?.title, "现存方", "side A joined from the store");
407
+ assert.equal(queue[0].memory_a?.archived, false);
408
+ assert.equal(queue[0].memory_b?.missing, true, "ghost side marked missing");
409
+ assert.equal(queue[0].reason, "对方已被删除");
410
+ });