@modusensus/dsh-mneme 0.6.9 → 0.6.10

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/LICENSE +21 -21
  2. package/README.md +468 -219
  3. package/{dsh-mneme/cordis.patch.yml → cordis.patch.yml} +15 -15
  4. package/{dsh-mneme/src → lib}/api.js +783 -783
  5. package/{dsh-mneme/lib → lib}/client.js +1754 -1757
  6. package/{dsh-mneme/src → lib}/commands.js +64 -64
  7. package/{dsh-mneme/lib → lib}/config.js +298 -298
  8. package/{dsh-mneme/lib → lib}/dream/clustering.js +118 -118
  9. package/{dsh-mneme/lib → lib}/dream/decisions.js +488 -488
  10. package/{dsh-mneme/lib → lib}/dream/sleep.js +561 -561
  11. package/{dsh-mneme/src → lib}/dream/tag-extractor.js +156 -156
  12. package/{dsh-mneme/lib → lib}/dream.js +958 -958
  13. package/{dsh-mneme/src → lib}/embedding.js +154 -154
  14. package/{dsh-mneme/src → lib}/entities/extractor.js +242 -242
  15. package/{dsh-mneme/lib → lib}/hot-memory.js +53 -53
  16. package/{dsh-mneme/lib → lib}/index.js +361 -361
  17. package/{dsh-mneme/src → lib}/inject.js +208 -208
  18. package/{dsh-mneme/lib → lib}/local-embedder.js +282 -282
  19. package/{dsh-mneme/lib → lib}/mirror.js +170 -170
  20. package/{dsh-mneme/lib → lib}/parser/tag.js +59 -59
  21. package/{dsh-mneme/lib → lib}/parser/wiki-link.js +38 -38
  22. package/{dsh-mneme/src → lib}/quality-filter.js +123 -123
  23. package/{dsh-mneme/lib → lib}/reranker.js +218 -218
  24. package/{dsh-mneme/src → lib}/search/adaptive.js +22 -22
  25. package/{dsh-mneme/src → lib}/search/bm25.js +96 -96
  26. package/{dsh-mneme/src → lib}/search/tag-boost.js +61 -61
  27. package/{dsh-mneme/src → lib}/service.js +1726 -1726
  28. package/{dsh-mneme/lib → lib}/settings.js +172 -172
  29. package/{dsh-mneme/src → lib}/store.js +2238 -2238
  30. package/{dsh-mneme/src → lib}/summarize.js +236 -236
  31. package/{dsh-mneme/lib → lib}/tools.js +290 -290
  32. package/{dsh-mneme/lib → lib}/vector-index.js +116 -116
  33. package/package.json +40 -18
  34. package/{dsh-mneme/scripts → scripts}/benchmark-embed.js +201 -201
  35. package/{dsh-mneme/scripts → scripts}/benchmark-recall.js +133 -133
  36. package/{dsh-mneme/scripts → scripts}/benchmark-rerank.js +166 -166
  37. package/{dsh-mneme/scripts → scripts}/e2e-dsh.js +218 -218
  38. package/{dsh-mneme/scripts → scripts}/stress-dsh.js +255 -255
  39. package/{dsh-mneme/scripts → scripts}/sync-lib.js +52 -52
  40. package/{dsh-mneme/lib → src}/api.js +783 -783
  41. package/{dsh-mneme/lib → src}/commands.js +64 -64
  42. package/{dsh-mneme/src → src}/config.js +298 -298
  43. package/{dsh-mneme/src → src}/dream/clustering.js +118 -118
  44. package/{dsh-mneme/src → src}/dream/decisions.js +488 -488
  45. package/{dsh-mneme/src → src}/dream/sleep.js +561 -561
  46. package/{dsh-mneme/lib → src}/dream/tag-extractor.js +156 -156
  47. package/{dsh-mneme/src → src}/dream.js +958 -958
  48. package/{dsh-mneme/lib → src}/embedding.js +154 -154
  49. package/{dsh-mneme/lib → src}/entities/extractor.js +242 -242
  50. package/{dsh-mneme/src → src}/hot-memory.js +53 -53
  51. package/{dsh-mneme/src → src}/index.js +361 -361
  52. package/{dsh-mneme/lib → src}/inject.js +208 -208
  53. package/{dsh-mneme/src → src}/local-embedder.js +282 -282
  54. package/{dsh-mneme/src → src}/mirror.js +170 -170
  55. package/{dsh-mneme/src → src}/parser/tag.js +59 -59
  56. package/{dsh-mneme/src → src}/parser/wiki-link.js +38 -38
  57. package/{dsh-mneme/lib → src}/quality-filter.js +123 -123
  58. package/{dsh-mneme/src → src}/reranker.js +218 -218
  59. package/{dsh-mneme/lib → src}/search/adaptive.js +22 -22
  60. package/{dsh-mneme/lib → src}/search/bm25.js +96 -96
  61. package/{dsh-mneme/lib → src}/search/tag-boost.js +61 -61
  62. package/{dsh-mneme/lib → src}/service.js +1726 -1726
  63. package/{dsh-mneme/src → src}/settings.js +172 -172
  64. package/{dsh-mneme/lib → src}/store.js +2238 -2238
  65. package/{dsh-mneme/lib → src}/summarize.js +236 -236
  66. package/{dsh-mneme/src → src}/tools.js +290 -290
  67. package/{dsh-mneme/src → src}/vector-index.js +116 -116
  68. package/{dsh-mneme/test → test}/api.test.js +594 -594
  69. package/{dsh-mneme/test → test}/audit.test.js +448 -448
  70. package/{dsh-mneme/test → test}/benchmark.test.js +35 -35
  71. package/{dsh-mneme/test → test}/boundary-v0625.test.js +82 -82
  72. package/{dsh-mneme/test → test}/client.test.js +368 -368
  73. package/{dsh-mneme/test → test}/clustering.test.js +100 -100
  74. package/{dsh-mneme/test → test}/commands.test.js +69 -69
  75. package/{dsh-mneme/test → test}/config.test.js +50 -50
  76. package/{dsh-mneme/test → test}/conflict-freeze.test.js +290 -290
  77. package/{dsh-mneme/test → test}/directory.test.js +134 -134
  78. package/{dsh-mneme/test → test}/dream.test.js +1060 -1060
  79. package/{dsh-mneme/test → test}/entities.test.js +522 -522
  80. package/{dsh-mneme/test → test}/epistemic.test.js +298 -298
  81. package/{dsh-mneme/test → test}/fnew-0112.test.js +311 -311
  82. package/{dsh-mneme/test → test}/fnew-03.test.js +422 -422
  83. package/{dsh-mneme/test → test}/graph-api.test.js +175 -175
  84. package/{dsh-mneme/test → test}/helpers/dream-mock.js +82 -82
  85. package/{dsh-mneme/test → test}/hot-memory.test.js +174 -174
  86. package/{dsh-mneme/test → test}/inject.test.js +103 -103
  87. package/{dsh-mneme/test → test}/llm-audit.test.js +279 -279
  88. package/{dsh-mneme/test → test}/local-embedder.test.js +227 -227
  89. package/{dsh-mneme/test → test}/mirror-dirty.test.js +424 -424
  90. package/{dsh-mneme/test → test}/mirror-edit-digest.test.js +187 -187
  91. package/{dsh-mneme/test → test}/mirror-generation.test.js +499 -499
  92. package/{dsh-mneme/test → test}/mirror.test.js +249 -249
  93. package/{dsh-mneme/test → test}/normalize-decisions.test.js +120 -120
  94. package/{dsh-mneme/test → test}/peer-blockers.test.js +190 -190
  95. package/{dsh-mneme/test → test}/policy-epoch.test.js +259 -259
  96. package/{dsh-mneme/test → test}/provenance.test.js +103 -103
  97. package/{dsh-mneme/test → test}/quality-filter.test.js +118 -118
  98. package/{dsh-mneme/test → test}/reasoning-effort.test.js +199 -199
  99. package/{dsh-mneme/test → test}/recall-evals.test.js +235 -235
  100. package/{dsh-mneme/test → test}/recall-layer.test.js +315 -315
  101. package/{dsh-mneme/test → test}/receipt-chain.test.js +451 -451
  102. package/{dsh-mneme/test → test}/reflection.test.js +226 -226
  103. package/{dsh-mneme/test → test}/reranker.test.js +240 -240
  104. package/{dsh-mneme/test → test}/search-fusion.test.js +90 -90
  105. package/{dsh-mneme/test → test}/semantic.test.js +124 -124
  106. package/{dsh-mneme/test → test}/service-search.test.js +199 -199
  107. package/{dsh-mneme/test → test}/service.test.js +435 -435
  108. package/{dsh-mneme/test → test}/settings.test.js +118 -118
  109. package/{dsh-mneme/test → test}/sleep.test.js +365 -365
  110. package/{dsh-mneme/test → test}/store.test.js +436 -436
  111. package/{dsh-mneme/test → test}/stress.test.js +209 -209
  112. package/{dsh-mneme/test → test}/summarize.test.js +191 -191
  113. package/{dsh-mneme/test → test}/tag-boost.test.js +125 -125
  114. package/{dsh-mneme/test → test}/tag.test.js +312 -312
  115. package/{dsh-mneme/test → test}/tools.test.js +285 -285
  116. package/{dsh-mneme/test → test}/vector-index.test.js +221 -221
  117. package/{dsh-mneme/test → test}/wiki-link.test.js +332 -332
  118. package/.github/workflows/test.yml +0 -32
  119. package/.release-notes-v0.6.9.md +0 -13
  120. package/CHANGELOG.md +0 -89
  121. package/SECURITY.md +0 -544
  122. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +0 -247
  123. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +0 -145
  124. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +0 -56
  125. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +0 -77
  126. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +0 -64
  127. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +0 -90
  128. package/dsh-mneme/CHANGELOG.md +0 -248
  129. package/dsh-mneme/LICENSE +0 -21
  130. package/dsh-mneme/README.md +0 -465
  131. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +0 -183
  132. package/dsh-mneme/docs/ENTITIES.md +0 -245
  133. package/dsh-mneme/docs/LOCAL_MODEL.md +0 -141
  134. package/dsh-mneme/docs/MIGRATION.md +0 -127
  135. package/dsh-mneme/docs/SEMANTIC.md +0 -256
  136. package/dsh-mneme/docs/SLEEP.md +0 -163
  137. package/dsh-mneme/package-lock.json +0 -1936
  138. package/dsh-mneme/package.json +0 -80
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,435 +1,435 @@
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
- // session_id rides the DTO when present (session lifecycle needs it)
80
- const withSession = service.saveWithDedupe({ type: "decision", title: "带会话", content: "y", session_id: "sess-x" });
81
- const dto2 = service.toApiList([withSession.memory]);
82
- assert.equal(dto2[0].session_id, "sess-x");
83
- });
84
-
85
- test("mergeHumanEdits skips edits without id and keeps applying the rest", () => {
86
- const { store, service } = setup();
87
- const first = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
88
- const second = service.saveWithDedupe({ type: "preference", title: "主题", content: "机器内容" });
89
- const edits = [
90
- { content: "缺少 id 的损坏条目" },
91
- { id: first.memory.id, title: "语言", content: "人类编辑内容" },
92
- { id: second.memory.id, title: "主题", content: "第二个人类编辑" }
93
- ];
94
- const applied = service.mergeHumanEdits("preference", edits);
95
- assert.equal(applied, 2, "returns count of applied edits, not input length");
96
- assert.equal(store.getById(first.memory.id).content, "人类编辑内容");
97
- assert.equal(store.getById(second.memory.id).content, "第二个人类编辑");
98
- });
99
-
100
- test("mutations through passthroughs sync mirror; forgotten entries stay out of it", () => {
101
- const store = createStore(":memory:");
102
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
103
- const mirror = createMirror(dir);
104
- const service = createService({ store, mirror, config: {} });
105
- try {
106
- const saved = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
107
- assert.ok(existsSync(join(dir, "projects.md")), "mirror written on save");
108
-
109
- service.update(saved.memory.id, { content: "a2" });
110
- assert.match(readFileSync(join(dir, "projects.md"), "utf8"), /a2/, "update re-syncs mirror");
111
-
112
- service.setForget(saved.memory.id, true);
113
- assert.ok(!existsSync(join(dir, "projects.md")), "forgotten entry removed from mirror");
114
-
115
- const second = service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
116
- assert.ok(existsSync(join(dir, "projects.md")), "mirror rewritten after re-save");
117
- service.remove(second.memory.id);
118
- assert.ok(!existsSync(join(dir, "projects.md")), "remove re-syncs mirror");
119
- } finally {
120
- rmSync(dir, { recursive: true, force: true });
121
- }
122
- });
123
-
124
- test("saveWithDedupe created branch keeps forgotten entries out of mirror", () => {
125
- const store = createStore(":memory:");
126
- const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
127
- const mirror = createMirror(dir);
128
- const service = createService({ store, mirror, config: {} });
129
- try {
130
- const a = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
131
- service.setForget(a.memory.id, true);
132
- service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
133
- const text = readFileSync(join(dir, "projects.md"), "utf8");
134
- assert.ok(!text.includes(a.memory.id), "forgotten A must not reappear in mirror");
135
- assert.ok(!text.includes("## A"), "forgotten A entry absent from mirror");
136
- assert.match(text, /## B/, "non-forgotten B present in mirror");
137
- } finally {
138
- rmSync(dir, { recursive: true, force: true });
139
- }
140
- });
141
-
142
- test("injectCandidates excludes archived entries", () => {
143
- const { store, service } = setup();
144
- const saved = service.saveWithDedupe({ type: "preference", title: "旧偏好", content: "old", importance: 5 });
145
- store.setArchived(saved.memory.id, true);
146
- const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
147
- assert.ok(!candidates.some((c) => c.id === saved.memory.id), "archived excluded");
148
- });
149
-
150
- test("summary memory is a candidate at top priority", () => {
151
- const { service } = setup();
152
- service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
153
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览内容", importance: 5 });
154
- const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
155
- assert.equal(candidates[0]?.type, "summary", "summary first even with competing high-importance preference");
156
- });
157
-
158
- test("write methods invoke onWrite hook when provided", () => {
159
- const { store } = setup();
160
- let called = 0;
161
- const svc = createService({ store, mirror: null, config: {}, onWrite: () => { called++; } });
162
- svc.saveWithDedupe({ type: "project", title: "a", content: "x" });
163
- assert.equal(called, 1, "saveWithDedupe hooks");
164
- svc.update(svc.all()[0].id, { content: "y" });
165
- assert.equal(called, 2, "update hooks");
166
- svc.setArchived(svc.all()[0].id, true);
167
- assert.equal(called, 2, "setArchived does not hook (not a content write)");
168
- });
169
-
170
- // --- transactions (item ②) + compare-and-set (item ①/③) --------------------
171
-
172
- test("service.transaction rolls back every step when the body throws", () => {
173
- const { store, service } = setup();
174
- let threw = false;
175
- try {
176
- service.transaction(() => {
177
- service.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
178
- service.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
179
- throw new Error("boom");
180
- });
181
- } catch { threw = true; }
182
- assert.equal(threw, true, "error propagates");
183
- assert.equal(store.count(), 0, "no partial writes after rollback");
184
- assert.ok(!store.all().some((m) => m.title === "原子A"), "step A rolled back");
185
- assert.ok(!store.all().some((m) => m.title === "原子B"), "step B rolled back");
186
- store.close();
187
- });
188
-
189
- test("service.transaction commits all steps atomically on success", () => {
190
- const { store, service } = setup();
191
- service.transaction(() => {
192
- service.saveWithDedupe({ type: "project", title: "甲", content: "x" });
193
- service.saveWithDedupe({ type: "project", title: "乙", content: "y" });
194
- });
195
- assert.equal(store.count(), 2, "both steps committed");
196
- store.close();
197
- });
198
-
199
- test("service.compareAndUpdate rejects a stale version token (no lost update)", () => {
200
- const { store, service } = setup();
201
- const { memory: m } = service.saveWithDedupe({ type: "history", title: "计数器", content: "count=0" });
202
- const baseline = service.getById(m.id);
203
- const first = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=1" });
204
- assert.ok(first, "current version CAS succeeds");
205
- const stale = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=2" });
206
- assert.equal(stale, undefined, "stale version CAS misses without writing");
207
- assert.equal(service.getById(m.id).content, "count=1", "increment not lost");
208
- store.close();
209
- });
210
-
211
- // --- Bug4: injectCandidates semantic-first recall (query) --------------------
212
-
213
- test("Bug4: injectCandidates with an empty query keeps the legacy rule-based selection", () => {
214
- const { service } = setup();
215
- service.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
216
- service.saveWithDedupe({ type: "preference", title: "p1", content: "偏好" });
217
- service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
218
- service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
219
- service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
220
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
221
- const legacy = service.injectCandidates({ maxItems: 5, threshold: 4 });
222
- const noQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: "" });
223
- const blankQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: " " });
224
- assert.deepEqual(noQuery.map((c) => c.id), legacy.map((c) => c.id), "empty query behaves identically to the old logic");
225
- assert.deepEqual(blankQuery.map((c) => c.id), legacy.map((c) => c.id), "whitespace-only query degrades too");
226
- assert.equal(legacy[0].type, "summary", "summary still leads");
227
- assert.ok(!legacy.some((c) => c.type === "history"), "history still excluded");
228
- });
229
-
230
- test("Bug4: injectCandidates ignores the query when hybridInject is disabled", () => {
231
- const { store } = setup();
232
- const svc = createService({ store, mirror: null, config: { hybridInject: false } });
233
- svc.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
234
- svc.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
235
- const noQuery = svc.injectCandidates({ maxItems: 5, threshold: 3 });
236
- const withQuery = svc.injectCandidates({ maxItems: 5, threshold: 3, query: "中文" });
237
- assert.deepEqual(withQuery.map((c) => c.id), noQuery.map((c) => c.id), "hybridInject off keeps rule-based ordering");
238
- });
239
-
240
- // --- Bug5: content_history FIFO + human-edited direct overwrite --------------
241
-
242
- test("Bug5: content_history grows FIFO across repeated same-title merges (capped at 20)", () => {
243
- const { store, service } = setup();
244
- service.saveWithDedupe({ type: "project", title: "流水", content: "v0" });
245
- for (let i = 1; i <= 25; i++) {
246
- service.saveWithDedupe({ type: "project", title: "流水", content: `v${i}` });
247
- }
248
- const row = store.all()[0];
249
- assert.ok(Array.isArray(row.content_history), "content_history is an array");
250
- assert.equal(row.content_history.length, 20, "FIFO cap of 20 respected");
251
- assert.ok(row.content_history[0].content.includes("v24"), "newest archived body kept at index 0");
252
- assert.ok(row.content_history[19].content.includes("v5"), "oldest kept entry");
253
- assert.ok(!row.content_history[19].content.includes("v6"), "entries older than the cap dropped");
254
- assert.ok(row.content.includes("v25"), "latest merge still appended to the live body");
255
- });
256
-
257
- test("Bug5: _humanEdited overwrite replaces content directly and archives the old version", () => {
258
- const { store, service } = setup();
259
- service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
260
- const result = service.saveWithDedupe({ type: "preference", title: "语言", content: "人工修正", _humanEdited: true });
261
- const row = store.getById(result.memory.id);
262
- assert.equal(row.content, "人工修正", "direct overwrite, no appended --- block");
263
- assert.ok(!row.content.includes("机器内容"), "old content not in the live body");
264
- assert.equal(row.content_history.length, 1);
265
- assert.equal(row.content_history[0].content, "机器内容");
266
- assert.equal(row.content_history[0].source, "human_override");
267
- });
268
-
269
- // --- Bug7: memory quality filter ---------------------------------------------
270
-
271
- function qualitySetup(config = {}) {
272
- const store = createStore(":memory:");
273
- const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true, ...config } } });
274
- return { store, service };
275
- }
276
-
277
- test("Bug7: meta-memory is scored below the degrade threshold but still stored", () => {
278
- const { store, service } = qualitySetup();
279
- const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
280
- assert.equal(result.action, "created");
281
- assert.ok(result.memory.quality_score < 60, `meta-memory degraded, got ${result.memory.quality_score}`);
282
- assert.ok(result.memory.quality_score >= 30, "still above the archive threshold");
283
- assert.equal(result.memory.archived, false, "not archived");
284
- assert.equal(store.count(), 1, "still stored and searchable");
285
- });
286
-
287
- test("Bug7: short content is archived and tagged low_quality", () => {
288
- const { store, service } = qualitySetup();
289
- const result = service.saveWithDedupe({ type: "project", title: "备忘", content: "x" });
290
- const row = store.getById(result.memory.id);
291
- assert.equal(row.archived, true, "short content archived");
292
- assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
293
- assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
294
- });
295
-
296
- test("Bug7: near-duplicate content is archived and tagged low_quality", () => {
297
- const { store, service } = qualitySetup();
298
- const base = "今天下午去操场跑步三圈然后回来洗澡";
299
- service.saveWithDedupe({ type: "history", title: "记录A", content: base });
300
- const result = service.saveWithDedupe({ type: "history", title: "记录B", content: `${base}${base}${base}` });
301
- const row = store.getById(result.memory.id);
302
- assert.equal(row.archived, true, "near-duplicate archived");
303
- assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
304
- assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
305
- });
306
-
307
- test("Bug7: repetitive (dedup<0.3) content is scored into the degraded band", () => {
308
- const { store, service } = qualitySetup();
309
- const result = service.saveWithDedupe({ type: "history", title: "唠叨", content: "好好好好好好好好好好好好好好好好好好" });
310
- const row = store.getById(result.memory.id);
311
- assert.ok(row.quality_score >= 30 && row.quality_score < 60, `repetitive-only degraded, got ${row.quality_score}`);
312
- assert.equal(row.archived, false, "not archived (only a single non-meta signal)");
313
- });
314
-
315
- test("Bug7: memoryQualityFilter.enabled=false skips scoring entirely", () => {
316
- const store = createStore(":memory:");
317
- const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: false } } });
318
- const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
319
- const row = store.getById(result.memory.id);
320
- assert.ok(row.quality_score == null, "no quality_score written");
321
- assert.equal(row.archived, false, "not archived");
322
- assert.ok(!(row.tags ?? []).includes("low_quality"), "no low_quality tag");
323
- });
324
-
325
- test("Bug7: injection ranking re-weights by quality_score (degraded memories rank lower)", () => {
326
- const { store } = setup();
327
- const svc = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true } } });
328
- svc.saveWithDedupe({ type: "preference", title: "高质量", content: "用户喜欢读科幻小说和散文" });
329
- svc.saveWithDedupe({ type: "preference", title: "元记忆", content: "我需要记住用户偏好的完整清单防止忘记" });
330
- const candidates = svc.injectCandidates({ maxItems: 5, threshold: 3 });
331
- assert.equal(candidates[0].title, "高质量", "100-quality preference leads the degraded one");
332
- assert.equal(candidates[1].title, "元记忆");
333
- });
334
-
335
- // --- session lifecycle (v0.6.0): dispose/restore by session -----------------
336
- // session_disposed_at is orthogonal to `archived`: dispose hides only entries
337
- // born in the deleted session, and restore never resurrects user-archived ones.
338
-
339
- test("disposeBySession marks only that session's memories", () => {
340
- const store = createStore(":memory:");
341
- const svc = createService({ store, mirror: null, config: {} });
342
- const s1 = svc.saveWithDedupe({ type: "project", title: "会话A记忆", content: "x", session_id: "sess-1" });
343
- svc.saveWithDedupe({ type: "project", title: "会话B记忆", content: "y", session_id: "sess-2" });
344
-
345
- const res = svc.disposeBySession("sess-1");
346
- assert.deepEqual(res, { disposed: 1 });
347
- assert.ok(svc.getById(s1.memory.id).session_disposed_at, "session-1 memory marked disposed");
348
- // disposed memories vanish from default list (like archived)
349
- assert.ok(!svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "disposed hidden from default list");
350
- const other = svc.list({ type: "project", includeDisposed: true });
351
- assert.ok(other.some((m) => m.title === "会话B记忆" && !m.session_disposed_at), "other session untouched");
352
- });
353
-
354
- test("restoreBySession clears the dispose mark and makes entries visible again", () => {
355
- const store = createStore(":memory:");
356
- const svc = createService({ store, mirror: null, config: {} });
357
- const s1 = svc.saveWithDedupe({ type: "project", title: "存档会话", content: "x", session_id: "sess-9" });
358
- svc.disposeBySession("sess-9");
359
-
360
- assert.ok(!svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "hidden while disposed");
361
- const res = svc.restoreBySession("sess-9");
362
- assert.deepEqual(res, { restored: 1 });
363
- assert.equal(svc.getById(s1.memory.id).session_disposed_at, undefined, "dispose mark cleared");
364
- assert.ok(svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "visible again");
365
- });
366
-
367
- test("disposeBySession is idempotent: re-disposing returns 0", () => {
368
- const store = createStore(":memory:");
369
- const svc = createService({ store, mirror: null, config: {} });
370
- svc.saveWithDedupe({ type: "project", title: "重复销毁", content: "x", session_id: "sess-3" });
371
-
372
- assert.deepEqual(svc.disposeBySession("sess-3"), { disposed: 1 });
373
- assert.deepEqual(svc.disposeBySession("sess-3"), { disposed: 0 }, "no rows flipped the second time");
374
- });
375
-
376
- test("disposeBySession on an unknown session is a no-op", () => {
377
- const store = createStore(":memory:");
378
- const svc = createService({ store, mirror: null, config: {} });
379
- assert.deepEqual(svc.disposeBySession("nope"), { disposed: 0 });
380
- assert.deepEqual(svc.restoreBySession("nope"), { restored: 0 });
381
- });
382
-
383
- test("legacy rows without session_id are never touched by session lifecycle", () => {
384
- const store = createStore(":memory:");
385
- const svc = createService({ store, mirror: null, config: {} });
386
- const legacy = svc.saveWithDedupe({ type: "preference", title: "全局记忆", content: "no session", session_id: undefined });
387
-
388
- svc.disposeBySession("sess-x");
389
- assert.equal(svc.getById(legacy.memory.id).session_disposed_at, undefined, "global memory survives session dispose");
390
- });
391
-
392
- test("restoreBySession does NOT resurrect user-archived memories (orthogonal)", () => {
393
- const store = createStore(":memory:");
394
- const svc = createService({ store, mirror: null, config: {} });
395
- // user manually archived this one (archived=true), then the session is disposed
396
- const { memory: userArchived } = svc.saveWithDedupe({ type: "decision", title: "手动归档", content: "x", session_id: "sess-4" });
397
- svc.setArchived(userArchived.id, true);
398
- svc.disposeBySession("sess-4");
399
-
400
- svc.restoreBySession("sess-4");
401
- assert.equal(svc.getById(userArchived.id).archived, true, "user archive survives restore");
402
- assert.equal(svc.getById(userArchived.id).session_disposed_at, undefined, "dispose mark cleared but archive kept");
403
- assert.ok(!svc.list({ type: "decision" }).some((m) => m.id === userArchived.id), "still hidden by user archive");
404
- });
405
-
406
- test("listBySession returns only that session's memories via wire DTOs", () => {
407
- const store = createStore(":memory:");
408
- const svc = createService({ store, mirror: null, config: {} });
409
- const { memory } = svc.saveWithDedupe({ type: "decision", title: "会话决策", content: "d", session_id: "sess-7" });
410
- svc.saveWithDedupe({ type: "decision", title: "别会话", content: "e", session_id: "sess-8" });
411
-
412
- const rows = svc.listBySession("sess-7");
413
- assert.equal(rows.length, 1);
414
- assert.equal(rows[0].id, memory.id);
415
- assert.equal(rows[0].title, "会话决策");
416
- assert.equal(rows[0].session_id, "sess-7");
417
- });
418
-
419
- test("listBySession DTO hides disposed by default and flags it when included", () => {
420
- const store = createStore(":memory:");
421
- const svc = createService({ store, mirror: null, config: {} });
422
- const { memory } = svc.saveWithDedupe({ type: "decision", title: "会话决策", content: "d", session_id: "sess-9" });
423
- svc.disposeBySession("sess-9");
424
-
425
- assert.equal(svc.listBySession("sess-9").length, 0, "disposed hidden by default");
426
- const visible = svc.listBySession("sess-9", { includeDisposed: true });
427
- assert.equal(visible.length, 1);
428
- assert.equal(visible[0].id, memory.id);
429
- assert.equal(visible[0].disposed, true, "DTO carries disposed marker so restore is not blind");
430
-
431
- svc.restoreBySession("sess-9");
432
- const restored = svc.listBySession("sess-9");
433
- assert.equal(restored.length, 1, "restore brings it back to default view");
434
- assert.equal(restored[0].disposed, undefined, "marker cleared after restore");
435
- });
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
+ // session_id rides the DTO when present (session lifecycle needs it)
80
+ const withSession = service.saveWithDedupe({ type: "decision", title: "带会话", content: "y", session_id: "sess-x" });
81
+ const dto2 = service.toApiList([withSession.memory]);
82
+ assert.equal(dto2[0].session_id, "sess-x");
83
+ });
84
+
85
+ test("mergeHumanEdits skips edits without id and keeps applying the rest", () => {
86
+ const { store, service } = setup();
87
+ const first = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
88
+ const second = service.saveWithDedupe({ type: "preference", title: "主题", content: "机器内容" });
89
+ const edits = [
90
+ { content: "缺少 id 的损坏条目" },
91
+ { id: first.memory.id, title: "语言", content: "人类编辑内容" },
92
+ { id: second.memory.id, title: "主题", content: "第二个人类编辑" }
93
+ ];
94
+ const applied = service.mergeHumanEdits("preference", edits);
95
+ assert.equal(applied, 2, "returns count of applied edits, not input length");
96
+ assert.equal(store.getById(first.memory.id).content, "人类编辑内容");
97
+ assert.equal(store.getById(second.memory.id).content, "第二个人类编辑");
98
+ });
99
+
100
+ test("mutations through passthroughs sync mirror; forgotten entries stay out of it", () => {
101
+ const store = createStore(":memory:");
102
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
103
+ const mirror = createMirror(dir);
104
+ const service = createService({ store, mirror, config: {} });
105
+ try {
106
+ const saved = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
107
+ assert.ok(existsSync(join(dir, "projects.md")), "mirror written on save");
108
+
109
+ service.update(saved.memory.id, { content: "a2" });
110
+ assert.match(readFileSync(join(dir, "projects.md"), "utf8"), /a2/, "update re-syncs mirror");
111
+
112
+ service.setForget(saved.memory.id, true);
113
+ assert.ok(!existsSync(join(dir, "projects.md")), "forgotten entry removed from mirror");
114
+
115
+ const second = service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
116
+ assert.ok(existsSync(join(dir, "projects.md")), "mirror rewritten after re-save");
117
+ service.remove(second.memory.id);
118
+ assert.ok(!existsSync(join(dir, "projects.md")), "remove re-syncs mirror");
119
+ } finally {
120
+ rmSync(dir, { recursive: true, force: true });
121
+ }
122
+ });
123
+
124
+ test("saveWithDedupe created branch keeps forgotten entries out of mirror", () => {
125
+ const store = createStore(":memory:");
126
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-service-"));
127
+ const mirror = createMirror(dir);
128
+ const service = createService({ store, mirror, config: {} });
129
+ try {
130
+ const a = service.saveWithDedupe({ type: "project", title: "A", content: "a", importance: 4 });
131
+ service.setForget(a.memory.id, true);
132
+ service.saveWithDedupe({ type: "project", title: "B", content: "b", importance: 2 });
133
+ const text = readFileSync(join(dir, "projects.md"), "utf8");
134
+ assert.ok(!text.includes(a.memory.id), "forgotten A must not reappear in mirror");
135
+ assert.ok(!text.includes("## A"), "forgotten A entry absent from mirror");
136
+ assert.match(text, /## B/, "non-forgotten B present in mirror");
137
+ } finally {
138
+ rmSync(dir, { recursive: true, force: true });
139
+ }
140
+ });
141
+
142
+ test("injectCandidates excludes archived entries", () => {
143
+ const { store, service } = setup();
144
+ const saved = service.saveWithDedupe({ type: "preference", title: "旧偏好", content: "old", importance: 5 });
145
+ store.setArchived(saved.memory.id, true);
146
+ const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
147
+ assert.ok(!candidates.some((c) => c.id === saved.memory.id), "archived excluded");
148
+ });
149
+
150
+ test("summary memory is a candidate at top priority", () => {
151
+ const { service } = setup();
152
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
153
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览内容", importance: 5 });
154
+ const candidates = service.injectCandidates({ maxItems: 5, threshold: 3 });
155
+ assert.equal(candidates[0]?.type, "summary", "summary first even with competing high-importance preference");
156
+ });
157
+
158
+ test("write methods invoke onWrite hook when provided", () => {
159
+ const { store } = setup();
160
+ let called = 0;
161
+ const svc = createService({ store, mirror: null, config: {}, onWrite: () => { called++; } });
162
+ svc.saveWithDedupe({ type: "project", title: "a", content: "x" });
163
+ assert.equal(called, 1, "saveWithDedupe hooks");
164
+ svc.update(svc.all()[0].id, { content: "y" });
165
+ assert.equal(called, 2, "update hooks");
166
+ svc.setArchived(svc.all()[0].id, true);
167
+ assert.equal(called, 2, "setArchived does not hook (not a content write)");
168
+ });
169
+
170
+ // --- transactions (item ②) + compare-and-set (item ①/③) --------------------
171
+
172
+ test("service.transaction rolls back every step when the body throws", () => {
173
+ const { store, service } = setup();
174
+ let threw = false;
175
+ try {
176
+ service.transaction(() => {
177
+ service.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
178
+ service.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
179
+ throw new Error("boom");
180
+ });
181
+ } catch { threw = true; }
182
+ assert.equal(threw, true, "error propagates");
183
+ assert.equal(store.count(), 0, "no partial writes after rollback");
184
+ assert.ok(!store.all().some((m) => m.title === "原子A"), "step A rolled back");
185
+ assert.ok(!store.all().some((m) => m.title === "原子B"), "step B rolled back");
186
+ store.close();
187
+ });
188
+
189
+ test("service.transaction commits all steps atomically on success", () => {
190
+ const { store, service } = setup();
191
+ service.transaction(() => {
192
+ service.saveWithDedupe({ type: "project", title: "甲", content: "x" });
193
+ service.saveWithDedupe({ type: "project", title: "乙", content: "y" });
194
+ });
195
+ assert.equal(store.count(), 2, "both steps committed");
196
+ store.close();
197
+ });
198
+
199
+ test("service.compareAndUpdate rejects a stale version token (no lost update)", () => {
200
+ const { store, service } = setup();
201
+ const { memory: m } = service.saveWithDedupe({ type: "history", title: "计数器", content: "count=0" });
202
+ const baseline = service.getById(m.id);
203
+ const first = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=1" });
204
+ assert.ok(first, "current version CAS succeeds");
205
+ const stale = service.compareAndUpdate(m.id, baseline.updated_at, { content: "count=2" });
206
+ assert.equal(stale, undefined, "stale version CAS misses without writing");
207
+ assert.equal(service.getById(m.id).content, "count=1", "increment not lost");
208
+ store.close();
209
+ });
210
+
211
+ // --- Bug4: injectCandidates semantic-first recall (query) --------------------
212
+
213
+ test("Bug4: injectCandidates with an empty query keeps the legacy rule-based selection", () => {
214
+ const { service } = setup();
215
+ service.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
216
+ service.saveWithDedupe({ type: "preference", title: "p1", content: "偏好" });
217
+ service.saveWithDedupe({ type: "project", title: "low", content: "低", importance: 2 });
218
+ service.saveWithDedupe({ type: "project", title: "high", content: "高", importance: 5 });
219
+ service.saveWithDedupe({ type: "history", title: "h", content: "历史", importance: 5 });
220
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
221
+ const legacy = service.injectCandidates({ maxItems: 5, threshold: 4 });
222
+ const noQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: "" });
223
+ const blankQuery = service.injectCandidates({ maxItems: 5, threshold: 4, query: " " });
224
+ assert.deepEqual(noQuery.map((c) => c.id), legacy.map((c) => c.id), "empty query behaves identically to the old logic");
225
+ assert.deepEqual(blankQuery.map((c) => c.id), legacy.map((c) => c.id), "whitespace-only query degrades too");
226
+ assert.equal(legacy[0].type, "summary", "summary still leads");
227
+ assert.ok(!legacy.some((c) => c.type === "history"), "history still excluded");
228
+ });
229
+
230
+ test("Bug4: injectCandidates ignores the query when hybridInject is disabled", () => {
231
+ const { store } = setup();
232
+ const svc = createService({ store, mirror: null, config: { hybridInject: false } });
233
+ svc.saveWithDedupe({ type: "preference", title: "p0", content: "偏好" });
234
+ svc.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "总览", importance: 5 });
235
+ const noQuery = svc.injectCandidates({ maxItems: 5, threshold: 3 });
236
+ const withQuery = svc.injectCandidates({ maxItems: 5, threshold: 3, query: "中文" });
237
+ assert.deepEqual(withQuery.map((c) => c.id), noQuery.map((c) => c.id), "hybridInject off keeps rule-based ordering");
238
+ });
239
+
240
+ // --- Bug5: content_history FIFO + human-edited direct overwrite --------------
241
+
242
+ test("Bug5: content_history grows FIFO across repeated same-title merges (capped at 20)", () => {
243
+ const { store, service } = setup();
244
+ service.saveWithDedupe({ type: "project", title: "流水", content: "v0" });
245
+ for (let i = 1; i <= 25; i++) {
246
+ service.saveWithDedupe({ type: "project", title: "流水", content: `v${i}` });
247
+ }
248
+ const row = store.all()[0];
249
+ assert.ok(Array.isArray(row.content_history), "content_history is an array");
250
+ assert.equal(row.content_history.length, 20, "FIFO cap of 20 respected");
251
+ assert.ok(row.content_history[0].content.includes("v24"), "newest archived body kept at index 0");
252
+ assert.ok(row.content_history[19].content.includes("v5"), "oldest kept entry");
253
+ assert.ok(!row.content_history[19].content.includes("v6"), "entries older than the cap dropped");
254
+ assert.ok(row.content.includes("v25"), "latest merge still appended to the live body");
255
+ });
256
+
257
+ test("Bug5: _humanEdited overwrite replaces content directly and archives the old version", () => {
258
+ const { store, service } = setup();
259
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
260
+ const result = service.saveWithDedupe({ type: "preference", title: "语言", content: "人工修正", _humanEdited: true });
261
+ const row = store.getById(result.memory.id);
262
+ assert.equal(row.content, "人工修正", "direct overwrite, no appended --- block");
263
+ assert.ok(!row.content.includes("机器内容"), "old content not in the live body");
264
+ assert.equal(row.content_history.length, 1);
265
+ assert.equal(row.content_history[0].content, "机器内容");
266
+ assert.equal(row.content_history[0].source, "human_override");
267
+ });
268
+
269
+ // --- Bug7: memory quality filter ---------------------------------------------
270
+
271
+ function qualitySetup(config = {}) {
272
+ const store = createStore(":memory:");
273
+ const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true, ...config } } });
274
+ return { store, service };
275
+ }
276
+
277
+ test("Bug7: meta-memory is scored below the degrade threshold but still stored", () => {
278
+ const { store, service } = qualitySetup();
279
+ const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
280
+ assert.equal(result.action, "created");
281
+ assert.ok(result.memory.quality_score < 60, `meta-memory degraded, got ${result.memory.quality_score}`);
282
+ assert.ok(result.memory.quality_score >= 30, "still above the archive threshold");
283
+ assert.equal(result.memory.archived, false, "not archived");
284
+ assert.equal(store.count(), 1, "still stored and searchable");
285
+ });
286
+
287
+ test("Bug7: short content is archived and tagged low_quality", () => {
288
+ const { store, service } = qualitySetup();
289
+ const result = service.saveWithDedupe({ type: "project", title: "备忘", content: "x" });
290
+ const row = store.getById(result.memory.id);
291
+ assert.equal(row.archived, true, "short content archived");
292
+ assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
293
+ assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
294
+ });
295
+
296
+ test("Bug7: near-duplicate content is archived and tagged low_quality", () => {
297
+ const { store, service } = qualitySetup();
298
+ const base = "今天下午去操场跑步三圈然后回来洗澡";
299
+ service.saveWithDedupe({ type: "history", title: "记录A", content: base });
300
+ const result = service.saveWithDedupe({ type: "history", title: "记录B", content: `${base}${base}${base}` });
301
+ const row = store.getById(result.memory.id);
302
+ assert.equal(row.archived, true, "near-duplicate archived");
303
+ assert.ok(row.tags.includes("low_quality"), "low_quality tag added");
304
+ assert.ok(row.quality_score < 30, `score below archive threshold: ${row.quality_score}`);
305
+ });
306
+
307
+ test("Bug7: repetitive (dedup<0.3) content is scored into the degraded band", () => {
308
+ const { store, service } = qualitySetup();
309
+ const result = service.saveWithDedupe({ type: "history", title: "唠叨", content: "好好好好好好好好好好好好好好好好好好" });
310
+ const row = store.getById(result.memory.id);
311
+ assert.ok(row.quality_score >= 30 && row.quality_score < 60, `repetitive-only degraded, got ${row.quality_score}`);
312
+ assert.equal(row.archived, false, "not archived (only a single non-meta signal)");
313
+ });
314
+
315
+ test("Bug7: memoryQualityFilter.enabled=false skips scoring entirely", () => {
316
+ const store = createStore(":memory:");
317
+ const service = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: false } } });
318
+ const result = service.saveWithDedupe({ type: "project", title: "记忆系统规则", content: "我需要记住用户喜欢中文阅读长篇小说和散文" });
319
+ const row = store.getById(result.memory.id);
320
+ assert.ok(row.quality_score == null, "no quality_score written");
321
+ assert.equal(row.archived, false, "not archived");
322
+ assert.ok(!(row.tags ?? []).includes("low_quality"), "no low_quality tag");
323
+ });
324
+
325
+ test("Bug7: injection ranking re-weights by quality_score (degraded memories rank lower)", () => {
326
+ const { store } = setup();
327
+ const svc = createService({ store, mirror: null, config: { memoryQualityFilter: { enabled: true } } });
328
+ svc.saveWithDedupe({ type: "preference", title: "高质量", content: "用户喜欢读科幻小说和散文" });
329
+ svc.saveWithDedupe({ type: "preference", title: "元记忆", content: "我需要记住用户偏好的完整清单防止忘记" });
330
+ const candidates = svc.injectCandidates({ maxItems: 5, threshold: 3 });
331
+ assert.equal(candidates[0].title, "高质量", "100-quality preference leads the degraded one");
332
+ assert.equal(candidates[1].title, "元记忆");
333
+ });
334
+
335
+ // --- session lifecycle (v0.6.0): dispose/restore by session -----------------
336
+ // session_disposed_at is orthogonal to `archived`: dispose hides only entries
337
+ // born in the deleted session, and restore never resurrects user-archived ones.
338
+
339
+ test("disposeBySession marks only that session's memories", () => {
340
+ const store = createStore(":memory:");
341
+ const svc = createService({ store, mirror: null, config: {} });
342
+ const s1 = svc.saveWithDedupe({ type: "project", title: "会话A记忆", content: "x", session_id: "sess-1" });
343
+ svc.saveWithDedupe({ type: "project", title: "会话B记忆", content: "y", session_id: "sess-2" });
344
+
345
+ const res = svc.disposeBySession("sess-1");
346
+ assert.deepEqual(res, { disposed: 1 });
347
+ assert.ok(svc.getById(s1.memory.id).session_disposed_at, "session-1 memory marked disposed");
348
+ // disposed memories vanish from default list (like archived)
349
+ assert.ok(!svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "disposed hidden from default list");
350
+ const other = svc.list({ type: "project", includeDisposed: true });
351
+ assert.ok(other.some((m) => m.title === "会话B记忆" && !m.session_disposed_at), "other session untouched");
352
+ });
353
+
354
+ test("restoreBySession clears the dispose mark and makes entries visible again", () => {
355
+ const store = createStore(":memory:");
356
+ const svc = createService({ store, mirror: null, config: {} });
357
+ const s1 = svc.saveWithDedupe({ type: "project", title: "存档会话", content: "x", session_id: "sess-9" });
358
+ svc.disposeBySession("sess-9");
359
+
360
+ assert.ok(!svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "hidden while disposed");
361
+ const res = svc.restoreBySession("sess-9");
362
+ assert.deepEqual(res, { restored: 1 });
363
+ assert.equal(svc.getById(s1.memory.id).session_disposed_at, undefined, "dispose mark cleared");
364
+ assert.ok(svc.list({ type: "project" }).some((m) => m.id === s1.memory.id), "visible again");
365
+ });
366
+
367
+ test("disposeBySession is idempotent: re-disposing returns 0", () => {
368
+ const store = createStore(":memory:");
369
+ const svc = createService({ store, mirror: null, config: {} });
370
+ svc.saveWithDedupe({ type: "project", title: "重复销毁", content: "x", session_id: "sess-3" });
371
+
372
+ assert.deepEqual(svc.disposeBySession("sess-3"), { disposed: 1 });
373
+ assert.deepEqual(svc.disposeBySession("sess-3"), { disposed: 0 }, "no rows flipped the second time");
374
+ });
375
+
376
+ test("disposeBySession on an unknown session is a no-op", () => {
377
+ const store = createStore(":memory:");
378
+ const svc = createService({ store, mirror: null, config: {} });
379
+ assert.deepEqual(svc.disposeBySession("nope"), { disposed: 0 });
380
+ assert.deepEqual(svc.restoreBySession("nope"), { restored: 0 });
381
+ });
382
+
383
+ test("legacy rows without session_id are never touched by session lifecycle", () => {
384
+ const store = createStore(":memory:");
385
+ const svc = createService({ store, mirror: null, config: {} });
386
+ const legacy = svc.saveWithDedupe({ type: "preference", title: "全局记忆", content: "no session", session_id: undefined });
387
+
388
+ svc.disposeBySession("sess-x");
389
+ assert.equal(svc.getById(legacy.memory.id).session_disposed_at, undefined, "global memory survives session dispose");
390
+ });
391
+
392
+ test("restoreBySession does NOT resurrect user-archived memories (orthogonal)", () => {
393
+ const store = createStore(":memory:");
394
+ const svc = createService({ store, mirror: null, config: {} });
395
+ // user manually archived this one (archived=true), then the session is disposed
396
+ const { memory: userArchived } = svc.saveWithDedupe({ type: "decision", title: "手动归档", content: "x", session_id: "sess-4" });
397
+ svc.setArchived(userArchived.id, true);
398
+ svc.disposeBySession("sess-4");
399
+
400
+ svc.restoreBySession("sess-4");
401
+ assert.equal(svc.getById(userArchived.id).archived, true, "user archive survives restore");
402
+ assert.equal(svc.getById(userArchived.id).session_disposed_at, undefined, "dispose mark cleared but archive kept");
403
+ assert.ok(!svc.list({ type: "decision" }).some((m) => m.id === userArchived.id), "still hidden by user archive");
404
+ });
405
+
406
+ test("listBySession returns only that session's memories via wire DTOs", () => {
407
+ const store = createStore(":memory:");
408
+ const svc = createService({ store, mirror: null, config: {} });
409
+ const { memory } = svc.saveWithDedupe({ type: "decision", title: "会话决策", content: "d", session_id: "sess-7" });
410
+ svc.saveWithDedupe({ type: "decision", title: "别会话", content: "e", session_id: "sess-8" });
411
+
412
+ const rows = svc.listBySession("sess-7");
413
+ assert.equal(rows.length, 1);
414
+ assert.equal(rows[0].id, memory.id);
415
+ assert.equal(rows[0].title, "会话决策");
416
+ assert.equal(rows[0].session_id, "sess-7");
417
+ });
418
+
419
+ test("listBySession DTO hides disposed by default and flags it when included", () => {
420
+ const store = createStore(":memory:");
421
+ const svc = createService({ store, mirror: null, config: {} });
422
+ const { memory } = svc.saveWithDedupe({ type: "decision", title: "会话决策", content: "d", session_id: "sess-9" });
423
+ svc.disposeBySession("sess-9");
424
+
425
+ assert.equal(svc.listBySession("sess-9").length, 0, "disposed hidden by default");
426
+ const visible = svc.listBySession("sess-9", { includeDisposed: true });
427
+ assert.equal(visible.length, 1);
428
+ assert.equal(visible[0].id, memory.id);
429
+ assert.equal(visible[0].disposed, true, "DTO carries disposed marker so restore is not blind");
430
+
431
+ svc.restoreBySession("sess-9");
432
+ const restored = svc.listBySession("sess-9");
433
+ assert.equal(restored.length, 1, "restore brings it back to default view");
434
+ assert.equal(restored[0].disposed, undefined, "marker cleared after restore");
435
+ });