@modusensus/dsh-mneme 0.8.3 → 0.8.5

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