@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,700 +1,702 @@
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" && m.type !== "document");
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: config.sleepMaxTokens ?? 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
+ // #230:document 在查询层排除(excludeTypes)而不是截断后过滤——LIMIT 200
372
+ // 先生效的话,指针行一多就会把普通记忆挤出扫描窗,池子饿到门槛以下。
373
+ const memories = service
374
+ .list({ limit: 200, includeForgotten: false, excludeTypes: ["document"] })
375
+ .filter((m) => !m.archived && m.type !== "summary" && m.type !== "pattern")
376
+ .sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))
377
+ .slice(0, limit);
378
+ if (memories.length === 0) return { status: "skipped", reason: "no memories to scan" };
379
+ if (signal?.aborted) return { status: "aborted", reason: "user activity" };
380
+ const listText = memories
381
+ .map((m) => `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`)
382
+ .join("\n");
383
+ const maxPatterns = config.sleepMaxPatternPerRun ?? 3;
384
+ const sleepEffort = await resolveDreamEffort(ctx, route, config.sleepReasoningEffort, logger);
385
+ let patternStreamFailure = "";
386
+ const runPattern = (withEffort) => {
387
+ patternStreamFailure = "";
388
+ return streamText(ctx, {
389
+ provider: route.provider,
390
+ model: route.model,
391
+ purpose: "sleep-pattern",
392
+ maxTokens: config.sleepMaxTokens ?? 2048,
393
+ ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
394
+ messages: [
395
+ { role: "system", content: [{ type: "text", text: STR.prompts.pattern[language].replace("N", String(maxPatterns)) }], source: { kind: "plugin", plugin: "dsh-mneme" } },
396
+ { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin", plugin: "dsh-mneme" } }
397
+ ]
398
+ }, (reason) => { patternStreamFailure = describeStreamFailure(reason); });
399
+ };
400
+ const text = await withEffortFallback(ctx, sleepEffort, () => runPattern(true), () => runPattern(false), () => patternStreamFailure);
401
+ if (text === undefined) {
402
+ if (patternStreamFailure) ctx.logger?.warn?.(`dsh-mneme sleep: pattern stream aborted or errored (${patternStreamFailure})`);
403
+ return { status: "failed", error: "llm failed" };
404
+ }
405
+ const decisions = parseJsonArray(text);
406
+ if (!decisions || decisions.length === 0) return { status: "skipped", reason: "no patterns found" };
407
+ // Evidence ids are provenance refs; an LLM-fabricated id would mint a dead
408
+ // ev:tag pointing nowhere. Intersect evidence with the scanned set so only
409
+ // real memory references survive.
410
+ const scannedIds = new Set(memories.map((m) => m.id));
411
+ for (const d of decisions) {
412
+ if (d?.action === "create" && Array.isArray(d.evidence)) {
413
+ d.evidence = d.evidence.filter((id) => typeof id === "string" && scannedIds.has(id));
414
+ }
415
+ }
416
+ const snapshot = new Map();
417
+ const { ok, errors } = validateDecisions(decisions, snapshot, {
418
+ maxCreatePerRun: maxPatterns
419
+ });
420
+ if (!ok) return { status: "failed", error: `invalid decisions: ${errors.join("; ")}` };
421
+ const { applied, failures, conflicts } = applyDecisions(decisions, service, logger, snapshot, config);
422
+ return {
423
+ status: applied > 0 ? "ok" : "noop",
424
+ scanned: memories.length,
425
+ applied,
426
+ failures,
427
+ conflicts
428
+ };
429
+ }
430
+
431
+ /**
432
+ * Phase 4 — entity relation completion. Detects orphan entities (zero
433
+ * relations) and completes implied relations from memory co-occurrence:
434
+ * entities named in the same memory → related_to; container kinds
435
+ * (project/module) → part_of; tech-ish pairs → depends_on. Deterministic,
436
+ * no LLM — cheap, so it runs even without a route. saveRelation is
437
+ * bookkeeping (no write hook), so it never re-triggers the scheduler.
438
+ */
439
+ function inferRelationType(a, b) {
440
+ if ((a.type === "project" || a.type === "module") && a.type !== b.type) return "part_of";
441
+ if ((b.type === "project" || b.type === "module") && b.type !== a.type) return "part_of";
442
+ if (/npm|plugin|api|sdk|lib|framework|package|deps?|build/i.test(`${a.name} ${b.name}`)) return "depends_on";
443
+ return "related_to";
444
+ }
445
+
446
+ function phaseRelations(service, config, logger, runId, signal = null) {
447
+ const entities = service.listEntities({ limit: 1000 }) ?? [];
448
+ if (entities.length < 2) return { status: "skipped", reason: "too few entities" };
449
+ const orphans = entities.filter((e) => (service.getRelations(e.id) ?? []).length === 0);
450
+ if (orphans.length === 0) return { status: "skipped", reason: "no orphan entities" };
451
+ const memories = service.all().filter((m) => !m.archived && !m.forgotten);
452
+ const seen = new Set();
453
+ const related = [];
454
+ const MAX_RELATIONS_PER_ORPHAN = 3;
455
+ for (const o of orphans) {
456
+ if (signal?.aborted) break;
457
+ let made = 0;
458
+ for (const m of memories) {
459
+ if (signal?.aborted || made >= MAX_RELATIONS_PER_ORPHAN) break;
460
+ const text = `${m.title ?? ""} ${m.content ?? ""}`;
461
+ if (!text.includes(o.name)) continue;
462
+ for (const other of entities) {
463
+ if (other.id === o.id || other.name === o.name) continue;
464
+ const key = [o.id, other.id].sort().join("|");
465
+ if (seen.has(key)) continue;
466
+ if (!text.includes(other.name)) continue;
467
+ const relationType = inferRelationType(o, other);
468
+ try {
469
+ service.saveRelation({ from_entity: o.id, to_entity: other.id, relation_type: relationType, memory_id: m.id, metadata: { source: "sleep_relation_completion" } });
470
+ seen.add(key);
471
+ related.push({ from: o.id, to: other.id, type: relationType });
472
+ made++;
473
+ } catch (error) {
474
+ logger?.warn?.(`dsh-mneme sleep: relation ${o.id}/${other.id} failed: ${String(error)}`);
475
+ }
476
+ }
477
+ }
478
+ }
479
+ return {
480
+ status: related.length > 0 ? "ok" : "noop",
481
+ orphanCount: orphans.length,
482
+ related
483
+ };
484
+ }
485
+
486
+ // ---------------------------------------------------------------- run
487
+
488
+ function deriveStatus(phases) {
489
+ const list = Object.values(phases);
490
+ if (list.length === 0) return "noop";
491
+ const anyError = list.some((p) => p.status === "failed" || p.status === "error");
492
+ // Issue #126 review(Copilot):phase 自身可以是 degraded(合法子集已应用但有条目被
493
+ // 跳过),它同样算"有产出"——否则整轮会被误判成 noop,把真实变更报成空轮。
494
+ const anyWork = list.some((p) => p.status === "ok" || p.status === "degraded");
495
+ const anyDegraded = list.some((p) => p.status === "degraded");
496
+ if (anyDegraded) return "degraded";
497
+ if (anyWork && anyError) return "degraded";
498
+ if (anyError) return "failed";
499
+ if (anyWork) return "ok";
500
+ return "noop";
501
+ }
502
+
503
+ /**
504
+ * Run one full sleep cycle. Best-effort across all phases; writes a
505
+ * run_type='sleep' audit row (same dream_runs table) so sleep activity is
506
+ * observable alongside consolidation runs.
507
+ */
508
+ export async function runSleep(ctx, service, config, logger, semantic = null, signal = null) {
509
+ const runId = randomUUID();
510
+ const phases = {};
511
+ const attempt = async (name, fn) => {
512
+ if (signal?.aborted) return; // user resumed activity — stop before next phase
513
+ try {
514
+ phases[name] = await fn();
515
+ } catch (error) {
516
+ phases[name] = { status: "failed", error: error?.message ?? String(error) };
517
+ logger?.warn?.(`dsh-mneme sleep: ${name} phase failed: ${error?.message ?? error}`);
518
+ }
519
+ };
520
+ await attempt("conflicts", () => phaseConflicts(ctx, service, config, logger, runId, semantic, signal));
521
+ await attempt("demotion", () => phaseDemotion(service, config, logger, runId, signal));
522
+ await attempt("patterns", () => phasePatterns(ctx, service, config, logger, runId, signal));
523
+ await attempt("relations", () => phaseRelations(service, config, logger, runId, signal));
524
+
525
+ const status = deriveStatus(phases);
526
+ const route = resolveSleepRoute(ctx, config, logger);
527
+ const totalApplied = Object.values(phases).reduce((n, p) => n + (Number.isInteger(p?.applied) ? p.applied : 0), 0);
528
+ // Issue #126(与 #104 同向):把各 phase 的跳过明细汇总成一行审计数据,带 phase
529
+ // 名(同一次 run 里 conflicts 与 patterns 都可能产出 skipped)。全空时写 NULL,
530
+ // 不落空数组——审计行只记真实发生过的跳过。
531
+ const skippedDetail = Object.entries(phases).flatMap(([phase, p]) =>
532
+ Array.isArray(p?.skipped) ? p.skipped.map((s) => ({ phase, ...s })) : []
533
+ );
534
+ const snapshotHash = createHash("sha256").update(JSON.stringify(phases)).digest("hex");
535
+ const receipt = buildReceipt({
536
+ runId,
537
+ status,
538
+ snapshotHash,
539
+ inputCount: 0,
540
+ applied: totalApplied,
541
+ summaryStored: false
542
+ });
543
+ try {
544
+ service.saveDreamRun({
545
+ id: runId,
546
+ status,
547
+ provider: route?.provider,
548
+ model: route?.model,
549
+ snapshot_hash: snapshotHash,
550
+ input_count: 0,
551
+ input: null,
552
+ decisions: phases,
553
+ outcome: phases,
554
+ applied: totalApplied,
555
+ summary_stored: false,
556
+ receipt,
557
+ policy_epoch: config.policyEpoch ?? 0,
558
+ run_type: "sleep",
559
+ skipped: skippedDetail.length ? skippedDetail : undefined
560
+ });
561
+ } catch (error) {
562
+ logger?.warn?.(`dsh-mneme sleep: failed to record audit run: ${String(error)}`);
563
+ }
564
+ return { ok: status === "ok" || status === "degraded", status, runId, phases, receipt };
565
+ }
566
+
567
+ // ---------------------------------------------------------------- scheduler
568
+
569
+ /**
570
+ * Idle-triggered scheduler. DSH plugins have no resident cron, so a sleep run
571
+ * fires when: sleep is enabled, the store has been quiet for sleepIdleMinutes,
572
+ * and the previous run is older than sleepMinIntervalHours. noteWrite() is
573
+ * called on every store write and (re)arms an idle timer that re-checks at the
574
+ * exact moment the idle window elapses — no polling, no cron.
575
+ *
576
+ * A `now` clock can be injected for tests; it defaults to Date.now.
577
+ */
578
+ export function createSleepScheduler({
579
+ service,
580
+ config,
581
+ logger,
582
+ onRun = null,
583
+ now = () => Date.now(),
584
+ setTimeoutFn = setTimeout,
585
+ clearTimeoutFn = clearTimeout
586
+ }) {
587
+ let lastWriteAt = now();
588
+ let lastRunAt = 0;
589
+ let running = false;
590
+ let disposed = false;
591
+ let idleTimer = null;
592
+ let sleepAbort = null;
593
+
594
+ function armIdleTimer() {
595
+ if (disposed || idleTimer) return;
596
+ if (config.sleepModeEnabled !== true) return;
597
+ const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
598
+ const delay = Math.max(0, idleMs - (now() - lastWriteAt)) + 1000;
599
+ idleTimer = setTimeoutFn(async () => {
600
+ idleTimer = null;
601
+ // Issue #187:false = 撞上 CD(或 run 失败)——此前这里直接丢弃,"CD 到期"
602
+ // 成了没有监听者的时刻,要等下一次写入才救回来。改为按剩余窗口重排。
603
+ const ran = await maybeSchedule();
604
+ if (!ran) armNextWindow();
605
+ }, delay);
606
+ idleTimer.unref?.();
607
+ }
608
+
609
+ // Issue #187:撞 CD / run 失败后的补挂表——按「剩余 CD / 剩余静默」里更晚的
610
+ // 到点时刻重排一次,回调里重复同样的判断所以不会空转。跑成了一轮就不重排:
611
+ // 安静的库没有要处理的新东西,触发权交还给下一次写入的 noteWrite。
612
+ function armNextWindow() {
613
+ if (disposed || idleTimer) return;
614
+ if (config.sleepModeEnabled !== true) return;
615
+ // lastRunAt === 0 表示从未跑过(此路径不该出现,防御性返回)。
616
+ if (lastRunAt <= 0) return;
617
+ const idleMs = (config.sleepIdleMinutes ?? 5) * 60000;
618
+ const cdMs = (config.sleepMinIntervalHours ?? 8) * 3600000;
619
+ const delay = Math.max(
620
+ lastRunAt + cdMs - now(),
621
+ lastWriteAt + idleMs - now(),
622
+ 0
623
+ ) + 1000;
624
+ idleTimer = setTimeoutFn(async () => {
625
+ idleTimer = null;
626
+ const ran = await maybeSchedule();
627
+ if (!ran) armNextWindow();
628
+ }, delay);
629
+ idleTimer.unref?.();
630
+ }
631
+
632
+ function shouldRun(at = now()) {
633
+ if (disposed || running) return false;
634
+ if (config.sleepModeEnabled !== true) return false;
635
+ if (at - lastWriteAt < (config.sleepIdleMinutes ?? 5) * 60000) return false;
636
+ // lastRunAt === 0 means never ran — the min-interval check must not block
637
+ // the very first cycle (a real run stamps a nonzero timestamp).
638
+ if (lastRunAt > 0 && at - lastRunAt < (config.sleepMinIntervalHours ?? 8) * 3600000) return false;
639
+ return true;
640
+ }
641
+
642
+ /** Called on writes: resets the idle clock and re-arms the fire timer. The
643
+ * pending timer is cleared first — a stale timer armed against the old idle
644
+ * window would otherwise fire early, fail shouldRun, and leave nothing armed
645
+ * for the next window (a missed trigger until the next write).
646
+ *
647
+ * While a sleep run is executing (running=true) the in-flight AbortController
648
+ * is NOT aborted: the run's own writes (demoteToSummary / setArchived ride
649
+ * the normal write-hook path) would otherwise self-abort the cycle. External
650
+ * activity during the run still resets the idle clock here, so no new cycle
651
+ * fires until the store is quiet again. */
652
+ function noteWrite() {
653
+ lastWriteAt = now();
654
+ if (!running && sleepAbort) {
655
+ sleepAbort.abort(); // user resumed activity — interrupt an idle run
656
+ }
657
+ if (idleTimer) {
658
+ clearTimeoutFn(idleTimer);
659
+ idleTimer = null;
660
+ }
661
+ armIdleTimer();
662
+ }
663
+
664
+ async function maybeSchedule() {
665
+ if (!shouldRun()) return false;
666
+ running = true;
667
+ const abort = new AbortController();
668
+ sleepAbort = abort;
669
+ try {
670
+ lastRunAt = now();
671
+ const result = await service.enqueue(() =>
672
+ onRun ? onRun(abort.signal) : Promise.resolve({ ok: true, skipped: true })
673
+ );
674
+ return !!(result && result.ok);
675
+ } catch (error) {
676
+ logger?.warn?.(`dsh-mneme sleep: run failed: ${error?.message ?? error}`);
677
+ return false;
678
+ } finally {
679
+ sleepAbort = null;
680
+ running = false;
681
+ }
682
+ }
683
+
684
+ async function dispose() {
685
+ disposed = true;
686
+ if (idleTimer) {
687
+ clearTimeoutFn(idleTimer);
688
+ idleTimer = null;
689
+ }
690
+ if (sleepAbort) {
691
+ sleepAbort.abort();
692
+ sleepAbort = null;
693
+ }
694
+ }
695
+
696
+ // Issue #187(同族缺陷):构造即挂表——重启后只要没发生过写入,此前永远没有
697
+ // 闹钟,安静多久都不会触发。lastWriteAt 已在构造时设为当前时刻,shouldRun 的
698
+ // 静默条件自然生效:重启后静默满 idleMinutes 才可能起跑。
699
+ armIdleTimer();
700
+
701
+ return { noteWrite, maybeSchedule, shouldRun, dispose };
702
+ }