@modusensus/dsh-mneme 0.8.2 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -633
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4362
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -500
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -513
  22. package/lib/inject.js +299 -253
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -308
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -260
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -0
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2071
  42. package/lib/settings.js +430 -419
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -500
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -513
  75. package/src/inject.js +299 -253
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -308
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -260
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -0
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2071
  95. package/src/settings.js +430 -419
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1481
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -0
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -229
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -0
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
@@ -1,373 +1,373 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { createSleepScheduler, runSleep } from "../src/dream/sleep.js";
4
- import { createStore } from "../src/store.js";
5
- import { createService } from "../src/service.js";
6
- import { createVectorIndex } from "../src/vector-index.js";
7
-
8
- // Mock embedder: every query maps to [1,0,0] so vectors are identical unless a
9
- // test pre-seeds a custom vector via vectorIndex.saveEmbedding.
10
- const embedder = {
11
- embedSingle: async () => [1, 0, 0],
12
- embed: async () => [1, 0, 0],
13
- schedule: () => {},
14
- modelHash: "mock#1",
15
- dimension: 3
16
- };
17
-
18
- // Deterministic LLM: onConsolidation(userText) => decisions JSON string.
19
- function mockCtx(onConsolidation, selection = { provider: "mock", model: "sleep-model" }) {
20
- return {
21
- logger: { warn: () => {}, info: () => {} },
22
- agentDefaultModel: { currentSelection: () => selection },
23
- llm: {
24
- async *stream(options) {
25
- const userText = options.messages.find((m) => m.role === "user")?.content?.[0]?.text ?? "";
26
- const reply = onConsolidation ? onConsolidation(userText) : "[]";
27
- yield { type: "text-delta", index: 0, text: reply };
28
- yield { type: "finish", reason: { kind: "stop" } };
29
- }
30
- }
31
- };
32
- }
33
-
34
- function baseConfig(overrides = {}) {
35
- return {
36
- sleepModeEnabled: true,
37
- sleepIdleMinutes: 5,
38
- sleepMinIntervalHours: 8,
39
- sleepConflictStrictness: "normal",
40
- sleepArchiveDays: 30,
41
- sleepCompressDays: 90,
42
- sleepPatternMinMemories: 100,
43
- sleepMaxPatternPerRun: 3,
44
- ...overrides
45
- };
46
- }
47
-
48
- // v0.7.0 heat 双保护默认保守:默认 heatTypeDecay 下 project 记忆 40 天热值
49
- // ≈0.55、100 天 ≈0.28,始终高于 sleepHeatThreshold(0.05),demotion 不触发。
50
- // 降级语义测试把 project 的 λ 调快到 0.02(40 天热值≈0.03),复现"时间窗冷态
51
- // 即降级"的旧路径;默认保守语义由 sleep-heat.test.js 单独覆盖。
52
- function demotionConfig(overrides = {}) {
53
- return baseConfig({ heatTypeDecay: { project: 0.02 }, ...overrides });
54
- }
55
-
56
- function setup() {
57
- const store = createStore(":memory:");
58
- const service = createService({ store, mirror: null, config: {} });
59
- const vectorIndex = createVectorIndex({ store });
60
- service.setEmbedder(embedder);
61
- service.setVectorIndex(vectorIndex);
62
- return { store, service, vectorIndex };
63
- }
64
-
65
- function makeMemory(service, title, content, type = "project") {
66
- return service.saveWithDedupe({ type, title, content, importance: 3 }).memory;
67
- }
68
-
69
- // ------------------------------------------------------------ scheduler
70
-
71
- test("sleep: scheduler does not run when disabled", () => {
72
- const { service, store } = setup();
73
- const sched = createSleepScheduler({
74
- service, config: baseConfig({ sleepModeEnabled: false }), logger: { warn: () => {} },
75
- onRun: async () => ({ ok: true }),
76
- now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
77
- });
78
- assert.equal(sched.shouldRun(1_000_000 + 60 * 60000), false, "disabled never schedules");
79
- store.close();
80
- });
81
-
82
- test("sleep: scheduler fires once idle window elapses", () => {
83
- const { service, store } = setup();
84
- const sched = createSleepScheduler({
85
- service, config: baseConfig(), logger: { warn: () => {} },
86
- onRun: async () => ({ ok: true }),
87
- now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
88
- });
89
- assert.equal(sched.shouldRun(1_000_000 + 4 * 60000), false, "still within idle window");
90
- assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "idle window elapsed");
91
- store.close();
92
- });
93
-
94
- test("sleep: noteWrite resets the idle clock (stale-timer guard)", () => {
95
- const { service, store } = setup();
96
- let now = 1_000_000;
97
- const sched = createSleepScheduler({
98
- service, config: baseConfig(), logger: { warn: () => {} },
99
- onRun: async () => ({ ok: true }),
100
- now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
101
- });
102
- assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle after 6min");
103
- now = 1_000_000 + 6 * 60000;
104
- sched.noteWrite();
105
- assert.equal(sched.shouldRun(now), false, "write resets idle clock");
106
- assert.equal(sched.shouldRun(now + 4 * 60000), false, "still idle-pending after reset");
107
- assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle again after fresh window");
108
- store.close();
109
- });
110
-
111
- test("sleep: first-ever run is not blocked by min interval (lastRunAt=0)", () => {
112
- const { service, store } = setup();
113
- const sched = createSleepScheduler({
114
- service, config: baseConfig(), logger: { warn: () => {} },
115
- onRun: async () => ({ ok: true }),
116
- now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
117
- });
118
- assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "first run allowed");
119
- store.close();
120
- });
121
-
122
- test("sleep: min interval blocks a re-run within the window, allows after", async () => {
123
- const { service, store } = setup();
124
- let now = 1_000_000;
125
- const sched = createSleepScheduler({
126
- service, config: baseConfig(), logger: { warn: () => {} },
127
- onRun: async () => ({ ok: true }),
128
- now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
129
- });
130
- now = 1_000_000 + 6 * 60000; // idle satisfied
131
- const ok = await sched.maybeSchedule();
132
- assert.equal(ok, true, "first run executed");
133
- assert.equal(sched.shouldRun(now + 1 * 3600000), false, "1h later still inside 8h min interval");
134
- assert.equal(sched.shouldRun(now + 9 * 3600000), true, "9h later past min interval → allowed");
135
- store.close();
136
- });
137
-
138
- test("sleep: maybeSchedule enqueues via service and serializes with other work", async () => {
139
- const { service, store } = setup();
140
- const config = baseConfig();
141
- let now = 1_000_000;
142
- let order = [];
143
- const sched = createSleepScheduler({
144
- service, config, logger: { warn: () => {} },
145
- onRun: async () => { order.push("sleep"); return { ok: true, applied: 7 }; },
146
- now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
147
- });
148
- now = 1_000_000 + 6 * 60000;
149
- const p1 = service.enqueue(async () => { order.push("a"); });
150
- const p2 = sched.maybeSchedule();
151
- await p1;
152
- const result = await p2;
153
- assert.equal(result, true, "run result propagated through enqueue");
154
- assert.deepEqual(order, ["a", "sleep"], "sleep run serialized behind queued work");
155
- store.close();
156
- });
157
-
158
- test("sleep: dispose clears the timer and prevents further runs", async () => {
159
- const { service, store } = setup();
160
- let cleared = false;
161
- const sched = createSleepScheduler({
162
- service, config: baseConfig(), logger: { warn: () => {} },
163
- onRun: async () => ({ ok: true }),
164
- now: () => 1_000_000,
165
- setTimeoutFn: () => 1,
166
- clearTimeoutFn: () => { cleared = true; }
167
- });
168
- // #187 起构造即挂表——dispose 必须能清掉这张(以及 noteWrite 重挂过的任何)表。
169
- assert.equal(cleared, false, "timer armed at construction, not yet cleared");
170
- await sched.dispose();
171
- assert.equal(cleared, true, "idle timer cleared on dispose");
172
- assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), false, "disposed never runs");
173
- store.close();
174
- });
175
-
176
- // ------------------------------------------------------------ runSleep phases
177
-
178
- test("sleep: demotion shrinks cold memory to summary, keeps _full_content", async () => {
179
- const { service, store } = setup();
180
- const now = Date.now();
181
- const m = makeMemory(service, "cold", "原内容".repeat(60), "project");
182
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
183
- const ctx = mockCtx(() => "[]");
184
- const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
185
- const after = service.getById(m.id);
186
- assert.equal(result.status, "ok");
187
- assert.ok(after._full_content && after._full_content.length > 0, "full body preserved");
188
- assert.ok(after.content.length < "原内容".repeat(60).length, "content shrank to summary");
189
- assert.equal(after.archived, false, "not fully archived at 40 days");
190
- store.close();
191
- });
192
-
193
- test("sleep: demotion fully archives memory past sleepCompressDays", async () => {
194
- const { service, store } = setup();
195
- const now = Date.now();
196
- const m = makeMemory(service, "ancient", "很老的记忆", "project");
197
- service.touchLastAccess(m.id, new Date(now - 100 * 86400000).toISOString());
198
- const ctx = mockCtx(() => "[]");
199
- const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
200
- const after = service.getById(m.id);
201
- assert.equal(result.status, "ok");
202
- assert.equal(after.archived, true, "past compress days → archived");
203
- store.close();
204
- });
205
-
206
- test("sleep: demoteToSummary minRefTimeMs skips a memory touched after snapshot", () => {
207
- const { service, store } = setup();
208
- const now = Date.now();
209
- const m = makeMemory(service, "touched", "内容".repeat(60), "project");
210
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
211
- const snapshotCut = now - 1 * 86400000;
212
- service.touchLastAccess(m.id, new Date(snapshotCut + 60000).toISOString());
213
- const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
214
- assert.equal(updated, undefined, "touched-after-snapshot memory is not demoted");
215
- assert.equal(service.getById(m.id)._full_content ?? null, null, "no demotion happened");
216
- store.close();
217
- });
218
-
219
- test("sleep: demotion demotes a memory still cold after snapshot", () => {
220
- const { service, store } = setup();
221
- const now = Date.now();
222
- const m = makeMemory(service, "stillcold", "内容".repeat(60), "project");
223
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
224
- const snapshotCut = now - 1 * 86400000;
225
- const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
226
- assert.ok(updated && updated._full_content, "cold memory demoted to summary");
227
- store.close();
228
- });
229
-
230
- test("sleep: pattern discovery filters fabricated evidence ids", async () => {
231
- const { service, store } = setup();
232
- const a = makeMemory(service, "模式A", "反复出现的模式A", "project");
233
- const b = makeMemory(service, "模式B", "反复出现的模式B", "project");
234
- const ctx = mockCtx(() =>
235
- JSON.stringify([
236
- { action: "create", type: "pattern", title: "真模式", content: "从 a 和 b 提取", importance: 3, evidence: [a.id, "fake-zzz", b.id] }
237
- ])
238
- );
239
- const result = await runSleep(ctx, service, baseConfig({ sleepPatternMinMemories: 10 }), ctx.logger, null, null);
240
- assert.ok(!JSON.stringify(result.phases.patterns).includes("fake-zzz"), "fabricated evidence filtered before apply");
241
- const pattern = service.all().find((x) => x.type === "pattern");
242
- assert.ok(pattern, "pattern minted");
243
- store.close();
244
- });
245
-
246
- test("sleep: relation completion links orphan entities co-occurring in a memory", async () => {
247
- const { service, store } = setup();
248
- const alpha = service.createEntity({ name: "Alpha", type: "project" });
249
- const beta = service.createEntity({ name: "Beta", type: "project" });
250
- makeMemory(service, "协作", "Alpha 与 Beta 一起干活", "project");
251
- const ctx = mockCtx(() => "[]");
252
- const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
253
- assert.equal(result.phases.relations.status, "ok", "relations phase ran");
254
- const rels = service.getRelations(alpha.id);
255
- assert.ok(rels.length >= 1, "orphan Alpha gained a relation");
256
- assert.ok(rels.some((r) => r.to_entity === beta.id || r.from_entity === beta.id), "relation targets Beta");
257
- store.close();
258
- });
259
-
260
- test("sleep: runSleep writes an audit receipt with run_type='sleep'", async () => {
261
- const { service, store } = setup();
262
- const now = Date.now();
263
- const m = makeMemory(service, "cold", "内容".repeat(60), "project");
264
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
265
- const ctx = mockCtx(() => "[]");
266
- const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
267
- const runs = service.listDreamRuns();
268
- const last = runs[runs.length - 1];
269
- assert.equal(last.run_type, "sleep", "audit row tagged sleep");
270
- assert.equal(result.runId, last.id, "run id matches audit row");
271
- assert.ok(typeof result.receipt === "string" && result.receipt.startsWith("dsh-mneme:run:"), "receipt is the audit string");
272
- store.close();
273
- });
274
-
275
- test("sleep: a failing phase does not block the others (fail-safe)", async () => {
276
- const { service, store } = setup();
277
- service.setEmbedder({
278
- embed: async () => { throw new Error("embed down"); },
279
- embedSingle: async () => { throw new Error("embed down"); },
280
- modelHash: "x", dimension: 3
281
- });
282
- const now = Date.now();
283
- const m = makeMemory(service, "cold", "内容".repeat(60), "project");
284
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
285
- const ctx = mockCtx(() => "[]");
286
- const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
287
- assert.equal(result.phases.conflicts.status, "skipped", "conflicts phase degraded gracefully (no usable vectors)");
288
- assert.equal(result.phases.demotion.status, "ok", "demotion still ran");
289
- assert.equal(result.status, "ok", "overall run still ok despite conflicts degrading");
290
- assert.ok(service.getById(m.id)._full_content, "cold memory still demoted despite conflicts failure");
291
- store.close();
292
- });
293
-
294
- test("sleep: no LLM route skips LLM phases but demotion still runs", async () => {
295
- const { service, store } = setup();
296
- const now = Date.now();
297
- const m = makeMemory(service, "cold", "内容".repeat(60), "project");
298
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
299
- const ctx = mockCtx(() => "[]", null); // currentSelection() → null, no route
300
- const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
301
- assert.equal(result.phases.conflicts.status, "skipped", "no llm route → conflicts skipped");
302
- assert.equal(result.phases.patterns.status, "skipped", "no llm route → patterns skipped");
303
- assert.equal(result.phases.demotion.status, "ok", "demotion is LLM-free and runs");
304
- store.close();
305
- });
306
-
307
- // ------------------------------------------------------------ conflict strictness
308
-
309
- function seedConflictPair(service, vectorIndex, sim) {
310
- const a = makeMemory(service, "主题X", "内容A 关于主题X", "project");
311
- const b = makeMemory(service, "主题X副本", "内容B 关于主题X", "project");
312
- const sin = Math.sqrt(Math.max(0, 1 - sim * sim));
313
- vectorIndex.saveEmbedding(a.id, [1, 0, 0]);
314
- vectorIndex.saveEmbedding(b.id, [sim, sin, 0]);
315
- return { a, b };
316
- }
317
-
318
- test("sleep: conflict strictness gentle ignores sim 0.88 pairs", async () => {
319
- const { service, store, vectorIndex } = setup();
320
- seedConflictPair(service, vectorIndex, 0.88);
321
- const config = baseConfig({ sleepConflictStrictness: "gentle", conflictFreezeEnabled: true });
322
- const ctx = mockCtx(() => "[]");
323
- const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
324
- assert.equal(result.phases.conflicts.status, "skipped", "0.88 below gentle 0.92 → no conflicts");
325
- store.close();
326
- });
327
-
328
- test("sleep: conflict strictness normal resolves sim 0.88 pairs", async () => {
329
- const { service, store, vectorIndex } = setup();
330
- seedConflictPair(service, vectorIndex, 0.88);
331
- const config = baseConfig({ sleepConflictStrictness: "normal", conflictFreezeEnabled: true });
332
- const ctx = mockCtx(() => "[]");
333
- const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
334
- assert.equal(result.phases.conflicts.status, "ok", "0.88 above normal 0.85 → conflicts found");
335
- assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen for review");
336
- store.close();
337
- });
338
-
339
- test("sleep: conflict strictness aggressive adjudicates low-confidence pairs", async () => {
340
- const { service, store, vectorIndex } = setup();
341
- seedConflictPair(service, vectorIndex, 0.80);
342
- const config = baseConfig({ sleepConflictStrictness: "aggressive", conflictFreezeEnabled: true });
343
- const ctx = mockCtx(() => "[]");
344
- const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
345
- assert.equal(result.phases.conflicts.status, "ok", "0.80 above aggressive 0.75 → conflicts found");
346
- assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen");
347
- store.close();
348
- });
349
-
350
- test("sleep: conflict LLM arbitration applies winner/loser", async () => {
351
- const { service, store, vectorIndex } = setup();
352
- const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
353
- const ctx = mockCtx(() =>
354
- JSON.stringify([{ action: "conflict", winner: a.id, loser: b.id, reason: "重复覆盖" }])
355
- );
356
- const result = await runSleep(ctx, service, baseConfig(), ctx.logger, { embedder, vectorIndex }, null);
357
- assert.equal(result.phases.conflicts.status, "ok", "conflict resolved");
358
- assert.equal(service.getById(b.id).archived, true, "loser archived by arbitration");
359
- store.close();
360
- });
361
-
362
- test("sleep: runSleep is abortable via signal between phases", async () => {
363
- const { service, store } = setup();
364
- const now = Date.now();
365
- const m = makeMemory(service, "cold", "内容".repeat(60), "project");
366
- service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
367
- const ctrl = new AbortController();
368
- ctrl.abort(); // pre-aborted
369
- const ctx = mockCtx(() => "[]");
370
- const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, ctrl.signal);
371
- assert.equal(result.phases.conflicts, undefined, "aborted before any phase ran");
372
- store.close();
373
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createSleepScheduler, runSleep } from "../src/dream/sleep.js";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createVectorIndex } from "../src/vector-index.js";
7
+
8
+ // Mock embedder: every query maps to [1,0,0] so vectors are identical unless a
9
+ // test pre-seeds a custom vector via vectorIndex.saveEmbedding.
10
+ const embedder = {
11
+ embedSingle: async () => [1, 0, 0],
12
+ embed: async () => [1, 0, 0],
13
+ schedule: () => {},
14
+ modelHash: "mock#1",
15
+ dimension: 3
16
+ };
17
+
18
+ // Deterministic LLM: onConsolidation(userText) => decisions JSON string.
19
+ function mockCtx(onConsolidation, selection = { provider: "mock", model: "sleep-model" }) {
20
+ return {
21
+ logger: { warn: () => {}, info: () => {} },
22
+ agentDefaultModel: { currentSelection: () => selection },
23
+ llm: {
24
+ async *stream(options) {
25
+ const userText = options.messages.find((m) => m.role === "user")?.content?.[0]?.text ?? "";
26
+ const reply = onConsolidation ? onConsolidation(userText) : "[]";
27
+ yield { type: "text-delta", index: 0, text: reply };
28
+ yield { type: "finish", reason: { kind: "stop" } };
29
+ }
30
+ }
31
+ };
32
+ }
33
+
34
+ function baseConfig(overrides = {}) {
35
+ return {
36
+ sleepModeEnabled: true,
37
+ sleepIdleMinutes: 5,
38
+ sleepMinIntervalHours: 8,
39
+ sleepConflictStrictness: "normal",
40
+ sleepArchiveDays: 30,
41
+ sleepCompressDays: 90,
42
+ sleepPatternMinMemories: 100,
43
+ sleepMaxPatternPerRun: 3,
44
+ ...overrides
45
+ };
46
+ }
47
+
48
+ // v0.7.0 heat 双保护默认保守:默认 heatTypeDecay 下 project 记忆 40 天热值
49
+ // ≈0.55、100 天 ≈0.28,始终高于 sleepHeatThreshold(0.05),demotion 不触发。
50
+ // 降级语义测试把 project 的 λ 调快到 0.02(40 天热值≈0.03),复现"时间窗冷态
51
+ // 即降级"的旧路径;默认保守语义由 sleep-heat.test.js 单独覆盖。
52
+ function demotionConfig(overrides = {}) {
53
+ return baseConfig({ heatTypeDecay: { project: 0.02 }, ...overrides });
54
+ }
55
+
56
+ function setup() {
57
+ const store = createStore(":memory:");
58
+ const service = createService({ store, mirror: null, config: {} });
59
+ const vectorIndex = createVectorIndex({ store });
60
+ service.setEmbedder(embedder);
61
+ service.setVectorIndex(vectorIndex);
62
+ return { store, service, vectorIndex };
63
+ }
64
+
65
+ function makeMemory(service, title, content, type = "project") {
66
+ return service.saveWithDedupe({ type, title, content, importance: 3 }).memory;
67
+ }
68
+
69
+ // ------------------------------------------------------------ scheduler
70
+
71
+ test("sleep: scheduler does not run when disabled", () => {
72
+ const { service, store } = setup();
73
+ const sched = createSleepScheduler({
74
+ service, config: baseConfig({ sleepModeEnabled: false }), logger: { warn: () => {} },
75
+ onRun: async () => ({ ok: true }),
76
+ now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
77
+ });
78
+ assert.equal(sched.shouldRun(1_000_000 + 60 * 60000), false, "disabled never schedules");
79
+ store.close();
80
+ });
81
+
82
+ test("sleep: scheduler fires once idle window elapses", () => {
83
+ const { service, store } = setup();
84
+ const sched = createSleepScheduler({
85
+ service, config: baseConfig(), logger: { warn: () => {} },
86
+ onRun: async () => ({ ok: true }),
87
+ now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
88
+ });
89
+ assert.equal(sched.shouldRun(1_000_000 + 4 * 60000), false, "still within idle window");
90
+ assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "idle window elapsed");
91
+ store.close();
92
+ });
93
+
94
+ test("sleep: noteWrite resets the idle clock (stale-timer guard)", () => {
95
+ const { service, store } = setup();
96
+ let now = 1_000_000;
97
+ const sched = createSleepScheduler({
98
+ service, config: baseConfig(), logger: { warn: () => {} },
99
+ onRun: async () => ({ ok: true }),
100
+ now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
101
+ });
102
+ assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle after 6min");
103
+ now = 1_000_000 + 6 * 60000;
104
+ sched.noteWrite();
105
+ assert.equal(sched.shouldRun(now), false, "write resets idle clock");
106
+ assert.equal(sched.shouldRun(now + 4 * 60000), false, "still idle-pending after reset");
107
+ assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle again after fresh window");
108
+ store.close();
109
+ });
110
+
111
+ test("sleep: first-ever run is not blocked by min interval (lastRunAt=0)", () => {
112
+ const { service, store } = setup();
113
+ const sched = createSleepScheduler({
114
+ service, config: baseConfig(), logger: { warn: () => {} },
115
+ onRun: async () => ({ ok: true }),
116
+ now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
117
+ });
118
+ assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "first run allowed");
119
+ store.close();
120
+ });
121
+
122
+ test("sleep: min interval blocks a re-run within the window, allows after", async () => {
123
+ const { service, store } = setup();
124
+ let now = 1_000_000;
125
+ const sched = createSleepScheduler({
126
+ service, config: baseConfig(), logger: { warn: () => {} },
127
+ onRun: async () => ({ ok: true }),
128
+ now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
129
+ });
130
+ now = 1_000_000 + 6 * 60000; // idle satisfied
131
+ const ok = await sched.maybeSchedule();
132
+ assert.equal(ok, true, "first run executed");
133
+ assert.equal(sched.shouldRun(now + 1 * 3600000), false, "1h later still inside 8h min interval");
134
+ assert.equal(sched.shouldRun(now + 9 * 3600000), true, "9h later past min interval → allowed");
135
+ store.close();
136
+ });
137
+
138
+ test("sleep: maybeSchedule enqueues via service and serializes with other work", async () => {
139
+ const { service, store } = setup();
140
+ const config = baseConfig();
141
+ let now = 1_000_000;
142
+ let order = [];
143
+ const sched = createSleepScheduler({
144
+ service, config, logger: { warn: () => {} },
145
+ onRun: async () => { order.push("sleep"); return { ok: true, applied: 7 }; },
146
+ now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
147
+ });
148
+ now = 1_000_000 + 6 * 60000;
149
+ const p1 = service.enqueue(async () => { order.push("a"); });
150
+ const p2 = sched.maybeSchedule();
151
+ await p1;
152
+ const result = await p2;
153
+ assert.equal(result, true, "run result propagated through enqueue");
154
+ assert.deepEqual(order, ["a", "sleep"], "sleep run serialized behind queued work");
155
+ store.close();
156
+ });
157
+
158
+ test("sleep: dispose clears the timer and prevents further runs", async () => {
159
+ const { service, store } = setup();
160
+ let cleared = false;
161
+ const sched = createSleepScheduler({
162
+ service, config: baseConfig(), logger: { warn: () => {} },
163
+ onRun: async () => ({ ok: true }),
164
+ now: () => 1_000_000,
165
+ setTimeoutFn: () => 1,
166
+ clearTimeoutFn: () => { cleared = true; }
167
+ });
168
+ // #187 起构造即挂表——dispose 必须能清掉这张(以及 noteWrite 重挂过的任何)表。
169
+ assert.equal(cleared, false, "timer armed at construction, not yet cleared");
170
+ await sched.dispose();
171
+ assert.equal(cleared, true, "idle timer cleared on dispose");
172
+ assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), false, "disposed never runs");
173
+ store.close();
174
+ });
175
+
176
+ // ------------------------------------------------------------ runSleep phases
177
+
178
+ test("sleep: demotion shrinks cold memory to summary, keeps _full_content", async () => {
179
+ const { service, store } = setup();
180
+ const now = Date.now();
181
+ const m = makeMemory(service, "cold", "原内容".repeat(60), "project");
182
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
183
+ const ctx = mockCtx(() => "[]");
184
+ const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
185
+ const after = service.getById(m.id);
186
+ assert.equal(result.status, "ok");
187
+ assert.ok(after._full_content && after._full_content.length > 0, "full body preserved");
188
+ assert.ok(after.content.length < "原内容".repeat(60).length, "content shrank to summary");
189
+ assert.equal(after.archived, false, "not fully archived at 40 days");
190
+ store.close();
191
+ });
192
+
193
+ test("sleep: demotion fully archives memory past sleepCompressDays", async () => {
194
+ const { service, store } = setup();
195
+ const now = Date.now();
196
+ const m = makeMemory(service, "ancient", "很老的记忆", "project");
197
+ service.touchLastAccess(m.id, new Date(now - 100 * 86400000).toISOString());
198
+ const ctx = mockCtx(() => "[]");
199
+ const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
200
+ const after = service.getById(m.id);
201
+ assert.equal(result.status, "ok");
202
+ assert.equal(after.archived, true, "past compress days → archived");
203
+ store.close();
204
+ });
205
+
206
+ test("sleep: demoteToSummary minRefTimeMs skips a memory touched after snapshot", () => {
207
+ const { service, store } = setup();
208
+ const now = Date.now();
209
+ const m = makeMemory(service, "touched", "内容".repeat(60), "project");
210
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
211
+ const snapshotCut = now - 1 * 86400000;
212
+ service.touchLastAccess(m.id, new Date(snapshotCut + 60000).toISOString());
213
+ const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
214
+ assert.equal(updated, undefined, "touched-after-snapshot memory is not demoted");
215
+ assert.equal(service.getById(m.id)._full_content ?? null, null, "no demotion happened");
216
+ store.close();
217
+ });
218
+
219
+ test("sleep: demotion demotes a memory still cold after snapshot", () => {
220
+ const { service, store } = setup();
221
+ const now = Date.now();
222
+ const m = makeMemory(service, "stillcold", "内容".repeat(60), "project");
223
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
224
+ const snapshotCut = now - 1 * 86400000;
225
+ const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
226
+ assert.ok(updated && updated._full_content, "cold memory demoted to summary");
227
+ store.close();
228
+ });
229
+
230
+ test("sleep: pattern discovery filters fabricated evidence ids", async () => {
231
+ const { service, store } = setup();
232
+ const a = makeMemory(service, "模式A", "反复出现的模式A", "project");
233
+ const b = makeMemory(service, "模式B", "反复出现的模式B", "project");
234
+ const ctx = mockCtx(() =>
235
+ JSON.stringify([
236
+ { action: "create", type: "pattern", title: "真模式", content: "从 a 和 b 提取", importance: 3, evidence: [a.id, "fake-zzz", b.id] }
237
+ ])
238
+ );
239
+ const result = await runSleep(ctx, service, baseConfig({ sleepPatternMinMemories: 10 }), ctx.logger, null, null);
240
+ assert.ok(!JSON.stringify(result.phases.patterns).includes("fake-zzz"), "fabricated evidence filtered before apply");
241
+ const pattern = service.all().find((x) => x.type === "pattern");
242
+ assert.ok(pattern, "pattern minted");
243
+ store.close();
244
+ });
245
+
246
+ test("sleep: relation completion links orphan entities co-occurring in a memory", async () => {
247
+ const { service, store } = setup();
248
+ const alpha = service.createEntity({ name: "Alpha", type: "project" });
249
+ const beta = service.createEntity({ name: "Beta", type: "project" });
250
+ makeMemory(service, "协作", "Alpha 与 Beta 一起干活", "project");
251
+ const ctx = mockCtx(() => "[]");
252
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
253
+ assert.equal(result.phases.relations.status, "ok", "relations phase ran");
254
+ const rels = service.getRelations(alpha.id);
255
+ assert.ok(rels.length >= 1, "orphan Alpha gained a relation");
256
+ assert.ok(rels.some((r) => r.to_entity === beta.id || r.from_entity === beta.id), "relation targets Beta");
257
+ store.close();
258
+ });
259
+
260
+ test("sleep: runSleep writes an audit receipt with run_type='sleep'", async () => {
261
+ const { service, store } = setup();
262
+ const now = Date.now();
263
+ const m = makeMemory(service, "cold", "内容".repeat(60), "project");
264
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
265
+ const ctx = mockCtx(() => "[]");
266
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
267
+ const runs = service.listDreamRuns();
268
+ const last = runs[runs.length - 1];
269
+ assert.equal(last.run_type, "sleep", "audit row tagged sleep");
270
+ assert.equal(result.runId, last.id, "run id matches audit row");
271
+ assert.ok(typeof result.receipt === "string" && result.receipt.startsWith("dsh-mneme:run:"), "receipt is the audit string");
272
+ store.close();
273
+ });
274
+
275
+ test("sleep: a failing phase does not block the others (fail-safe)", async () => {
276
+ const { service, store } = setup();
277
+ service.setEmbedder({
278
+ embed: async () => { throw new Error("embed down"); },
279
+ embedSingle: async () => { throw new Error("embed down"); },
280
+ modelHash: "x", dimension: 3
281
+ });
282
+ const now = Date.now();
283
+ const m = makeMemory(service, "cold", "内容".repeat(60), "project");
284
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
285
+ const ctx = mockCtx(() => "[]");
286
+ const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
287
+ assert.equal(result.phases.conflicts.status, "skipped", "conflicts phase degraded gracefully (no usable vectors)");
288
+ assert.equal(result.phases.demotion.status, "ok", "demotion still ran");
289
+ assert.equal(result.status, "ok", "overall run still ok despite conflicts degrading");
290
+ assert.ok(service.getById(m.id)._full_content, "cold memory still demoted despite conflicts failure");
291
+ store.close();
292
+ });
293
+
294
+ test("sleep: no LLM route skips LLM phases but demotion still runs", async () => {
295
+ const { service, store } = setup();
296
+ const now = Date.now();
297
+ const m = makeMemory(service, "cold", "内容".repeat(60), "project");
298
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
299
+ const ctx = mockCtx(() => "[]", null); // currentSelection() → null, no route
300
+ const result = await runSleep(ctx, service, demotionConfig(), ctx.logger, null, null);
301
+ assert.equal(result.phases.conflicts.status, "skipped", "no llm route → conflicts skipped");
302
+ assert.equal(result.phases.patterns.status, "skipped", "no llm route → patterns skipped");
303
+ assert.equal(result.phases.demotion.status, "ok", "demotion is LLM-free and runs");
304
+ store.close();
305
+ });
306
+
307
+ // ------------------------------------------------------------ conflict strictness
308
+
309
+ function seedConflictPair(service, vectorIndex, sim) {
310
+ const a = makeMemory(service, "主题X", "内容A 关于主题X", "project");
311
+ const b = makeMemory(service, "主题X副本", "内容B 关于主题X", "project");
312
+ const sin = Math.sqrt(Math.max(0, 1 - sim * sim));
313
+ vectorIndex.saveEmbedding(a.id, [1, 0, 0]);
314
+ vectorIndex.saveEmbedding(b.id, [sim, sin, 0]);
315
+ return { a, b };
316
+ }
317
+
318
+ test("sleep: conflict strictness gentle ignores sim 0.88 pairs", async () => {
319
+ const { service, store, vectorIndex } = setup();
320
+ seedConflictPair(service, vectorIndex, 0.88);
321
+ const config = baseConfig({ sleepConflictStrictness: "gentle", conflictFreezeEnabled: true });
322
+ const ctx = mockCtx(() => "[]");
323
+ const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
324
+ assert.equal(result.phases.conflicts.status, "skipped", "0.88 below gentle 0.92 → no conflicts");
325
+ store.close();
326
+ });
327
+
328
+ test("sleep: conflict strictness normal resolves sim 0.88 pairs", async () => {
329
+ const { service, store, vectorIndex } = setup();
330
+ seedConflictPair(service, vectorIndex, 0.88);
331
+ const config = baseConfig({ sleepConflictStrictness: "normal", conflictFreezeEnabled: true });
332
+ const ctx = mockCtx(() => "[]");
333
+ const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
334
+ assert.equal(result.phases.conflicts.status, "ok", "0.88 above normal 0.85 → conflicts found");
335
+ assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen for review");
336
+ store.close();
337
+ });
338
+
339
+ test("sleep: conflict strictness aggressive adjudicates low-confidence pairs", async () => {
340
+ const { service, store, vectorIndex } = setup();
341
+ seedConflictPair(service, vectorIndex, 0.80);
342
+ const config = baseConfig({ sleepConflictStrictness: "aggressive", conflictFreezeEnabled: true });
343
+ const ctx = mockCtx(() => "[]");
344
+ const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
345
+ assert.equal(result.phases.conflicts.status, "ok", "0.80 above aggressive 0.75 → conflicts found");
346
+ assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen");
347
+ store.close();
348
+ });
349
+
350
+ test("sleep: conflict LLM arbitration applies winner/loser", async () => {
351
+ const { service, store, vectorIndex } = setup();
352
+ const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
353
+ const ctx = mockCtx(() =>
354
+ JSON.stringify([{ action: "conflict", winner: a.id, loser: b.id, reason: "重复覆盖" }])
355
+ );
356
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, { embedder, vectorIndex }, null);
357
+ assert.equal(result.phases.conflicts.status, "ok", "conflict resolved");
358
+ assert.equal(service.getById(b.id).archived, true, "loser archived by arbitration");
359
+ store.close();
360
+ });
361
+
362
+ test("sleep: runSleep is abortable via signal between phases", async () => {
363
+ const { service, store } = setup();
364
+ const now = Date.now();
365
+ const m = makeMemory(service, "cold", "内容".repeat(60), "project");
366
+ service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
367
+ const ctrl = new AbortController();
368
+ ctrl.abort(); // pre-aborted
369
+ const ctx = mockCtx(() => "[]");
370
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, ctrl.signal);
371
+ assert.equal(result.phases.conflicts, undefined, "aborted before any phase ran");
372
+ store.close();
373
+ });