@modusensus/dsh-mneme 0.8.3 → 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 -636
  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 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  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 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  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 -269
  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 -361
  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 -2087
  42. package/lib/settings.js +430 -420
  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 -510
  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 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  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 -269
  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 -361
  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 -2087
  95. package/src/settings.js +430 -420
  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 -1482
  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 -161
  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 -249
  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 -348
  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,700 +1,700 @@
1
- import { STR, langOf } from "../lang.js";
2
- // System-level sleep (v0.4.0): an idle-triggered, LLM-assisted deep pass over
3
- // the memory store. Four independent, fail-safe phases:
4
- // 1. conflict resolution — high-similarity same-type pairs are either parked
5
- // for review (freeze mode) or adjudicated by the LLM (winner kept / loser
6
- // archived), reusing the dream conflict machinery. Strictness-graded.
7
- // v0.8.1 (issue #170): cross-scope pairs are ALWAYS parked for human
8
- // ownership review with a dedicated reason — never auto-adjudicated.
9
- // 2. archival demotion — memories unreferenced past sleepArchiveDays shrink
10
- // to a one-line summary with the full body moved to _full_content; past
11
- // sleepCompressDays they are archived outright.
12
- // 3. pattern discovery — the LLM scans the most recent memories and mints
13
- // type=pattern entries carrying evidence id references.
14
- // 4. relation completion — orphan entities (zero relations) get implied
15
- // relations completed from memory co-occurrence.
16
- // Each phase is wrapped so one failure never aborts the others, and a missing
17
- // LLM route / semantic embedder only skips the phases that need it. A run is
18
- // abortable via an AbortController signal (user activity) — phases check the
19
- // signal between batches so a running cycle yields promptly.
20
- import { randomUUID, createHash } from "node:crypto";
21
- import { validateDecisions, applyDecisions, ACTIONS } from "./decisions.js";
22
- import { findPotentialConflicts, cosineSimilarity } from "./clustering.js";
23
- import { scopeKeyOf } from "../scope.js";
24
- import { buildReceipt, describeStreamFailure, resolveDreamEffort, withEffortFallback, maintainIndexAfterDream } from "../dream.js";
25
- import { computeHeat } from "../heat.js";
26
-
27
- // Issue #126 review(Copilot):默认档(sleepActionSet="conflict")允许的动作 = 全局
28
- // ACTIONS 去掉 #126 新增的两个。从 ACTIONS 派生而非硬编码,将来再扩动作集时自动跟随。
29
- // 只换 prompt 挡不住模型自发输出新动作,必须由校验器按档位收口。
30
- const LEGACY_ACTIONS = [...ACTIONS].filter((a) => a !== "supersede" && a !== "differentiate");
31
-
32
- const SUMMARY_MAX = 120;
33
- // Conflict similarity threshold per strictness level (v0.4.0):
34
- // gentle only high-confidence pairs (0.92) — first-time users
35
- // normal standard dream-level (0.85) — default
36
- // aggressive low-confidence pairs too (0.75) — bloated stores
37
- const CONFLICT_THRESHOLDS = { gentle: 0.92, normal: 0.85, aggressive: 0.75 };
38
-
39
- function parseJsonArray(text) {
40
- if (typeof text !== "string") return undefined;
41
- const start = text.indexOf("[");
42
- const end = text.lastIndexOf("]");
43
- if (start === -1 || end <= start) return undefined;
44
- try {
45
- const parsed = JSON.parse(text.slice(start, end + 1));
46
- return Array.isArray(parsed) ? parsed : undefined;
47
- } catch {
48
- return undefined;
49
- }
50
- }
51
-
52
- /** Same stream consumption contract as dream.js. */
53
- async function streamText(ctx, options, onStreamError) {
54
- if (!ctx?.llm?.stream) return undefined;
55
- let text = "";
56
- for await (const chunk of ctx.llm.stream(options)) {
57
- if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
58
- if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
59
- // Same rc.1 error-as-finish-chunk behavior as dream.js — surface the
60
- // cause instead of discarding it.
61
- if (typeof onStreamError === "function") {
62
- try { onStreamError(chunk.reason); } catch { /* diagnostics only */ }
63
- }
64
- return undefined;
65
- }
66
- }
67
- return text;
68
- }
69
-
70
- /** LLM route (Issue #25): explicit sleepProvider/Model wins, then the dream
71
- * route as a shared explicit fallback, then the agent default model. Sleep
72
- * can pin a cheaper model for its bulk passes without disturbing the dream
73
- * route. Explicit config first — otherwise the config routes are dead code
74
- * whenever agentDefaultModel resolves (see resolveRoute in dream.js). */
75
- function resolveSleepRoute(ctx, config, logger) {
76
- if (config.sleepProvider && config.sleepModel) return { provider: config.sleepProvider, model: config.sleepModel };
77
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
78
- try {
79
- const sel = ctx?.agentDefaultModel?.currentSelection?.();
80
- if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
81
- } catch { /* fall through to warn */ }
82
- logger?.warn?.("dsh-mneme sleep: no llm route available");
83
- return undefined;
84
- }
85
-
86
- function makeSummary(m) {
87
- const text = (m.content ?? "").trim();
88
- if (!text) return (m.title ?? "").trim();
89
- return text.length <= SUMMARY_MAX ? text : `${text.slice(0, SUMMARY_MAX)}…`;
90
- }
91
-
92
- // ---------------------------------------------------------------- phases
93
-
94
- /**
95
- * Phase 1 — conflict resolution. Needs a semantic embedder + vector index.
96
- * In freeze mode (conflictFreezeEnabled) conflicting pairs are parked in
97
- * conflict_pending for human review (no LLM). Otherwise the LLM adjudicates:
98
- * each pair → winner kept / loser archived. Returns a per-run summary.
99
- */
100
- async function phaseConflicts(ctx, service, config, logger, runId, semantic = null, signal = null) {
101
- const language = langOf(config);
102
- const embedder = semantic?.embedder;
103
- const vectorIndex = semantic?.vectorIndex;
104
- if (!embedder || !vectorIndex || typeof embedder.embed !== "function") {
105
- return { status: "skipped", reason: "no semantic embedder" };
106
- }
107
- const strictness = config.sleepConflictStrictness ?? "normal";
108
- const threshold = CONFLICT_THRESHOLDS[strictness] ?? CONFLICT_THRESHOLDS.normal;
109
- const memories = service.all().filter((m) => !m.archived && !m.forgotten && m.type !== "summary");
110
- if (memories.length < 2) return { status: "skipped", reason: "too few memories" };
111
- if (signal?.aborted) return { status: "aborted", reason: "user activity" };
112
-
113
- // Backfill + collect vectors for every eligible memory (best effort).
114
- const vectors = new Array(memories.length);
115
- const missing = [];
116
- for (let i = 0; i < memories.length; i++) {
117
- const cached = vectorIndex.getEmbedding?.(memories[i].id);
118
- if (cached) vectors[i] = cached;
119
- else missing.push(i);
120
- }
121
- if (missing.length) {
122
- try {
123
- const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
124
- const rows = await embedder.embed(texts);
125
- missing.forEach((mi, j) => {
126
- if (rows[j]?.length) {
127
- vectors[mi] = rows[j];
128
- vectorIndex.saveEmbedding?.(memories[mi].id, rows[j]);
129
- }
130
- });
131
- } catch (error) {
132
- logger?.warn?.(`dsh-mneme sleep: conflict vector backfill failed: ${String(error)}`);
133
- }
134
- }
135
- const usable = [];
136
- for (let i = 0; i < memories.length; i++) {
137
- if (vectors[i]?.length) usable.push(i);
138
- }
139
- if (usable.length < 2) return { status: "skipped", reason: "no usable vectors" };
140
- const usableMemories = usable.map((i) => memories[i]);
141
- const usableVectors = usable.map((i) => vectors[i]);
142
-
143
- // Issue #126:动作集档位既要决定 prompt,也要决定**校验器允许的动作集合**(见下方
144
- // allowedActions),并且在候选构造阶段就要知道——full 档需要补跨类型对。因此在这里
145
- // 解析,而不是等到拼 prompt 时。
146
- const actionSet = config.sleepActionSet ?? "conflict";
147
- const pairs = findPotentialConflicts(usableMemories, usableVectors, threshold);
148
- if (actionSet === "full") {
149
- // Issue #126 review(Copilot):findPotentialConflicts 只看同类型,而 full 档的
150
- // prompt 明确宣传 differentiate 用于互补型——互补本来就常跨类型(同一事实的项目侧
151
- // 与偏好侧)。不补这一遍,那条路径永远选不到。merge 的类型守卫不受影响:它拦在
152
- // validateDecisions 里(allowCrossTypeMerge),不在候选生成。
153
- for (let i = 0; i < usableMemories.length; i++) {
154
- for (let j = i + 1; j < usableMemories.length; j++) {
155
- if (usableMemories[i].type === usableMemories[j].type) continue;
156
- const sim = cosineSimilarity(usableVectors[i], usableVectors[j]);
157
- if (sim > threshold) pairs.push({ a: usableMemories[i], b: usableMemories[j], similarity: sim });
158
- }
159
- }
160
- }
161
- if (pairs.length === 0) return { status: "skipped", reason: "no conflicts found" };
162
-
163
- // Dedupe: each memory participates in at most one pair, highest similarity
164
- // first — overlapping pairs would violate validateDecisions' "one claim".
165
- pairs.sort((a, b) => b.similarity - a.similarity);
166
- const used = new Set();
167
- const selected = [];
168
- for (const p of pairs) {
169
- if (used.has(p.a.id) || used.has(p.b.id)) continue;
170
- used.add(p.a.id);
171
- used.add(p.b.id);
172
- selected.push(p);
173
- }
174
-
175
- // v0.8.1(issue #170 第 2 步):跨 scope 相似对分流。同一内容落在两个归属下
176
- // (任一维标注键不等即算,NULL=未标注=全局也参与比较——「全局副本 + 专属副本
177
- // 并存」正是收窄/提升裁决的典型候选)不能自动裁决:归档败者可能销毁该内容在
178
- // 某个归属下的唯一副本,LLM 也无从替用户决定归属。一律停车到冲突待确认队列
179
- // (专属 reason),同 scope 对维持既有路径(freeze 停车 / LLM 裁决)。
180
- const isCrossScopePair = (p) =>
181
- scopeKeyOf(p.a.agent_scope) !== scopeKeyOf(p.b.agent_scope)
182
- || scopeKeyOf(p.a.workspace_scope) !== scopeKeyOf(p.b.workspace_scope);
183
- const crossPairs = selected.filter(isCrossScopePair);
184
- const samePairs = selected.filter((p) => !isCrossScopePair(p));
185
- const parkPair = (p, reason) => {
186
- try {
187
- // 返回 undefined = 该对已被人工裁决且两侧内容未变(复核项 4)——不算停车。
188
- return service.saveConflictPending({ run_id: runId, memory_a: p.a.id, memory_b: p.b.id, reason }) != null;
189
- } catch (error) {
190
- logger?.warn?.(`dsh-mneme sleep: failed to park conflict ${p.a.id}/${p.b.id}: ${String(error)}`);
191
- return false;
192
- }
193
- };
194
- const scopeReason = (p) => STR.scopeCandidateReason[language](p.similarity.toFixed(2));
195
- const simReason = (p) => STR.similarityReason[language](p.similarity.toFixed(2));
196
-
197
- // Freeze mode: park pairs for manual review, no LLM required. Cross-scope
198
- // pairs carry the dedicated scope-candidate reason so the queue reads them
199
- // as ownership decisions rather than plain duplicates.
200
- if (config.conflictFreezeEnabled === true) {
201
- let frozen = 0;
202
- for (const p of selected) {
203
- if (parkPair(p, isCrossScopePair(p) ? scopeReason(p) : simReason(p))) frozen++;
204
- }
205
- return { status: frozen > 0 ? "ok" : "noop", frozen, scopeCandidates: crossPairs.length, pairs: selected.length };
206
- }
207
-
208
- // 非 freeze:跨 scope 对先停车(绝不进 LLM 裁决),同 scope 对照常走 LLM。
209
- let scopeParked = 0;
210
- for (const p of crossPairs) {
211
- if (parkPair(p, scopeReason(p))) scopeParked++;
212
- }
213
- if (samePairs.length === 0) {
214
- return { status: scopeParked > 0 ? "ok" : "noop", frozen: 0, scopeCandidates: scopeParked, pairs: selected.length };
215
- }
216
-
217
- // LLM adjudication(仅同 scope 对)。
218
- const route = resolveSleepRoute(ctx, config, logger);
219
- if (!route) return { status: "skipped", reason: "no llm route", scopeCandidates: scopeParked, pairs: selected.length };
220
- const snapshot = new Map();
221
- for (const p of samePairs) {
222
- snapshot.set(p.a.id, p.a);
223
- snapshot.set(p.b.id, p.b);
224
- }
225
- const listText = samePairs.map((p) =>
226
- STR.candidateConflicts[language](p)
227
- ).join("\n\n");
228
- const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
229
- let conflictStreamFailure = "";
230
- // actionSet 已在候选构造前解析(跨类型候选需要它),这里只按档位选 prompt:
231
- // 默认档保持只有 conflict/keep 的窄 prompt,"full" 才开放六分支。
232
- const conflictPrompt = actionSet === "full" ? STR.prompts.conflictFull[language] : STR.prompts.conflict[language];
233
- const runConflict = (withEffort) => {
234
- conflictStreamFailure = "";
235
- return streamText(ctx, {
236
- provider: route.provider,
237
- model: route.model,
238
- purpose: "sleep-conflict",
239
- maxTokens: 2048,
240
- ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
241
- messages: [
242
- { role: "system", content: [{ type: "text", text: conflictPrompt }], source: { kind: "plugin", plugin: "dsh-mneme" } },
243
- { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin", plugin: "dsh-mneme" } }
244
- ]
245
- }, (reason) => { conflictStreamFailure = describeStreamFailure(reason); });
246
- };
247
- const text = await withEffortFallback(ctx, sleepEffort, () => runConflict(true), () => runConflict(false), () => conflictStreamFailure);
248
- if (text === undefined) {
249
- if (conflictStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: conflict stream aborted or errored (${conflictStreamFailure})`);
250
- return { status: "failed", error: "llm failed" };
251
- }
252
- const decisions = parseJsonArray(text);
253
- if (!decisions) return { status: "failed", error: "invalid decisions json" };
254
- // validateDecisions 要求每个 snapshot id 恰好被 claim 一次。v0.4.4 起它本身
255
- // 就会为未覆盖的 id 自动补 keep(dreamImplicitKeep 默认开启),这里保留显式
256
- // 预填作为防御性双保险——漏判读作"未裁决冲突"而非"冲突阶段整体失败"。
257
- const covered = new Set();
258
- for (const d of decisions) {
259
- // Issue #126 review(Copilot):supersede 同样用 winner/loser 定位(没有 ids),
260
- // 此前只认 conflict → 它的两个目标都没进 covered → 被补成 implicit keep → 与
261
- // supersede 的 claim 冲突:严格模式整单拒绝,宽容模式把合成的 keep 记成 skipped。
262
- if (d?.action === "conflict" || d?.action === "supersede") {
263
- if (typeof d?.winner === "string") covered.add(d.winner);
264
- if (typeof d?.loser === "string") covered.add(d.loser);
265
- } else if (Array.isArray(d?.ids)) {
266
- for (const id of d.ids) covered.add(id);
267
- }
268
- }
269
- for (const id of snapshot.keys()) {
270
- if (!covered.has(id)) decisions.push({ action: "keep", ids: [id] });
271
- }
272
- // Issue #126:sleep 是多对批量裁决,严格模式"一票否决"太脆(一对非法就丢掉整轮
273
- // 成果)→ 与 dream 对齐透传 skipInvalid:非法的那一对只跳过自己,合法子集照常
274
- // 应用,run 记 degraded。update 上限与保护期同样取 dream 的同一组配置,保证两个
275
- // 模块对"什么算合法"的判据一致。
276
- const { ok, errors, skipped } = validateDecisions(decisions, snapshot, {
277
- maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
278
- minAgeHours: config.reflectionUpdateMinAgeHours,
279
- skipInvalid: config.dreamSkipInvalid !== false,
280
- allowCrossTypeMerge: config.allowCrossTypeMerge === true,
281
- // Issue #126 review(Copilot):默认档必须真的只放行旧动作集——只换 prompt 挡不住
282
- // 模型自发输出 supersede / differentiate,那样"opt-in 零行为变化"就不成立。
283
- allowedActions: actionSet === "full" ? null : LEGACY_ACTIONS
284
- });
285
- if (!ok) return { status: "failed", error: `invalid decisions: ${errors.join("; ")}`, skipped };
286
- const { applied, failures, conflicts } = applyDecisions(decisions, service, logger, snapshot, config);
287
- // Issue #126 review(Copilot):事务内 service.update 会跳过 scheduleEmbed(txDepth>0),
288
- // 而 sleep 路径此前没有 dream 那样的 post-apply 索引维护——differentiate 的差异注记与
289
- // supersede 的归档都反映不到缓存向量,"注记进 embedding 防再判重复"就是空承诺。
290
- if (applied > 0 && semantic?.embedder && semantic?.vectorIndex) {
291
- try {
292
- await maintainIndexAfterDream(decisions, service, semantic);
293
- } catch (error) {
294
- logger?.warn?.(`dsh-mneme sleep: index maintenance failed: ${String(error)}`);
295
- }
296
- }
297
- // Issue #126 review(Copilot):有决策被跳过时不能报 ok——与 dream 的 degraded 契约
298
- // 对齐("合法子集已应用"是 degraded 而非 ok),否则消费方分不清整轮与残轮。
299
- const degraded = skipped.length > 0;
300
- return {
301
- status: applied > 0 ? (degraded ? "degraded" : "ok") : failures.length ? "failed" : "noop",
302
- pairs: selected.length,
303
- applied,
304
- failures,
305
- conflicts,
306
- // Issue #126:#104 同向——被跳过的逐对明细要进审计行,否则事后无法判断
307
- // 是哪一对、因何被跳过(此前只进 logger.warn,splice 后就地消失)。
308
- skipped
309
- };
310
- }
311
-
312
- /**
313
- * Phase 2 — archival demotion. No LLM: tiering is time-based, summaries are
314
- * truncations, and the full body is preserved in _full_content so nothing is
315
- * lost. Deterministic and cheap, so it runs even with no LLM route.
316
- */
317
- function phaseDemotion(service, config, logger, runId, signal = null) {
318
- const archiveDays = config.sleepArchiveDays ?? 30;
319
- const compressDays = config.sleepCompressDays ?? 90;
320
- const archiveCut = Date.now() - archiveDays * 86400000;
321
- const compressCut = Date.now() - compressDays * 86400000;
322
- const demoted = [];
323
- const archived = [];
324
- for (const m of service.all()) {
325
- if (signal?.aborted) break;
326
- if (m.archived || m.forgotten) continue;
327
- const ref = m.last_accessed_at ?? m.created_at;
328
- if (!ref) continue;
329
- const t = new Date(ref).getTime();
330
- if (Number.isNaN(t)) continue;
331
- // v0.7.0 热联合判定(仅 heatEnabled 时启用;默认关则退回纯时间分层,
332
- // 与 v0.7.12 行为一致):时间窗之外再加两道保护闸——热度低于
333
- // sleepHeatThreshold 且 importance<5 才允许降级。λ=0 的免疫类型 heat 恒
334
- // 1.0 天然豁免(preference/pattern/summary 永不因 sleep 降级);importance
335
- // ≥5 的紧要记忆无论多冷都保留。`冷但重要` 与 `热但低值` 均不满足条件。
336
- const heatOn = config.heatEnabled !== false;
337
- if (heatOn) {
338
- const heat = computeHeat(m, Date.now(), config);
339
- const heatProtected = heat >= (config.sleepHeatThreshold ?? 0.05);
340
- const important = (m.importance ?? 0) >= 5;
341
- if (heatProtected || important) continue;
342
- }
343
- if (t < compressCut) {
344
- service.setArchived(m.id, true);
345
- archived.push(m.id);
346
- } else if (t < archiveCut) {
347
- // minRefTimeMs re-checks freshness inside demoteToSummary's transaction:
348
- // a recall touch landing after this snapshot must not demote the memory.
349
- service.demoteToSummary(m.id, makeSummary(m), { minRefTimeMs: archiveCut });
350
- demoted.push(m.id);
351
- }
352
- }
353
- return {
354
- status: demoted.length || archived.length ? "ok" : "noop",
355
- demoted,
356
- archived
357
- };
358
- }
359
-
360
- /**
361
- * Phase 3 — pattern discovery. The LLM scans the most recent memories and
362
- * mints type=pattern entries (create actions) with evidence references.
363
- * The empty snapshot is intentional: create claims no existing id, so the
364
- * "every id claimed" invariant is trivially satisfied for pure-create lists.
365
- */
366
- async function phasePatterns(ctx, service, config, logger, runId, signal = null) {
367
- const language = langOf(config);
368
- const route = resolveSleepRoute(ctx, config, logger);
369
- if (!route) return { status: "skipped", reason: "no llm route" };
370
- const limit = config.sleepPatternMinMemories ?? 100;
371
- const memories = service
372
- .list({ limit: 200, includeForgotten: false })
373
- .filter((m) => !m.archived && m.type !== "summary" && m.type !== "pattern")
374
- .sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))
375
- .slice(0, limit);
376
- if (memories.length === 0) return { status: "skipped", reason: "no memories to scan" };
377
- if (signal?.aborted) return { status: "aborted", reason: "user activity" };
378
- const listText = memories
379
- .map((m) => `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`)
380
- .join("\n");
381
- const maxPatterns = config.sleepMaxPatternPerRun ?? 3;
382
- const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
383
- let patternStreamFailure = "";
384
- const runPattern = (withEffort) => {
385
- patternStreamFailure = "";
386
- return streamText(ctx, {
387
- provider: route.provider,
388
- model: route.model,
389
- purpose: "sleep-pattern",
390
- maxTokens: 2048,
391
- ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
392
- messages: [
393
- { role: "system", content: [{ type: "text", text: STR.prompts.pattern[language].replace("N", String(maxPatterns)) }], source: { kind: "plugin", plugin: "dsh-mneme" } },
394
- { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin", plugin: "dsh-mneme" } }
395
- ]
396
- }, (reason) => { patternStreamFailure = describeStreamFailure(reason); });
397
- };
398
- const text = await withEffortFallback(ctx, sleepEffort, () => runPattern(true), () => runPattern(false), () => patternStreamFailure);
399
- if (text === undefined) {
400
- if (patternStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: pattern stream aborted or errored (${patternStreamFailure})`);
401
- return { status: "failed", error: "llm failed" };
402
- }
403
- const decisions = parseJsonArray(text);
404
- if (!decisions || decisions.length === 0) return { status: "skipped", reason: "no patterns found" };
405
- // Evidence ids are provenance refs; an LLM-fabricated id would mint a dead
406
- // ev:tag pointing nowhere. Intersect evidence with the scanned set so only
407
- // real memory references survive.
408
- const scannedIds = new Set(memories.map((m) => m.id));
409
- for (const d of decisions) {
410
- if (d?.action === "create" && Array.isArray(d.evidence)) {
411
- d.evidence = d.evidence.filter((id) => typeof id === "string" && scannedIds.has(id));
412
- }
413
- }
414
- const snapshot = new Map();
415
- const { ok, errors } = validateDecisions(decisions, snapshot, {
416
- maxCreatePerRun: maxPatterns
417
- });
418
- if (!ok) return { status: "failed", error: `invalid decisions: ${errors.join("; ")}` };
419
- const { applied, failures, conflicts } = applyDecisions(decisions, service, logger, snapshot, config);
420
- return {
421
- status: applied > 0 ? "ok" : "noop",
422
- scanned: memories.length,
423
- applied,
424
- failures,
425
- conflicts
426
- };
427
- }
428
-
429
- /**
430
- * Phase 4 — entity relation completion. Detects orphan entities (zero
431
- * relations) and completes implied relations from memory co-occurrence:
432
- * entities named in the same memory → related_to; container kinds
433
- * (project/module) → part_of; tech-ish pairs → depends_on. Deterministic,
434
- * no LLM — cheap, so it runs even without a route. saveRelation is
435
- * bookkeeping (no write hook), so it never re-triggers the scheduler.
436
- */
437
- function inferRelationType(a, b) {
438
- if ((a.type === "project" || a.type === "module") && a.type !== b.type) return "part_of";
439
- if ((b.type === "project" || b.type === "module") && b.type !== a.type) return "part_of";
440
- if (/npm|plugin|api|sdk|lib|framework|package|deps?|build/i.test(`${a.name} ${b.name}`)) return "depends_on";
441
- return "related_to";
442
- }
443
-
444
- function phaseRelations(service, config, logger, runId, signal = null) {
445
- const entities = service.listEntities({ limit: 1000 }) ?? [];
446
- if (entities.length < 2) return { status: "skipped", reason: "too few entities" };
447
- const orphans = entities.filter((e) => (service.getRelations(e.id) ?? []).length === 0);
448
- if (orphans.length === 0) return { status: "skipped", reason: "no orphan entities" };
449
- const memories = service.all().filter((m) => !m.archived && !m.forgotten);
450
- const seen = new Set();
451
- const related = [];
452
- const MAX_RELATIONS_PER_ORPHAN = 3;
453
- for (const o of orphans) {
454
- if (signal?.aborted) break;
455
- let made = 0;
456
- for (const m of memories) {
457
- if (signal?.aborted || made >= MAX_RELATIONS_PER_ORPHAN) break;
458
- const text = `${m.title ?? ""} ${m.content ?? ""}`;
459
- if (!text.includes(o.name)) continue;
460
- for (const other of entities) {
461
- if (other.id === o.id || other.name === o.name) continue;
462
- const key = [o.id, other.id].sort().join("|");
463
- if (seen.has(key)) continue;
464
- if (!text.includes(other.name)) continue;
465
- const relationType = inferRelationType(o, other);
466
- try {
467
- service.saveRelation({ from_entity: o.id, to_entity: other.id, relation_type: relationType, memory_id: m.id, metadata: { source: "sleep_relation_completion" } });
468
- seen.add(key);
469
- related.push({ from: o.id, to: other.id, type: relationType });
470
- made++;
471
- } catch (error) {
472
- logger?.warn?.(`dsh-mneme sleep: relation ${o.id}/${other.id} failed: ${String(error)}`);
473
- }
474
- }
475
- }
476
- }
477
- return {
478
- status: related.length > 0 ? "ok" : "noop",
479
- orphanCount: orphans.length,
480
- related
481
- };
482
- }
483
-
484
- // ---------------------------------------------------------------- run
485
-
486
- function deriveStatus(phases) {
487
- const list = Object.values(phases);
488
- if (list.length === 0) return "noop";
489
- const anyError = list.some((p) => p.status === "failed" || p.status === "error");
490
- // Issue #126 review(Copilot):phase 自身可以是 degraded(合法子集已应用但有条目被
491
- // 跳过),它同样算"有产出"——否则整轮会被误判成 noop,把真实变更报成空轮。
492
- const anyWork = list.some((p) => p.status === "ok" || p.status === "degraded");
493
- const anyDegraded = list.some((p) => p.status === "degraded");
494
- if (anyDegraded) return "degraded";
495
- if (anyWork && anyError) return "degraded";
496
- if (anyError) return "failed";
497
- if (anyWork) return "ok";
498
- return "noop";
499
- }
500
-
501
- /**
502
- * Run one full sleep cycle. Best-effort across all phases; writes a
503
- * run_type='sleep' audit row (same dream_runs table) so sleep activity is
504
- * observable alongside consolidation runs.
505
- */
506
- export async function runSleep(ctx, service, config, logger, semantic = null, signal = null) {
507
- const runId = randomUUID();
508
- const phases = {};
509
- const attempt = async (name, fn) => {
510
- if (signal?.aborted) return; // user resumed activity — stop before next phase
511
- try {
512
- phases[name] = await fn();
513
- } catch (error) {
514
- phases[name] = { status: "failed", error: error?.message ?? String(error) };
515
- logger?.warn?.(`dsh-mneme sleep: ${name} phase failed: ${error?.message ?? error}`);
516
- }
517
- };
518
- await attempt("conflicts", () => phaseConflicts(ctx, service, config, logger, runId, semantic, signal));
519
- await attempt("demotion", () => phaseDemotion(service, config, logger, runId, signal));
520
- await attempt("patterns", () => phasePatterns(ctx, service, config, logger, runId, signal));
521
- await attempt("relations", () => phaseRelations(service, config, logger, runId, signal));
522
-
523
- const status = deriveStatus(phases);
524
- const route = resolveSleepRoute(ctx, config, logger);
525
- const totalApplied = Object.values(phases).reduce((n, p) => n + (Number.isInteger(p?.applied) ? p.applied : 0), 0);
526
- // Issue #126(与 #104 同向):把各 phase 的跳过明细汇总成一行审计数据,带 phase
527
- // 名(同一次 run 里 conflicts 与 patterns 都可能产出 skipped)。全空时写 NULL,
528
- // 不落空数组——审计行只记真实发生过的跳过。
529
- const skippedDetail = Object.entries(phases).flatMap(([phase, p]) =>
530
- Array.isArray(p?.skipped) ? p.skipped.map((s) => ({ phase, ...s })) : []
531
- );
532
- const snapshotHash = createHash("sha256").update(JSON.stringify(phases)).digest("hex");
533
- const receipt = buildReceipt({
534
- runId,
535
- status,
536
- snapshotHash,
537
- inputCount: 0,
538
- applied: totalApplied,
539
- summaryStored: false
540
- });
541
- try {
542
- service.saveDreamRun({
543
- id: runId,
544
- status,
545
- provider: route?.provider,
546
- model: route?.model,
547
- snapshot_hash: snapshotHash,
548
- input_count: 0,
549
- input: null,
550
- decisions: phases,
551
- outcome: phases,
552
- applied: totalApplied,
553
- summary_stored: false,
554
- receipt,
555
- policy_epoch: config.policyEpoch ?? 0,
556
- run_type: "sleep",
557
- skipped: skippedDetail.length ? skippedDetail : undefined
558
- });
559
- } catch (error) {
560
- logger?.warn?.(`dsh-mneme sleep: failed to record audit run: ${String(error)}`);
561
- }
562
- return { ok: status === "ok" || status === "degraded", status, runId, phases, receipt };
563
- }
564
-
565
- // ---------------------------------------------------------------- scheduler
566
-
567
- /**
568
- * Idle-triggered scheduler. DSH plugins have no resident cron, so a sleep run
569
- * fires when: sleep is enabled, the store has been quiet for sleepIdleMinutes,
570
- * and the previous run is older than sleepMinIntervalHours. noteWrite() is
571
- * called on every store write and (re)arms an idle timer that re-checks at the
572
- * exact moment the idle window elapses — no polling, no cron.
573
- *
574
- * A `now` clock can be injected for tests; it defaults to Date.now.
575
- */
576
- export function createSleepScheduler({
577
- service,
578
- config,
579
- logger,
580
- onRun = null,
581
- now = () => Date.now(),
582
- setTimeoutFn = setTimeout,
583
- clearTimeoutFn = clearTimeout
584
- }) {
585
- let lastWriteAt = now();
586
- let lastRunAt = 0;
587
- let running = false;
588
- let disposed = false;
589
- let idleTimer = null;
590
- let sleepAbort = null;
591
-
592
- function armIdleTimer() {
593
- if (disposed || idleTimer) return;
594
- if (config.sleepModeEnabled !== true) return;
595
- const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
596
- const delay = Math.max(0, idleMs - (now() - lastWriteAt)) + 1000;
597
- idleTimer = setTimeoutFn(async () => {
598
- idleTimer = null;
599
- // Issue #187:false = 撞上 CD(或 run 失败)——此前这里直接丢弃,"CD 到期"
600
- // 成了没有监听者的时刻,要等下一次写入才救回来。改为按剩余窗口重排。
601
- const ran = await maybeSchedule();
602
- if (!ran) armNextWindow();
603
- }, delay);
604
- idleTimer.unref?.();
605
- }
606
-
607
- // Issue #187:撞 CD / run 失败后的补挂表——按「剩余 CD / 剩余静默」里更晚的
608
- // 到点时刻重排一次,回调里重复同样的判断所以不会空转。跑成了一轮就不重排:
609
- // 安静的库没有要处理的新东西,触发权交还给下一次写入的 noteWrite。
610
- function armNextWindow() {
611
- if (disposed || idleTimer) return;
612
- if (config.sleepModeEnabled !== true) return;
613
- // lastRunAt === 0 表示从未跑过(此路径不该出现,防御性返回)。
614
- if (lastRunAt <= 0) return;
615
- const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
616
- const cdMs = (config.sleepMinIntervalHours ?? 8) * 3600000;
617
- const delay = Math.max(
618
- lastRunAt + cdMs - now(),
619
- lastWriteAt + idleMs - now(),
620
- 0
621
- ) + 1000;
622
- idleTimer = setTimeoutFn(async () => {
623
- idleTimer = null;
624
- const ran = await maybeSchedule();
625
- if (!ran) armNextWindow();
626
- }, delay);
627
- idleTimer.unref?.();
628
- }
629
-
630
- function shouldRun(at = now()) {
631
- if (disposed || running) return false;
632
- if (config.sleepModeEnabled !== true) return false;
633
- if (at - lastWriteAt < (config.sleepIdleMinutes ?? 5) * 60000) return false;
634
- // lastRunAt === 0 means never ran — the min-interval check must not block
635
- // the very first cycle (a real run stamps a nonzero timestamp).
636
- if (lastRunAt > 0 && at - lastRunAt < (config.sleepMinIntervalHours ?? 8) * 3600000) return false;
637
- return true;
638
- }
639
-
640
- /** Called on writes: resets the idle clock and re-arms the fire timer. The
641
- * pending timer is cleared first — a stale timer armed against the old idle
642
- * window would otherwise fire early, fail shouldRun, and leave nothing armed
643
- * for the next window (a missed trigger until the next write).
644
- *
645
- * While a sleep run is executing (running=true) the in-flight AbortController
646
- * is NOT aborted: the run's own writes (demoteToSummary / setArchived ride
647
- * the normal write-hook path) would otherwise self-abort the cycle. External
648
- * activity during the run still resets the idle clock here, so no new cycle
649
- * fires until the store is quiet again. */
650
- function noteWrite() {
651
- lastWriteAt = now();
652
- if (!running && sleepAbort) {
653
- sleepAbort.abort(); // user resumed activity — interrupt an idle run
654
- }
655
- if (idleTimer) {
656
- clearTimeoutFn(idleTimer);
657
- idleTimer = null;
658
- }
659
- armIdleTimer();
660
- }
661
-
662
- async function maybeSchedule() {
663
- if (!shouldRun()) return false;
664
- running = true;
665
- const abort = new AbortController();
666
- sleepAbort = abort;
667
- try {
668
- lastRunAt = now();
669
- const result = await service.enqueue(() =>
670
- onRun ? onRun(abort.signal) : Promise.resolve({ ok: true, skipped: true })
671
- );
672
- return !!(result && result.ok);
673
- } catch (error) {
674
- logger?.warn?.(`dsh-mneme sleep: run failed: ${error?.message ?? error}`);
675
- return false;
676
- } finally {
677
- sleepAbort = null;
678
- running = false;
679
- }
680
- }
681
-
682
- async function dispose() {
683
- disposed = true;
684
- if (idleTimer) {
685
- clearTimeoutFn(idleTimer);
686
- idleTimer = null;
687
- }
688
- if (sleepAbort) {
689
- sleepAbort.abort();
690
- sleepAbort = null;
691
- }
692
- }
693
-
694
- // Issue #187(同族缺陷):构造即挂表——重启后只要没发生过写入,此前永远没有
695
- // 闹钟,安静多久都不会触发。lastWriteAt 已在构造时设为当前时刻,shouldRun 的
696
- // 静默条件自然生效:重启后静默满 idleMinutes 才可能起跑。
697
- armIdleTimer();
698
-
699
- return { noteWrite, maybeSchedule, shouldRun, dispose };
700
- }
1
+ import { STR, langOf } from "../lang.js";
2
+ // System-level sleep (v0.4.0): an idle-triggered, LLM-assisted deep pass over
3
+ // the memory store. Four independent, fail-safe phases:
4
+ // 1. conflict resolution — high-similarity same-type pairs are either parked
5
+ // for review (freeze mode) or adjudicated by the LLM (winner kept / loser
6
+ // archived), reusing the dream conflict machinery. Strictness-graded.
7
+ // v0.8.1 (issue #170): cross-scope pairs are ALWAYS parked for human
8
+ // ownership review with a dedicated reason — never auto-adjudicated.
9
+ // 2. archival demotion — memories unreferenced past sleepArchiveDays shrink
10
+ // to a one-line summary with the full body moved to _full_content; past
11
+ // sleepCompressDays they are archived outright.
12
+ // 3. pattern discovery — the LLM scans the most recent memories and mints
13
+ // type=pattern entries carrying evidence id references.
14
+ // 4. relation completion — orphan entities (zero relations) get implied
15
+ // relations completed from memory co-occurrence.
16
+ // Each phase is wrapped so one failure never aborts the others, and a missing
17
+ // LLM route / semantic embedder only skips the phases that need it. A run is
18
+ // abortable via an AbortController signal (user activity) — phases check the
19
+ // signal between batches so a running cycle yields promptly.
20
+ import { randomUUID, createHash } from "node:crypto";
21
+ import { validateDecisions, applyDecisions, ACTIONS } from "./decisions.js";
22
+ import { findPotentialConflicts, cosineSimilarity } from "./clustering.js";
23
+ import { scopeKeyOf } from "../scope.js";
24
+ import { buildReceipt, describeStreamFailure, resolveDreamEffort, withEffortFallback, maintainIndexAfterDream } from "../dream.js";
25
+ import { computeHeat } from "../heat.js";
26
+
27
+ // Issue #126 review(Copilot):默认档(sleepActionSet="conflict")允许的动作 = 全局
28
+ // ACTIONS 去掉 #126 新增的两个。从 ACTIONS 派生而非硬编码,将来再扩动作集时自动跟随。
29
+ // 只换 prompt 挡不住模型自发输出新动作,必须由校验器按档位收口。
30
+ const LEGACY_ACTIONS = [...ACTIONS].filter((a) => a !== "supersede" && a !== "differentiate");
31
+
32
+ const SUMMARY_MAX = 120;
33
+ // Conflict similarity threshold per strictness level (v0.4.0):
34
+ // gentle only high-confidence pairs (0.92) — first-time users
35
+ // normal standard dream-level (0.85) — default
36
+ // aggressive low-confidence pairs too (0.75) — bloated stores
37
+ const CONFLICT_THRESHOLDS = { gentle: 0.92, normal: 0.85, aggressive: 0.75 };
38
+
39
+ function parseJsonArray(text) {
40
+ if (typeof text !== "string") return undefined;
41
+ const start = text.indexOf("[");
42
+ const end = text.lastIndexOf("]");
43
+ if (start === -1 || end <= start) return undefined;
44
+ try {
45
+ const parsed = JSON.parse(text.slice(start, end + 1));
46
+ return Array.isArray(parsed) ? parsed : undefined;
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ /** Same stream consumption contract as dream.js. */
53
+ async function streamText(ctx, options, onStreamError) {
54
+ if (!ctx?.llm?.stream) return undefined;
55
+ let text = "";
56
+ for await (const chunk of ctx.llm.stream(options)) {
57
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
58
+ if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
59
+ // Same rc.1 error-as-finish-chunk behavior as dream.js — surface the
60
+ // cause instead of discarding it.
61
+ if (typeof onStreamError === "function") {
62
+ try { onStreamError(chunk.reason); } catch { /* diagnostics only */ }
63
+ }
64
+ return undefined;
65
+ }
66
+ }
67
+ return text;
68
+ }
69
+
70
+ /** LLM route (Issue #25): explicit sleepProvider/Model wins, then the dream
71
+ * route as a shared explicit fallback, then the agent default model. Sleep
72
+ * can pin a cheaper model for its bulk passes without disturbing the dream
73
+ * route. Explicit config first — otherwise the config routes are dead code
74
+ * whenever agentDefaultModel resolves (see resolveRoute in dream.js). */
75
+ function resolveSleepRoute(ctx, config, logger) {
76
+ if (config.sleepProvider && config.sleepModel) return { provider: config.sleepProvider, model: config.sleepModel };
77
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
78
+ try {
79
+ const sel = ctx?.agentDefaultModel?.currentSelection?.();
80
+ if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
81
+ } catch { /* fall through to warn */ }
82
+ logger?.warn?.("dsh-mneme sleep: no llm route available");
83
+ return undefined;
84
+ }
85
+
86
+ function makeSummary(m) {
87
+ const text = (m.content ?? "").trim();
88
+ if (!text) return (m.title ?? "").trim();
89
+ return text.length <= SUMMARY_MAX ? text : `${text.slice(0, SUMMARY_MAX)}…`;
90
+ }
91
+
92
+ // ---------------------------------------------------------------- phases
93
+
94
+ /**
95
+ * Phase 1 — conflict resolution. Needs a semantic embedder + vector index.
96
+ * In freeze mode (conflictFreezeEnabled) conflicting pairs are parked in
97
+ * conflict_pending for human review (no LLM). Otherwise the LLM adjudicates:
98
+ * each pair → winner kept / loser archived. Returns a per-run summary.
99
+ */
100
+ async function phaseConflicts(ctx, service, config, logger, runId, semantic = null, signal = null) {
101
+ const language = langOf(config);
102
+ const embedder = semantic?.embedder;
103
+ const vectorIndex = semantic?.vectorIndex;
104
+ if (!embedder || !vectorIndex || typeof embedder.embed !== "function") {
105
+ return { status: "skipped", reason: "no semantic embedder" };
106
+ }
107
+ const strictness = config.sleepConflictStrictness ?? "normal";
108
+ const threshold = CONFLICT_THRESHOLDS[strictness] ?? CONFLICT_THRESHOLDS.normal;
109
+ const memories = service.all().filter((m) => !m.archived && !m.forgotten && m.type !== "summary");
110
+ if (memories.length < 2) return { status: "skipped", reason: "too few memories" };
111
+ if (signal?.aborted) return { status: "aborted", reason: "user activity" };
112
+
113
+ // Backfill + collect vectors for every eligible memory (best effort).
114
+ const vectors = new Array(memories.length);
115
+ const missing = [];
116
+ for (let i = 0; i < memories.length; i++) {
117
+ const cached = vectorIndex.getEmbedding?.(memories[i].id);
118
+ if (cached) vectors[i] = cached;
119
+ else missing.push(i);
120
+ }
121
+ if (missing.length) {
122
+ try {
123
+ const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
124
+ const rows = await embedder.embed(texts);
125
+ missing.forEach((mi, j) => {
126
+ if (rows[j]?.length) {
127
+ vectors[mi] = rows[j];
128
+ vectorIndex.saveEmbedding?.(memories[mi].id, rows[j]);
129
+ }
130
+ });
131
+ } catch (error) {
132
+ logger?.warn?.(`dsh-mneme sleep: conflict vector backfill failed: ${String(error)}`);
133
+ }
134
+ }
135
+ const usable = [];
136
+ for (let i = 0; i < memories.length; i++) {
137
+ if (vectors[i]?.length) usable.push(i);
138
+ }
139
+ if (usable.length < 2) return { status: "skipped", reason: "no usable vectors" };
140
+ const usableMemories = usable.map((i) => memories[i]);
141
+ const usableVectors = usable.map((i) => vectors[i]);
142
+
143
+ // Issue #126:动作集档位既要决定 prompt,也要决定**校验器允许的动作集合**(见下方
144
+ // allowedActions),并且在候选构造阶段就要知道——full 档需要补跨类型对。因此在这里
145
+ // 解析,而不是等到拼 prompt 时。
146
+ const actionSet = config.sleepActionSet ?? "conflict";
147
+ const pairs = findPotentialConflicts(usableMemories, usableVectors, threshold);
148
+ if (actionSet === "full") {
149
+ // Issue #126 review(Copilot):findPotentialConflicts 只看同类型,而 full 档的
150
+ // prompt 明确宣传 differentiate 用于互补型——互补本来就常跨类型(同一事实的项目侧
151
+ // 与偏好侧)。不补这一遍,那条路径永远选不到。merge 的类型守卫不受影响:它拦在
152
+ // validateDecisions 里(allowCrossTypeMerge),不在候选生成。
153
+ for (let i = 0; i < usableMemories.length; i++) {
154
+ for (let j = i + 1; j < usableMemories.length; j++) {
155
+ if (usableMemories[i].type === usableMemories[j].type) continue;
156
+ const sim = cosineSimilarity(usableVectors[i], usableVectors[j]);
157
+ if (sim > threshold) pairs.push({ a: usableMemories[i], b: usableMemories[j], similarity: sim });
158
+ }
159
+ }
160
+ }
161
+ if (pairs.length === 0) return { status: "skipped", reason: "no conflicts found" };
162
+
163
+ // Dedupe: each memory participates in at most one pair, highest similarity
164
+ // first — overlapping pairs would violate validateDecisions' "one claim".
165
+ pairs.sort((a, b) => b.similarity - a.similarity);
166
+ const used = new Set();
167
+ const selected = [];
168
+ for (const p of pairs) {
169
+ if (used.has(p.a.id) || used.has(p.b.id)) continue;
170
+ used.add(p.a.id);
171
+ used.add(p.b.id);
172
+ selected.push(p);
173
+ }
174
+
175
+ // v0.8.1(issue #170 第 2 步):跨 scope 相似对分流。同一内容落在两个归属下
176
+ // (任一维标注键不等即算,NULL=未标注=全局也参与比较——「全局副本 + 专属副本
177
+ // 并存」正是收窄/提升裁决的典型候选)不能自动裁决:归档败者可能销毁该内容在
178
+ // 某个归属下的唯一副本,LLM 也无从替用户决定归属。一律停车到冲突待确认队列
179
+ // (专属 reason),同 scope 对维持既有路径(freeze 停车 / LLM 裁决)。
180
+ const isCrossScopePair = (p) =>
181
+ scopeKeyOf(p.a.agent_scope) !== scopeKeyOf(p.b.agent_scope)
182
+ || scopeKeyOf(p.a.workspace_scope) !== scopeKeyOf(p.b.workspace_scope);
183
+ const crossPairs = selected.filter(isCrossScopePair);
184
+ const samePairs = selected.filter((p) => !isCrossScopePair(p));
185
+ const parkPair = (p, reason) => {
186
+ try {
187
+ // 返回 undefined = 该对已被人工裁决且两侧内容未变(复核项 4)——不算停车。
188
+ return service.saveConflictPending({ run_id: runId, memory_a: p.a.id, memory_b: p.b.id, reason }) != null;
189
+ } catch (error) {
190
+ logger?.warn?.(`dsh-mneme sleep: failed to park conflict ${p.a.id}/${p.b.id}: ${String(error)}`);
191
+ return false;
192
+ }
193
+ };
194
+ const scopeReason = (p) => STR.scopeCandidateReason[language](p.similarity.toFixed(2));
195
+ const simReason = (p) => STR.similarityReason[language](p.similarity.toFixed(2));
196
+
197
+ // Freeze mode: park pairs for manual review, no LLM required. Cross-scope
198
+ // pairs carry the dedicated scope-candidate reason so the queue reads them
199
+ // as ownership decisions rather than plain duplicates.
200
+ if (config.conflictFreezeEnabled === true) {
201
+ let frozen = 0;
202
+ for (const p of selected) {
203
+ if (parkPair(p, isCrossScopePair(p) ? scopeReason(p) : simReason(p))) frozen++;
204
+ }
205
+ return { status: frozen > 0 ? "ok" : "noop", frozen, scopeCandidates: crossPairs.length, pairs: selected.length };
206
+ }
207
+
208
+ // 非 freeze:跨 scope 对先停车(绝不进 LLM 裁决),同 scope 对照常走 LLM。
209
+ let scopeParked = 0;
210
+ for (const p of crossPairs) {
211
+ if (parkPair(p, scopeReason(p))) scopeParked++;
212
+ }
213
+ if (samePairs.length === 0) {
214
+ return { status: scopeParked > 0 ? "ok" : "noop", frozen: 0, scopeCandidates: scopeParked, pairs: selected.length };
215
+ }
216
+
217
+ // LLM adjudication(仅同 scope 对)。
218
+ const route = resolveSleepRoute(ctx, config, logger);
219
+ if (!route) return { status: "skipped", reason: "no llm route", scopeCandidates: scopeParked, pairs: selected.length };
220
+ const snapshot = new Map();
221
+ for (const p of samePairs) {
222
+ snapshot.set(p.a.id, p.a);
223
+ snapshot.set(p.b.id, p.b);
224
+ }
225
+ const listText = samePairs.map((p) =>
226
+ STR.candidateConflicts[language](p)
227
+ ).join("\n\n");
228
+ const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
229
+ let conflictStreamFailure = "";
230
+ // actionSet 已在候选构造前解析(跨类型候选需要它),这里只按档位选 prompt:
231
+ // 默认档保持只有 conflict/keep 的窄 prompt,"full" 才开放六分支。
232
+ const conflictPrompt = actionSet === "full" ? STR.prompts.conflictFull[language] : STR.prompts.conflict[language];
233
+ const runConflict = (withEffort) => {
234
+ conflictStreamFailure = "";
235
+ return streamText(ctx, {
236
+ provider: route.provider,
237
+ model: route.model,
238
+ purpose: "sleep-conflict",
239
+ maxTokens: 2048,
240
+ ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
241
+ messages: [
242
+ { role: "system", content: [{ type: "text", text: conflictPrompt }], source: { kind: "plugin", plugin: "dsh-mneme" } },
243
+ { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin", plugin: "dsh-mneme" } }
244
+ ]
245
+ }, (reason) => { conflictStreamFailure = describeStreamFailure(reason); });
246
+ };
247
+ const text = await withEffortFallback(ctx, sleepEffort, () => runConflict(true), () => runConflict(false), () => conflictStreamFailure);
248
+ if (text === undefined) {
249
+ if (conflictStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: conflict stream aborted or errored (${conflictStreamFailure})`);
250
+ return { status: "failed", error: "llm failed" };
251
+ }
252
+ const decisions = parseJsonArray(text);
253
+ if (!decisions) return { status: "failed", error: "invalid decisions json" };
254
+ // validateDecisions 要求每个 snapshot id 恰好被 claim 一次。v0.4.4 起它本身
255
+ // 就会为未覆盖的 id 自动补 keep(dreamImplicitKeep 默认开启),这里保留显式
256
+ // 预填作为防御性双保险——漏判读作"未裁决冲突"而非"冲突阶段整体失败"。
257
+ const covered = new Set();
258
+ for (const d of decisions) {
259
+ // Issue #126 review(Copilot):supersede 同样用 winner/loser 定位(没有 ids),
260
+ // 此前只认 conflict → 它的两个目标都没进 covered → 被补成 implicit keep → 与
261
+ // supersede 的 claim 冲突:严格模式整单拒绝,宽容模式把合成的 keep 记成 skipped。
262
+ if (d?.action === "conflict" || d?.action === "supersede") {
263
+ if (typeof d?.winner === "string") covered.add(d.winner);
264
+ if (typeof d?.loser === "string") covered.add(d.loser);
265
+ } else if (Array.isArray(d?.ids)) {
266
+ for (const id of d.ids) covered.add(id);
267
+ }
268
+ }
269
+ for (const id of snapshot.keys()) {
270
+ if (!covered.has(id)) decisions.push({ action: "keep", ids: [id] });
271
+ }
272
+ // Issue #126:sleep 是多对批量裁决,严格模式"一票否决"太脆(一对非法就丢掉整轮
273
+ // 成果)→ 与 dream 对齐透传 skipInvalid:非法的那一对只跳过自己,合法子集照常
274
+ // 应用,run 记 degraded。update 上限与保护期同样取 dream 的同一组配置,保证两个
275
+ // 模块对"什么算合法"的判据一致。
276
+ const { ok, errors, skipped } = validateDecisions(decisions, snapshot, {
277
+ maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
278
+ minAgeHours: config.reflectionUpdateMinAgeHours,
279
+ skipInvalid: config.dreamSkipInvalid !== false,
280
+ allowCrossTypeMerge: config.allowCrossTypeMerge === true,
281
+ // Issue #126 review(Copilot):默认档必须真的只放行旧动作集——只换 prompt 挡不住
282
+ // 模型自发输出 supersede / differentiate,那样"opt-in 零行为变化"就不成立。
283
+ allowedActions: actionSet === "full" ? null : LEGACY_ACTIONS
284
+ });
285
+ if (!ok) return { status: "failed", error: `invalid decisions: ${errors.join("; ")}`, skipped };
286
+ const { applied, failures, conflicts } = applyDecisions(decisions, service, logger, snapshot, config);
287
+ // Issue #126 review(Copilot):事务内 service.update 会跳过 scheduleEmbed(txDepth>0),
288
+ // 而 sleep 路径此前没有 dream 那样的 post-apply 索引维护——differentiate 的差异注记与
289
+ // supersede 的归档都反映不到缓存向量,"注记进 embedding 防再判重复"就是空承诺。
290
+ if (applied > 0 && semantic?.embedder && semantic?.vectorIndex) {
291
+ try {
292
+ await maintainIndexAfterDream(decisions, service, semantic);
293
+ } catch (error) {
294
+ logger?.warn?.(`dsh-mneme sleep: index maintenance failed: ${String(error)}`);
295
+ }
296
+ }
297
+ // Issue #126 review(Copilot):有决策被跳过时不能报 ok——与 dream 的 degraded 契约
298
+ // 对齐("合法子集已应用"是 degraded 而非 ok),否则消费方分不清整轮与残轮。
299
+ const degraded = skipped.length > 0;
300
+ return {
301
+ status: applied > 0 ? (degraded ? "degraded" : "ok") : failures.length ? "failed" : "noop",
302
+ pairs: selected.length,
303
+ applied,
304
+ failures,
305
+ conflicts,
306
+ // Issue #126:#104 同向——被跳过的逐对明细要进审计行,否则事后无法判断
307
+ // 是哪一对、因何被跳过(此前只进 logger.warn,splice 后就地消失)。
308
+ skipped
309
+ };
310
+ }
311
+
312
+ /**
313
+ * Phase 2 — archival demotion. No LLM: tiering is time-based, summaries are
314
+ * truncations, and the full body is preserved in _full_content so nothing is
315
+ * lost. Deterministic and cheap, so it runs even with no LLM route.
316
+ */
317
+ function phaseDemotion(service, config, logger, runId, signal = null) {
318
+ const archiveDays = config.sleepArchiveDays ?? 30;
319
+ const compressDays = config.sleepCompressDays ?? 90;
320
+ const archiveCut = Date.now() - archiveDays * 86400000;
321
+ const compressCut = Date.now() - compressDays * 86400000;
322
+ const demoted = [];
323
+ const archived = [];
324
+ for (const m of service.all()) {
325
+ if (signal?.aborted) break;
326
+ if (m.archived || m.forgotten) continue;
327
+ const ref = m.last_accessed_at ?? m.created_at;
328
+ if (!ref) continue;
329
+ const t = new Date(ref).getTime();
330
+ if (Number.isNaN(t)) continue;
331
+ // v0.7.0 热联合判定(仅 heatEnabled 时启用;默认关则退回纯时间分层,
332
+ // 与 v0.7.12 行为一致):时间窗之外再加两道保护闸——热度低于
333
+ // sleepHeatThreshold 且 importance<5 才允许降级。λ=0 的免疫类型 heat 恒
334
+ // 1.0 天然豁免(preference/pattern/summary 永不因 sleep 降级);importance
335
+ // ≥5 的紧要记忆无论多冷都保留。`冷但重要` 与 `热但低值` 均不满足条件。
336
+ const heatOn = config.heatEnabled !== false;
337
+ if (heatOn) {
338
+ const heat = computeHeat(m, Date.now(), config);
339
+ const heatProtected = heat >= (config.sleepHeatThreshold ?? 0.05);
340
+ const important = (m.importance ?? 0) >= 5;
341
+ if (heatProtected || important) continue;
342
+ }
343
+ if (t < compressCut) {
344
+ service.setArchived(m.id, true);
345
+ archived.push(m.id);
346
+ } else if (t < archiveCut) {
347
+ // minRefTimeMs re-checks freshness inside demoteToSummary's transaction:
348
+ // a recall touch landing after this snapshot must not demote the memory.
349
+ service.demoteToSummary(m.id, makeSummary(m), { minRefTimeMs: archiveCut });
350
+ demoted.push(m.id);
351
+ }
352
+ }
353
+ return {
354
+ status: demoted.length || archived.length ? "ok" : "noop",
355
+ demoted,
356
+ archived
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Phase 3 — pattern discovery. The LLM scans the most recent memories and
362
+ * mints type=pattern entries (create actions) with evidence references.
363
+ * The empty snapshot is intentional: create claims no existing id, so the
364
+ * "every id claimed" invariant is trivially satisfied for pure-create lists.
365
+ */
366
+ async function phasePatterns(ctx, service, config, logger, runId, signal = null) {
367
+ const language = langOf(config);
368
+ const route = resolveSleepRoute(ctx, config, logger);
369
+ if (!route) return { status: "skipped", reason: "no llm route" };
370
+ const limit = config.sleepPatternMinMemories ?? 100;
371
+ const memories = service
372
+ .list({ limit: 200, includeForgotten: false })
373
+ .filter((m) => !m.archived && m.type !== "summary" && m.type !== "pattern")
374
+ .sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))
375
+ .slice(0, limit);
376
+ if (memories.length === 0) return { status: "skipped", reason: "no memories to scan" };
377
+ if (signal?.aborted) return { status: "aborted", reason: "user activity" };
378
+ const listText = memories
379
+ .map((m) => `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`)
380
+ .join("\n");
381
+ const maxPatterns = config.sleepMaxPatternPerRun ?? 3;
382
+ const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
383
+ let patternStreamFailure = "";
384
+ const runPattern = (withEffort) => {
385
+ patternStreamFailure = "";
386
+ return streamText(ctx, {
387
+ provider: route.provider,
388
+ model: route.model,
389
+ purpose: "sleep-pattern",
390
+ maxTokens: 2048,
391
+ ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
392
+ messages: [
393
+ { role: "system", content: [{ type: "text", text: STR.prompts.pattern[language].replace("N", String(maxPatterns)) }], source: { kind: "plugin", plugin: "dsh-mneme" } },
394
+ { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin", plugin: "dsh-mneme" } }
395
+ ]
396
+ }, (reason) => { patternStreamFailure = describeStreamFailure(reason); });
397
+ };
398
+ const text = await withEffortFallback(ctx, sleepEffort, () => runPattern(true), () => runPattern(false), () => patternStreamFailure);
399
+ if (text === undefined) {
400
+ if (patternStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: pattern stream aborted or errored (${patternStreamFailure})`);
401
+ return { status: "failed", error: "llm failed" };
402
+ }
403
+ const decisions = parseJsonArray(text);
404
+ if (!decisions || decisions.length === 0) return { status: "skipped", reason: "no patterns found" };
405
+ // Evidence ids are provenance refs; an LLM-fabricated id would mint a dead
406
+ // ev:tag pointing nowhere. Intersect evidence with the scanned set so only
407
+ // real memory references survive.
408
+ const scannedIds = new Set(memories.map((m) => m.id));
409
+ for (const d of decisions) {
410
+ if (d?.action === "create" && Array.isArray(d.evidence)) {
411
+ d.evidence = d.evidence.filter((id) => typeof id === "string" && scannedIds.has(id));
412
+ }
413
+ }
414
+ const snapshot = new Map();
415
+ const { ok, errors } = validateDecisions(decisions, snapshot, {
416
+ maxCreatePerRun: maxPatterns
417
+ });
418
+ if (!ok) return { status: "failed", error: `invalid decisions: ${errors.join("; ")}` };
419
+ const { applied, failures, conflicts } = applyDecisions(decisions, service, logger, snapshot, config);
420
+ return {
421
+ status: applied > 0 ? "ok" : "noop",
422
+ scanned: memories.length,
423
+ applied,
424
+ failures,
425
+ conflicts
426
+ };
427
+ }
428
+
429
+ /**
430
+ * Phase 4 — entity relation completion. Detects orphan entities (zero
431
+ * relations) and completes implied relations from memory co-occurrence:
432
+ * entities named in the same memory → related_to; container kinds
433
+ * (project/module) → part_of; tech-ish pairs → depends_on. Deterministic,
434
+ * no LLM — cheap, so it runs even without a route. saveRelation is
435
+ * bookkeeping (no write hook), so it never re-triggers the scheduler.
436
+ */
437
+ function inferRelationType(a, b) {
438
+ if ((a.type === "project" || a.type === "module") && a.type !== b.type) return "part_of";
439
+ if ((b.type === "project" || b.type === "module") && b.type !== a.type) return "part_of";
440
+ if (/npm|plugin|api|sdk|lib|framework|package|deps?|build/i.test(`${a.name} ${b.name}`)) return "depends_on";
441
+ return "related_to";
442
+ }
443
+
444
+ function phaseRelations(service, config, logger, runId, signal = null) {
445
+ const entities = service.listEntities({ limit: 1000 }) ?? [];
446
+ if (entities.length < 2) return { status: "skipped", reason: "too few entities" };
447
+ const orphans = entities.filter((e) => (service.getRelations(e.id) ?? []).length === 0);
448
+ if (orphans.length === 0) return { status: "skipped", reason: "no orphan entities" };
449
+ const memories = service.all().filter((m) => !m.archived && !m.forgotten);
450
+ const seen = new Set();
451
+ const related = [];
452
+ const MAX_RELATIONS_PER_ORPHAN = 3;
453
+ for (const o of orphans) {
454
+ if (signal?.aborted) break;
455
+ let made = 0;
456
+ for (const m of memories) {
457
+ if (signal?.aborted || made >= MAX_RELATIONS_PER_ORPHAN) break;
458
+ const text = `${m.title ?? ""} ${m.content ?? ""}`;
459
+ if (!text.includes(o.name)) continue;
460
+ for (const other of entities) {
461
+ if (other.id === o.id || other.name === o.name) continue;
462
+ const key = [o.id, other.id].sort().join("|");
463
+ if (seen.has(key)) continue;
464
+ if (!text.includes(other.name)) continue;
465
+ const relationType = inferRelationType(o, other);
466
+ try {
467
+ service.saveRelation({ from_entity: o.id, to_entity: other.id, relation_type: relationType, memory_id: m.id, metadata: { source: "sleep_relation_completion" } });
468
+ seen.add(key);
469
+ related.push({ from: o.id, to: other.id, type: relationType });
470
+ made++;
471
+ } catch (error) {
472
+ logger?.warn?.(`dsh-mneme sleep: relation ${o.id}/${other.id} failed: ${String(error)}`);
473
+ }
474
+ }
475
+ }
476
+ }
477
+ return {
478
+ status: related.length > 0 ? "ok" : "noop",
479
+ orphanCount: orphans.length,
480
+ related
481
+ };
482
+ }
483
+
484
+ // ---------------------------------------------------------------- run
485
+
486
+ function deriveStatus(phases) {
487
+ const list = Object.values(phases);
488
+ if (list.length === 0) return "noop";
489
+ const anyError = list.some((p) => p.status === "failed" || p.status === "error");
490
+ // Issue #126 review(Copilot):phase 自身可以是 degraded(合法子集已应用但有条目被
491
+ // 跳过),它同样算"有产出"——否则整轮会被误判成 noop,把真实变更报成空轮。
492
+ const anyWork = list.some((p) => p.status === "ok" || p.status === "degraded");
493
+ const anyDegraded = list.some((p) => p.status === "degraded");
494
+ if (anyDegraded) return "degraded";
495
+ if (anyWork && anyError) return "degraded";
496
+ if (anyError) return "failed";
497
+ if (anyWork) return "ok";
498
+ return "noop";
499
+ }
500
+
501
+ /**
502
+ * Run one full sleep cycle. Best-effort across all phases; writes a
503
+ * run_type='sleep' audit row (same dream_runs table) so sleep activity is
504
+ * observable alongside consolidation runs.
505
+ */
506
+ export async function runSleep(ctx, service, config, logger, semantic = null, signal = null) {
507
+ const runId = randomUUID();
508
+ const phases = {};
509
+ const attempt = async (name, fn) => {
510
+ if (signal?.aborted) return; // user resumed activity — stop before next phase
511
+ try {
512
+ phases[name] = await fn();
513
+ } catch (error) {
514
+ phases[name] = { status: "failed", error: error?.message ?? String(error) };
515
+ logger?.warn?.(`dsh-mneme sleep: ${name} phase failed: ${error?.message ?? error}`);
516
+ }
517
+ };
518
+ await attempt("conflicts", () => phaseConflicts(ctx, service, config, logger, runId, semantic, signal));
519
+ await attempt("demotion", () => phaseDemotion(service, config, logger, runId, signal));
520
+ await attempt("patterns", () => phasePatterns(ctx, service, config, logger, runId, signal));
521
+ await attempt("relations", () => phaseRelations(service, config, logger, runId, signal));
522
+
523
+ const status = deriveStatus(phases);
524
+ const route = resolveSleepRoute(ctx, config, logger);
525
+ const totalApplied = Object.values(phases).reduce((n, p) => n + (Number.isInteger(p?.applied) ? p.applied : 0), 0);
526
+ // Issue #126(与 #104 同向):把各 phase 的跳过明细汇总成一行审计数据,带 phase
527
+ // 名(同一次 run 里 conflicts 与 patterns 都可能产出 skipped)。全空时写 NULL,
528
+ // 不落空数组——审计行只记真实发生过的跳过。
529
+ const skippedDetail = Object.entries(phases).flatMap(([phase, p]) =>
530
+ Array.isArray(p?.skipped) ? p.skipped.map((s) => ({ phase, ...s })) : []
531
+ );
532
+ const snapshotHash = createHash("sha256").update(JSON.stringify(phases)).digest("hex");
533
+ const receipt = buildReceipt({
534
+ runId,
535
+ status,
536
+ snapshotHash,
537
+ inputCount: 0,
538
+ applied: totalApplied,
539
+ summaryStored: false
540
+ });
541
+ try {
542
+ service.saveDreamRun({
543
+ id: runId,
544
+ status,
545
+ provider: route?.provider,
546
+ model: route?.model,
547
+ snapshot_hash: snapshotHash,
548
+ input_count: 0,
549
+ input: null,
550
+ decisions: phases,
551
+ outcome: phases,
552
+ applied: totalApplied,
553
+ summary_stored: false,
554
+ receipt,
555
+ policy_epoch: config.policyEpoch ?? 0,
556
+ run_type: "sleep",
557
+ skipped: skippedDetail.length ? skippedDetail : undefined
558
+ });
559
+ } catch (error) {
560
+ logger?.warn?.(`dsh-mneme sleep: failed to record audit run: ${String(error)}`);
561
+ }
562
+ return { ok: status === "ok" || status === "degraded", status, runId, phases, receipt };
563
+ }
564
+
565
+ // ---------------------------------------------------------------- scheduler
566
+
567
+ /**
568
+ * Idle-triggered scheduler. DSH plugins have no resident cron, so a sleep run
569
+ * fires when: sleep is enabled, the store has been quiet for sleepIdleMinutes,
570
+ * and the previous run is older than sleepMinIntervalHours. noteWrite() is
571
+ * called on every store write and (re)arms an idle timer that re-checks at the
572
+ * exact moment the idle window elapses — no polling, no cron.
573
+ *
574
+ * A `now` clock can be injected for tests; it defaults to Date.now.
575
+ */
576
+ export function createSleepScheduler({
577
+ service,
578
+ config,
579
+ logger,
580
+ onRun = null,
581
+ now = () => Date.now(),
582
+ setTimeoutFn = setTimeout,
583
+ clearTimeoutFn = clearTimeout
584
+ }) {
585
+ let lastWriteAt = now();
586
+ let lastRunAt = 0;
587
+ let running = false;
588
+ let disposed = false;
589
+ let idleTimer = null;
590
+ let sleepAbort = null;
591
+
592
+ function armIdleTimer() {
593
+ if (disposed || idleTimer) return;
594
+ if (config.sleepModeEnabled !== true) return;
595
+ const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
596
+ const delay = Math.max(0, idleMs - (now() - lastWriteAt)) + 1000;
597
+ idleTimer = setTimeoutFn(async () => {
598
+ idleTimer = null;
599
+ // Issue #187:false = 撞上 CD(或 run 失败)——此前这里直接丢弃,"CD 到期"
600
+ // 成了没有监听者的时刻,要等下一次写入才救回来。改为按剩余窗口重排。
601
+ const ran = await maybeSchedule();
602
+ if (!ran) armNextWindow();
603
+ }, delay);
604
+ idleTimer.unref?.();
605
+ }
606
+
607
+ // Issue #187:撞 CD / run 失败后的补挂表——按「剩余 CD / 剩余静默」里更晚的
608
+ // 到点时刻重排一次,回调里重复同样的判断所以不会空转。跑成了一轮就不重排:
609
+ // 安静的库没有要处理的新东西,触发权交还给下一次写入的 noteWrite。
610
+ function armNextWindow() {
611
+ if (disposed || idleTimer) return;
612
+ if (config.sleepModeEnabled !== true) return;
613
+ // lastRunAt === 0 表示从未跑过(此路径不该出现,防御性返回)。
614
+ if (lastRunAt <= 0) return;
615
+ const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
616
+ const cdMs = (config.sleepMinIntervalHours ?? 8) * 3600000;
617
+ const delay = Math.max(
618
+ lastRunAt + cdMs - now(),
619
+ lastWriteAt + idleMs - now(),
620
+ 0
621
+ ) + 1000;
622
+ idleTimer = setTimeoutFn(async () => {
623
+ idleTimer = null;
624
+ const ran = await maybeSchedule();
625
+ if (!ran) armNextWindow();
626
+ }, delay);
627
+ idleTimer.unref?.();
628
+ }
629
+
630
+ function shouldRun(at = now()) {
631
+ if (disposed || running) return false;
632
+ if (config.sleepModeEnabled !== true) return false;
633
+ if (at - lastWriteAt < (config.sleepIdleMinutes ?? 5) * 60000) return false;
634
+ // lastRunAt === 0 means never ran — the min-interval check must not block
635
+ // the very first cycle (a real run stamps a nonzero timestamp).
636
+ if (lastRunAt > 0 && at - lastRunAt < (config.sleepMinIntervalHours ?? 8) * 3600000) return false;
637
+ return true;
638
+ }
639
+
640
+ /** Called on writes: resets the idle clock and re-arms the fire timer. The
641
+ * pending timer is cleared first — a stale timer armed against the old idle
642
+ * window would otherwise fire early, fail shouldRun, and leave nothing armed
643
+ * for the next window (a missed trigger until the next write).
644
+ *
645
+ * While a sleep run is executing (running=true) the in-flight AbortController
646
+ * is NOT aborted: the run's own writes (demoteToSummary / setArchived ride
647
+ * the normal write-hook path) would otherwise self-abort the cycle. External
648
+ * activity during the run still resets the idle clock here, so no new cycle
649
+ * fires until the store is quiet again. */
650
+ function noteWrite() {
651
+ lastWriteAt = now();
652
+ if (!running && sleepAbort) {
653
+ sleepAbort.abort(); // user resumed activity — interrupt an idle run
654
+ }
655
+ if (idleTimer) {
656
+ clearTimeoutFn(idleTimer);
657
+ idleTimer = null;
658
+ }
659
+ armIdleTimer();
660
+ }
661
+
662
+ async function maybeSchedule() {
663
+ if (!shouldRun()) return false;
664
+ running = true;
665
+ const abort = new AbortController();
666
+ sleepAbort = abort;
667
+ try {
668
+ lastRunAt = now();
669
+ const result = await service.enqueue(() =>
670
+ onRun ? onRun(abort.signal) : Promise.resolve({ ok: true, skipped: true })
671
+ );
672
+ return !!(result && result.ok);
673
+ } catch (error) {
674
+ logger?.warn?.(`dsh-mneme sleep: run failed: ${error?.message ?? error}`);
675
+ return false;
676
+ } finally {
677
+ sleepAbort = null;
678
+ running = false;
679
+ }
680
+ }
681
+
682
+ async function dispose() {
683
+ disposed = true;
684
+ if (idleTimer) {
685
+ clearTimeoutFn(idleTimer);
686
+ idleTimer = null;
687
+ }
688
+ if (sleepAbort) {
689
+ sleepAbort.abort();
690
+ sleepAbort = null;
691
+ }
692
+ }
693
+
694
+ // Issue #187(同族缺陷):构造即挂表——重启后只要没发生过写入,此前永远没有
695
+ // 闹钟,安静多久都不会触发。lastWriteAt 已在构造时设为当前时刻,shouldRun 的
696
+ // 静默条件自然生效:重启后静默满 idleMinutes 才可能起跑。
697
+ armIdleTimer();
698
+
699
+ return { noteWrite, maybeSchedule, shouldRun, dispose };
700
+ }