@modusensus/dsh-mneme 0.8.14 → 0.8.16

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 (279) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +660 -654
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +691 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -151
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +275 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/DISTILL.md +162 -0
  12. package/docs/ENTITIES.md +245 -0
  13. package/docs/LOCAL_MODEL.md +222 -0
  14. package/docs/SEMANTIC.md +256 -0
  15. package/docs/SLEEP.md +164 -0
  16. package/docs/STORAGE.md +98 -0
  17. package/lib/api-standalone.js +656 -673
  18. package/lib/api.js +1605 -1433
  19. package/lib/bootstrap.js +211 -211
  20. package/lib/client.js +6354 -5296
  21. package/lib/commands.js +95 -95
  22. package/lib/config.js +947 -843
  23. package/lib/content-hash.js +54 -54
  24. package/lib/continuity.js +220 -220
  25. package/lib/document-index.js +94 -94
  26. package/lib/document.js +303 -303
  27. package/lib/dream/clustering.js +118 -118
  28. package/lib/dream/decisions.js +694 -674
  29. package/lib/dream/narratives.js +44 -44
  30. package/lib/dream/sleep.js +819 -819
  31. package/lib/dream.js +1503 -1501
  32. package/lib/embedding.js +177 -177
  33. package/lib/entities/extractor.js +252 -252
  34. package/lib/graph/anchoring.js +179 -179
  35. package/lib/guide.js +74 -74
  36. package/lib/heat.js +144 -144
  37. package/lib/hot-memory.js +108 -46
  38. package/lib/index.js +552 -503
  39. package/lib/inject.js +428 -450
  40. package/lib/lang.js +248 -229
  41. package/lib/local-embedder.js +358 -358
  42. package/lib/maintenance.js +162 -142
  43. package/lib/mirror.js +330 -330
  44. package/lib/organize.js +450 -450
  45. package/lib/peak-hours.js +117 -117
  46. package/lib/placement.js +13 -0
  47. package/lib/pre-inject-gate.js +340 -0
  48. package/lib/quality-filter.js +126 -126
  49. package/lib/recall-stats.js +190 -175
  50. package/lib/reclaim-http.js +150 -0
  51. package/lib/reranker.js +269 -269
  52. package/lib/runtime/adopt.js +176 -176
  53. package/lib/runtime/closure.js +172 -172
  54. package/lib/runtime/download.js +247 -247
  55. package/lib/runtime/layout.js +265 -265
  56. package/lib/runtime/loader.js +252 -252
  57. package/lib/runtime/model-fetch.js +361 -361
  58. package/lib/runtime/provision.js +237 -237
  59. package/lib/runtime/tarball.js +130 -130
  60. package/lib/runtime/verify.js +223 -204
  61. package/lib/safe-slice.js +18 -0
  62. package/lib/scope.js +146 -146
  63. package/lib/search/adaptive.js +60 -60
  64. package/lib/search/bm25.js +96 -96
  65. package/lib/semantic.js +229 -229
  66. package/lib/sensitive-scan.js +209 -209
  67. package/lib/serve.js +215 -215
  68. package/lib/service.js +2688 -2605
  69. package/lib/settings.js +528 -511
  70. package/lib/store.js +3196 -3007
  71. package/lib/summarize.js +1039 -856
  72. package/lib/tools.js +743 -737
  73. package/lib/vector-index.js +110 -110
  74. package/lib/version-check.js +122 -122
  75. package/lib/write-admission.js +402 -402
  76. package/locale/en.json +6 -6
  77. package/locale/zh.json +6 -6
  78. package/package.json +118 -118
  79. package/runtime-manifest.json +526 -526
  80. package/scripts/benchmark-embed.js +201 -201
  81. package/scripts/benchmark-recall.js +249 -249
  82. package/scripts/benchmark-rerank.js +166 -166
  83. package/scripts/build-runtime-manifest.mjs +224 -224
  84. package/scripts/changelog-prep.mjs +36 -36
  85. package/scripts/check-sync.js +42 -42
  86. package/scripts/e2e-dsh.js +220 -220
  87. package/scripts/mneme-runtime.mjs +277 -277
  88. package/scripts/stress-dsh.js +255 -255
  89. package/scripts/sync-lib.js +47 -47
  90. package/scripts/sync-test-badge.mjs +69 -69
  91. package/scripts/test-count-sync.mjs +44 -44
  92. package/src/api-standalone.js +656 -673
  93. package/src/api.js +1605 -1433
  94. package/src/bootstrap.js +211 -211
  95. package/src/commands.js +95 -95
  96. package/src/config.js +947 -843
  97. package/src/content-hash.js +54 -54
  98. package/src/continuity.js +220 -220
  99. package/src/document-index.js +94 -94
  100. package/src/document.js +303 -303
  101. package/src/dream/clustering.js +118 -118
  102. package/src/dream/decisions.js +694 -674
  103. package/src/dream/narratives.js +44 -44
  104. package/src/dream/sleep.js +819 -819
  105. package/src/dream.js +1503 -1501
  106. package/src/embedding.js +177 -177
  107. package/src/entities/extractor.js +252 -252
  108. package/src/graph/anchoring.js +179 -179
  109. package/src/guide.js +74 -74
  110. package/src/heat.js +144 -144
  111. package/src/hot-memory.js +108 -46
  112. package/src/index.js +552 -503
  113. package/src/inject.js +428 -450
  114. package/src/lang.js +248 -229
  115. package/src/local-embedder.js +358 -358
  116. package/src/maintenance.js +162 -142
  117. package/src/mirror.js +330 -330
  118. package/src/organize.js +450 -450
  119. package/src/peak-hours.js +117 -117
  120. package/src/placement.js +13 -0
  121. package/src/pre-inject-gate.js +340 -0
  122. package/src/quality-filter.js +126 -126
  123. package/src/recall-stats.js +190 -175
  124. package/src/reclaim-http.js +150 -0
  125. package/src/reranker.js +269 -269
  126. package/src/runtime/adopt.js +176 -176
  127. package/src/runtime/closure.js +172 -172
  128. package/src/runtime/download.js +247 -247
  129. package/src/runtime/layout.js +265 -265
  130. package/src/runtime/loader.js +252 -252
  131. package/src/runtime/model-fetch.js +361 -361
  132. package/src/runtime/provision.js +237 -237
  133. package/src/runtime/tarball.js +130 -130
  134. package/src/runtime/verify.js +223 -204
  135. package/src/safe-slice.js +18 -0
  136. package/src/scope.js +146 -146
  137. package/src/search/adaptive.js +60 -60
  138. package/src/search/bm25.js +96 -96
  139. package/src/semantic.js +229 -229
  140. package/src/sensitive-scan.js +209 -209
  141. package/src/serve.js +215 -215
  142. package/src/service.js +2688 -2605
  143. package/src/settings.js +528 -511
  144. package/src/store.js +3196 -3007
  145. package/src/summarize.js +1039 -856
  146. package/src/tools.js +743 -737
  147. package/src/vector-index.js +110 -110
  148. package/src/version-check.js +122 -122
  149. package/src/write-admission.js +402 -402
  150. package/test/adaptive-inject-budget.test.js +85 -85
  151. package/test/api-routes-gaps.test.js +899 -218
  152. package/test/api.test.js +1725 -1690
  153. package/test/audit.test.js +448 -448
  154. package/test/baseline-persist.test.js +248 -248
  155. package/test/benchmark.test.js +94 -94
  156. package/test/bootstrap.test.js +220 -220
  157. package/test/changelog-prep.test.js +60 -60
  158. package/test/client.test.js +1582 -1169
  159. package/test/clustering.test.js +100 -100
  160. package/test/commands.test.js +106 -106
  161. package/test/config.test.js +66 -66
  162. package/test/conflict-freeze.test.js +300 -300
  163. package/test/content-hash.test.js +204 -204
  164. package/test/continuity.test.js +333 -333
  165. package/test/contrast.test.js +314 -0
  166. package/test/document-dir.test.js +233 -233
  167. package/test/document.test.js +671 -671
  168. package/test/dream-archive-guardrail.test.js +116 -116
  169. package/test/dream-candidate-hybrid.test.js +281 -281
  170. package/test/dream-coverage-degrade.test.js +86 -86
  171. package/test/dream-failure-backoff.test.js +173 -173
  172. package/test/dream-merge-guardrail.test.js +219 -0
  173. package/test/dream-peak-hours.test.js +194 -194
  174. package/test/dream.test.js +1385 -1383
  175. package/test/embedding-ready.test.js +196 -196
  176. package/test/entities.test.js +627 -547
  177. package/test/entity-recall.test.js +179 -179
  178. package/test/epistemic.test.js +325 -325
  179. package/test/fnew-0112.test.js +311 -311
  180. package/test/fnew-03.test.js +422 -422
  181. package/test/graph-anchoring.test.js +184 -184
  182. package/test/graph-api.test.js +175 -175
  183. package/test/graph-inject-budget.test.js +103 -103
  184. package/test/graph-passive-confirm.test.js +91 -91
  185. package/test/graph-weight-evolution.test.js +104 -104
  186. package/test/heat.test.js +175 -175
  187. package/test/helpers/dream-mock.js +82 -82
  188. package/test/helpers/peer-worker.mjs +25 -25
  189. package/test/helpers/runtime-source.js +60 -60
  190. package/test/helpers/tar-builder.js +80 -80
  191. package/test/helpers/write-admission-samples.js +308 -308
  192. package/test/hot-memory.test.js +211 -145
  193. package/test/inject-content-cap.test.js +91 -91
  194. package/test/inject-first-round-bm25.test.js +89 -89
  195. package/test/inject-heat.test.js +77 -77
  196. package/test/inject-parent-gate.test.js +106 -106
  197. package/test/inject-pools.test.js +194 -194
  198. package/test/inject-recall.test.js +144 -105
  199. package/test/inject-rotation.test.js +161 -161
  200. package/test/inject.test.js +443 -420
  201. package/test/lang.test.js +87 -87
  202. package/test/lastrunat-persist.test.js +101 -101
  203. package/test/lib-smoke.test.js +96 -96
  204. package/test/llm-audit.test.js +696 -598
  205. package/test/llm-message-source.test.js +207 -207
  206. package/test/local-embedder.test.js +292 -292
  207. package/test/maintenance.test.js +501 -391
  208. package/test/mcp-stdio.test.js +385 -385
  209. package/test/mirror-dirty.test.js +424 -424
  210. package/test/mirror-edit-digest.test.js +187 -187
  211. package/test/mirror-generation.test.js +499 -499
  212. package/test/mirror-types.test.js +208 -208
  213. package/test/mirror.test.js +249 -249
  214. package/test/narrative-bars.test.js +162 -162
  215. package/test/organize.test.js +418 -418
  216. package/test/peer-blockers.test.js +193 -193
  217. package/test/placement.test.js +36 -0
  218. package/test/policy-epoch.test.js +259 -259
  219. package/test/pre-inject-gate.test.js +444 -0
  220. package/test/quality-filter.test.js +186 -186
  221. package/test/reasoning-effort.test.js +752 -752
  222. package/test/recall-anti-update.test.js +82 -82
  223. package/test/recall-evals.test.js +253 -253
  224. package/test/recall-layer.test.js +326 -326
  225. package/test/recall-stats.test.js +274 -189
  226. package/test/receipt-chain.test.js +451 -451
  227. package/test/reclaim-http.test.js +209 -0
  228. package/test/reflection.test.js +226 -226
  229. package/test/reindex-backfill.test.js +62 -62
  230. package/test/reranker-single-logit.test.js +73 -73
  231. package/test/reranker.test.js +197 -197
  232. package/test/resident-status.test.js +83 -83
  233. package/test/runtime-adopt.test.js +206 -206
  234. package/test/runtime-cli.test.js +89 -89
  235. package/test/runtime-closure.test.js +193 -193
  236. package/test/runtime-download.test.js +302 -302
  237. package/test/runtime-layout.test.js +163 -163
  238. package/test/runtime-loader.test.js +255 -255
  239. package/test/runtime-manifest.test.js +159 -159
  240. package/test/runtime-model-fetch.test.js +348 -348
  241. package/test/runtime-provision.test.js +101 -101
  242. package/test/runtime-tarball.test.js +81 -81
  243. package/test/runtime-verify.test.js +319 -279
  244. package/test/scope-candidates.test.js +239 -239
  245. package/test/scope-explicit.test.js +452 -452
  246. package/test/scope-inject-soft.test.js +106 -106
  247. package/test/scope-retrieval.test.js +197 -197
  248. package/test/scope-storage.test.js +255 -255
  249. package/test/scope-strict.test.js +367 -367
  250. package/test/search-fusion.test.js +90 -90
  251. package/test/semantic.test.js +124 -124
  252. package/test/sensitive-scan.test.js +207 -207
  253. package/test/serve-bin.test.js +121 -121
  254. package/test/serve.test.js +196 -196
  255. package/test/service-search.test.js +174 -174
  256. package/test/service.test.js +410 -405
  257. package/test/settings.test.js +269 -261
  258. package/test/skip-invalid-restore.test.js +262 -262
  259. package/test/sleep-action-set.test.js +422 -422
  260. package/test/sleep-heat.test.js +126 -126
  261. package/test/sleep-scheduler-rearm.test.js +89 -89
  262. package/test/sleep.test.js +527 -527
  263. package/test/standalone-api.test.js +751 -751
  264. package/test/store-vector-cache.test.js +98 -98
  265. package/test/store.test.js +504 -396
  266. package/test/stress.test.js +209 -209
  267. package/test/summarize-occurred-at.test.js +127 -0
  268. package/test/summarize-reasoning-effort.test.js +189 -189
  269. package/test/summarize.test.js +1639 -1465
  270. package/test/supersede-state-tracking.test.js +394 -0
  271. package/test/test-count-sync.test.js +60 -60
  272. package/test/tools-dto-schema-matrix.test.js +325 -325
  273. package/test/tools-memory-get-schema.test.js +65 -65
  274. package/test/tools.test.js +428 -374
  275. package/test/updated-at-semantics.test.js +113 -113
  276. package/test/vector-index.test.js +221 -221
  277. package/test/version-check.test.js +152 -152
  278. package/test/webServer-optional.test.js +82 -82
  279. package/test/write-admission.test.js +668 -668
package/src/dream.js CHANGED
@@ -1,1501 +1,1503 @@
1
- import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
- import { clusterMemories, findPotentialConflicts, cosineSimilarity } from "./dream/clustering.js";
3
- import { clusterByTag, intersectEvidence } from "./dream/narratives.js";
4
- import { scopeKeyOf } from "./scope.js";
5
- // Issue #239(第 4 项)镜像到巩固:错峰时段解析与「最近的高峰结束时刻」从独立的
6
- // 零依赖模块 peak-hours.js 取(该模块从 summarize.js 抽出,PR #320 review)——
7
- // 不另写一份解析器,两份实现漂移会让「同一个时段串在两处行为不同」,那比没有
8
- // 这个功能更糟。此前直接 import summarize.js,#316 后 summarize 反向依赖 dream
9
- // (withEffortFallback 复用),会成真循环,故抽模块。
10
- import { isInPeakWindow, nextOffPeakAt } from "./peak-hours.js";
11
- import { createHash, randomUUID } from "node:crypto";
12
- import { STR, langOf } from "./lang.js";
13
- export { validateDecisions, applyDecisions, withEffortFallback, describeStreamFailure, resolveDreamEffort, resolveRoute };
14
-
15
- // Extract the first JSON array from LLM output, tolerating markdown fences,
16
- // leading/trailing prose, and common wrapper noise. Returns an array or null.
17
- function extractJsonArray(text) {
18
- if (typeof text !== "string" || text.trim().length === 0) return null;
19
-
20
- // 1. Strip markdown code fences (```json ... ``` or ``` ... ```).
21
- let cleaned = text.replace(/```(?:json)?\s*([\s\S]*?)```/gi, "$1");
22
- cleaned = cleaned.trim();
23
-
24
- // 2. Find the first '[' and the matching last ']' that yields valid JSON.
25
- const start = cleaned.indexOf("[");
26
- if (start === -1) return null;
27
- for (let end = cleaned.lastIndexOf("]"); end > start; end = cleaned.lastIndexOf("]", end - 1)) {
28
- const candidate = cleaned.slice(start, end + 1);
29
- try {
30
- return JSON.parse(candidate);
31
- } catch {
32
- // Light repair: remove trailing commas before ] or }.
33
- try {
34
- const repaired = candidate.replace(/,(\s*[}\]])/g, "$1");
35
- return JSON.parse(repaired);
36
- } catch {
37
- // keep searching backwards
38
- }
39
- }
40
- }
41
-
42
- // 3. Fallback: a broader regex extraction.
43
- try {
44
- const match = cleaned.match(/\[[\s\S]*\]/);
45
- if (match) return JSON.parse(match[0]);
46
- } catch {
47
- // fall through
48
- }
49
- return null;
50
- }
51
- function totalChars(memories) {
52
- return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
53
- }
54
-
55
- // 阈值口径的唯一实现:活跃记忆(未归档、非 summary/document)的条数与正文字符数。
56
- // 触发判定(shouldTrigger)与「成功轮把基线落库」(runDream 的 finish)都走这里——
57
- // 两处若各写一份过滤条件,重启播种读到的基线就会和运行期判定口径漂移(一个把
58
- // document 算进去、一个不算),阈值随之失真,且这种漂移只会在重启后才显形。
59
- function activeStoreSize(service) {
60
- const memories = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
61
- return { count: memories.length, chars: totalChars(memories) };
62
- }
63
-
64
- // 基线的唯一合法形状:两个非负整数;其余(缺字段、负数、非整数、整个对象缺失)
65
- // 一律视为「没有基线」→ 调用方退回 {0,0}。播种值来自持久化列,可能是老库的 NULL
66
- // 或手工改坏的库,判定必须比调用点更严格,而不是相信数据库里存的一定合法。
67
- function toBaseline(raw) {
68
- if (!raw || typeof raw !== "object") return null;
69
- const count = Number.isInteger(raw.count) && raw.count >= 0 ? raw.count : null;
70
- const chars = Number.isInteger(raw.chars) && raw.chars >= 0 ? raw.chars : null;
71
- if (count === null || chars === null) return null;
72
- return { count, chars };
73
- }
74
-
75
- // ---------------------------------------------------------------- audit
76
-
77
- /**
78
- * Canonical digest of the consolidation input snapshot. Built from stable
79
- * fields sorted by id, so identical inputs always yield the same hash — the
80
- * basis for replaying/verifying a recorded decision (receipt check).
81
- */
82
- export function hashSnapshot(memories) {
83
- const canon = memories
84
- .map((m) => [m.id, m.type, m.title, m.content, m.importance, m.updated_at])
85
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
86
- .map((parts) => parts.map((p) => String(p ?? "")).join("\u0001"))
87
- .join("\u0002");
88
- return createHash("sha256").update(canon).digest("hex");
89
- }
90
-
91
- /**
92
- * Compact machine-verifiable receipt for one autoDream run. Format:
93
- * dsh-mneme:run:<runId>:<status>:<snapshotHash(12)>:<inputCount>:<applied>:<summaryFlag>
94
- * Enough to correlate a run with its persisted audit row and to spot silent
95
- * drift (same snapshot hash + same decisions must reproduce the same outcome).
96
- */
97
- export function buildReceipt({ runId, status, snapshotHash, inputCount, applied, summaryStored }) {
98
- return `dsh-mneme:run:${runId}:${status}:${snapshotHash.slice(0, 12)}:${inputCount}:${applied}:${summaryStored ? 1 : 0}`;
99
- }
100
-
101
- /**
102
- * Parse a receipt back into fields; returns undefined for malformed input.
103
- */
104
- export function parseReceipt(receipt) {
105
- if (typeof receipt !== "string") return undefined;
106
- const parts = receipt.split(":");
107
- if (parts.length !== 8 || parts[0] !== "dsh-mneme" || parts[1] !== "run") return undefined;
108
- const [, , runId, status, snapshotHash, inputCount, applied, summaryStored] = parts;
109
- // reconcile = decisions validated but one or more did not commit (CAS
110
- // conflict / transaction rollback) — the store diverges from the decision
111
- // list and the run must be reconciled, never reported as a fake ok.
112
- if (!runId || !/^(ok|noop|degraded|reconcile|failed)$/.test(status)) return undefined;
113
- const count = Number(inputCount);
114
- const appliedN = Number(applied);
115
- if (!Number.isInteger(count) || !Number.isInteger(appliedN)) return undefined;
116
- return { runId, status, snapshotHash, inputCount: count, applied: appliedN, summaryStored: summaryStored === "1" };
117
- }
118
-
119
- /**
120
- * Derive the per-id disposition (keep / merge-keep / merge-archived /
121
- * archived / conflict-winner / conflict-archived) from a validated decision
122
- * list. Stored in the audit row so a run can be replayed without re-running
123
- * the LLM.
124
- */
125
- export function buildOutcome(decisions) {
126
- const byId = {};
127
- for (const d of decisions ?? []) {
128
- if (d.action === "keep") {
129
- for (const id of d.ids) byId[id] = "keep";
130
- } else if (d.action === "archive") {
131
- for (const id of d.ids) byId[id] = "archived";
132
- } else if (d.action === "merge") {
133
- for (const id of d.ids) byId[id] = id === d.keepSource ? "merge-keep" : "merge-archived";
134
- } else if (d.action === "conflict") {
135
- byId[d.winner] = "conflict-winner";
136
- byId[d.loser] = "conflict-archived";
137
- } else if (d.action === "update") {
138
- for (const id of d.ids) byId[id] = "updated";
139
- } else if (d.action === "supersede") {
140
- // Issue #126 review(Copilot):新动作此前在 outcome.byId 里没有 disposition,
141
- // 审计行产了 receipt 却看不出这些目标被如何处置。
142
- byId[d.winner] = "supersede-winner";
143
- byId[d.loser] = "superseded-archived";
144
- } else if (d.action === "differentiate") {
145
- for (const id of d.ids ?? []) byId[id] = "differentiated";
146
- }
147
- }
148
- return { byId };
149
- }
150
-
151
- /**
152
- * Content-addressed digest of the memories a verdict was decided against
153
- * (id + title + content + importance), sorted by id so identical inputs always
154
- * hash the same. This is the per-record "判定依据" fingerprint: a receipt whose
155
- * digest cannot be reproduced from the involved memories is a bare claim, and a
156
- * digest match with a divergent outcome pinpoints drift to the exact record.
157
- */
158
- export function hashDecisionInput(memories) {
159
- const canon = (memories ?? [])
160
- .map((m) => [m.id, m.title, m.content, m.importance])
161
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
162
- .map((p) => p.map((x) => String(x ?? "")).join(""))
163
- .join("");
164
- return createHash("sha256").update(canon).digest("hex");
165
- }
166
-
167
- /**
168
- * Build the per-record receipts for a run's actually-committed mutable verdicts
169
- * (merge/conflict/update) — one row per verdict in the receipt_chain. Inputs
170
- * are drawn from the run snapshot (what the LLM actually arbitrated against),
171
- * and the idempotency counters count_before → count_after come from the
172
- * committed sub-step, so replaying the same decision must reproduce the same
173
- * numbers. verdict starts "live"; a later policy_epoch upgrade will batch-mark
174
- * older verdicts "historical" (a receipt_chain rewrite driven by the store's
175
- * getLatestPolicyEpoch — out of scope for this pass), while "revoked" is
176
- * reserved for verdicts later overturned by an explicit human decision.
177
- */
178
- function buildRecordReceipts({ runId, committed, snapshot, policyEpoch }) {
179
- const at = (id) => snapshot?.get?.(id);
180
- const receipts = [];
181
- for (const c of committed ?? []) {
182
- const base = {
183
- run_id: runId,
184
- verdict: "live",
185
- count_before: c.count_before,
186
- count_after: c.count_after,
187
- policy_epoch: policyEpoch,
188
- created_at: new Date().toISOString()
189
- };
190
- if (c.action === "merge") {
191
- receipts.push({
192
- ...base,
193
- receipt_id: randomUUID(),
194
- record_id: c.keepSource,
195
- kind: "merge",
196
- input_digest: hashDecisionInput((c.ids ?? []).map(at).filter(Boolean)),
197
- keep_source: c.keepSource,
198
- sources: c.ids
199
- });
200
- } else if (c.action === "conflict") {
201
- receipts.push({
202
- ...base,
203
- receipt_id: randomUUID(),
204
- record_id: c.winner,
205
- kind: "conflict",
206
- input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
207
- winner_id: c.winner,
208
- loser_id: c.loser
209
- });
210
- } else if (c.action === "update") {
211
- receipts.push({
212
- ...base,
213
- receipt_id: randomUUID(),
214
- record_id: c.ids[0],
215
- kind: "update",
216
- input_digest: hashDecisionInput([at(c.ids[0])].filter(Boolean))
217
- });
218
- } else if (c.action === "supersede") {
219
- // Issue #126:演进型裁决——record 记被取代的一方。winner 正文未被改动,
220
- // 不需要自己的 receipt;loser 归档并追加"已被取代"注记。
221
- receipts.push({
222
- ...base,
223
- receipt_id: randomUUID(),
224
- record_id: c.loser,
225
- kind: "supersede",
226
- input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
227
- winner_id: c.winner,
228
- loser_id: c.loser
229
- });
230
- } else if (c.action === "differentiate") {
231
- // Issue #126:互补型裁决——两条都保留,各记一条 receipt。数量没有变化,
232
- // count_before/after 固定 1/1(该记录只是被追加了差异注记)。
233
- for (const id of c.ids ?? []) {
234
- receipts.push({
235
- ...base,
236
- receipt_id: randomUUID(),
237
- record_id: id,
238
- kind: "differentiate",
239
- input_digest: hashDecisionInput([at(id)].filter(Boolean)),
240
- count_before: 1,
241
- count_after: 1
242
- });
243
- }
244
- }
245
- }
246
- return receipts;
247
- }
248
-
249
- /**
250
- * Consume an LLM stream and return the accumulated text. Direct text-delta
251
- * accumulation covers both the real protocol ({type:"text-delta", index, text})
252
- * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
253
- * surfaces as undefined. The caller decides how to treat an empty result.
254
- * `onUsage` (optional, Bug8) receives any usage chunk for token accounting.
255
- */
256
- async function streamText(ctx, options, onUsage, onStreamError) {
257
- let text = "";
258
- for await (const chunk of ctx.llm.stream(options)) {
259
- if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
260
- // DSH 的 StreamChunk 契约把用量嵌在 chunk.usage(TokenUsage:inputTokens /
261
- // outputTokens / …),chunk 顶层没有 token 字段——把整个 chunk 当用量对象交给
262
- // reporter,input/output 恒为 undefined,审计行落 0(v0.8.4 实测:7 天 49 次
263
- // success 调用 token 全 0,面板「LLM 消耗」长期显示 0)。`?? chunk` 兜底把用量
264
- // 平铺在顶层的替身。
265
- if (chunk.type === "usage" && typeof onUsage === "function") onUsage(chunk.usage ?? chunk);
266
- if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
267
- // dsh-llm rc.1 turns adapter-stage failures (unknown provider route,
268
- // UNSUPPORTED_REASONING_EFFORT from resolveCallWithInfo, …) into a
269
- // terminal finish chunk instead of a throw — the cause rides in
270
- // chunk.reason.failure {message, code}. Surface it, never swallow it.
271
- if (typeof onStreamError === "function") {
272
- try { onStreamError(chunk.reason); } catch { /* diagnostics only */ }
273
- }
274
- return undefined;
275
- }
276
- }
277
- return text;
278
- }
279
-
280
- /** One-line human-readable cause from a finish-chunk failure reason. */
281
- function describeStreamFailure(reason) {
282
- const failure = reason?.failure ?? reason ?? {};
283
- const code = failure.code ? String(failure.code) : "";
284
- const message = String(failure.message ?? failure.error ?? "");
285
- if (code && message) return message.includes(code) ? message : `${code}: ${message}`;
286
- return code || message;
287
- }
288
-
289
- /**
290
- * Bug8: wrap a background LLM call so its token/time/status are recorded in the
291
- * llm_audit_logs table. Best-effort bookkeeping: a failure to WRITE the audit
292
- * row is swallowed (never blocks the LLM call), while a failure of the call
293
- * itself is captured as status='error' and re-thrown so the caller keeps its
294
- * existing error path. `spec` carries the static metadata (trigger_source,
295
- * operation_type, model_id, related_memory_ids); `body(reportUsage)` performs
296
- * the actual stream consumption and is handed a usage reporter for the chunks.
297
- */
298
- async function runAuditedLlm(ctx, service, config, spec, body) {
299
- const audit = config?.llmAudit;
300
- if (audit?.enabled === false || typeof service?.saveLlmAudit !== "function") return body(() => {});
301
- const startedAt = Date.now();
302
- const timestamp = new Date(startedAt).toISOString();
303
- let inputTokens = 0;
304
- let outputTokens = 0;
305
- let status = "success";
306
- let errorMessage = null;
307
- let result;
308
- try {
309
- result = await body((usage) => {
310
- if (!usage) return;
311
- const i = usage.input_tokens ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens;
312
- const o = usage.output_tokens ?? usage.outputTokens ?? usage.completion_tokens ?? usage.completionTokens;
313
- if (Number.isFinite(i)) inputTokens = i;
314
- if (Number.isFinite(o)) outputTokens = o;
315
- });
316
- if (result === undefined) {
317
- // stream aborted/errored: the caller treats undefined as a failed run;
318
- // record it as error here so the audit shows the truth. spec.streamError
319
- // (a getter) lets the caller attach the finish-chunk cause so the audit
320
- // row names it instead of a bare "aborted".
321
- status = "error";
322
- const streamErr = typeof spec.streamError === "function" ? String(spec.streamError() ?? "") : "";
323
- errorMessage = errorMessage ?? (streamErr ? `llm stream aborted or errored (${streamErr})` : "llm stream aborted or errored");
324
- } else if (typeof spec.auditError === "function") {
325
- // A stream that returned text but yields nothing usable is still a
326
- // failed call — record it as error, not the default success, so the
327
- // audit no longer contradicts a failed run (dream "no json array").
328
- const message = spec.auditError(result);
329
- if (message) {
330
- status = "error";
331
- errorMessage = message;
332
- }
333
- }
334
- return result;
335
- } catch (error) {
336
- status = "error";
337
- errorMessage = String(error?.message ?? error);
338
- throw error;
339
- } finally {
340
- try {
341
- service.saveLlmAudit({
342
- timestamp,
343
- trigger_source: spec.triggerSource,
344
- operation_type: spec.operationType,
345
- model_id: spec.modelId,
346
- input_tokens: inputTokens,
347
- output_tokens: outputTokens,
348
- total_tokens: inputTokens + outputTokens,
349
- cost_usd: 0,
350
- duration_ms: Date.now() - startedAt,
351
- status,
352
- error_message: errorMessage,
353
- related_memory_ids: spec.relatedMemoryIds ?? []
354
- });
355
- } catch (auditError) {
356
- ctx.logger?.warn?.(`dsh-mneme: llm audit write failed: ${String(auditError)}`);
357
- }
358
- }
359
- }
360
-
361
- /**
362
- * Reasoning-effort rejection fallback (v0.8.1): a configured dreamReasoningEffort
363
- * / sleepReasoningEffort may be rejected by the provider (volcano-engine returns
364
- * UNSUPPORTED_REASONING_EFFORT for values it does not accept — "off" is known
365
- * rejected there). When that happens, retry once WITHOUT the reasoning field
366
- * instead of hard-failing the run, so effort config is safe to experiment with:
367
- * accepted → reasoning capped; rejected → provider default (old behavior),
368
- * logged so the rejection is observable.
369
- */
370
- // Issue #315:effort 拒收判别式的单一来源。summarize 的流失败以 aborted 结果
371
- // 返回,需在折叠成 undefined 前用同一甄别(各处手写会漂移)。
372
- export const EFFORT_REJECT_RE = /reasoning[\s_]*effort|UNSUPPORTED_REASONING_EFFORT/i;
373
- async function withEffortFallback(ctx, effort, attempt, fallback, getStreamError) {
374
- if (!effort || effort === "none") return attempt();
375
- try {
376
- const result = await attempt();
377
- if (result === undefined) {
378
- // dsh-llm rc.1 streams a provider effort-rejection as a terminal error
379
- // finish chunk (adapterStream catches everything, never throws) — match
380
- // on the chunk's failure reason here or the retry below is dead code
381
- // for the stream path.
382
- const reason = String(getStreamError?.() ?? "");
383
- if (EFFORT_REJECT_RE.test(reason)) {
384
- ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected via stream (${reason}); retrying without it`);
385
- return fallback();
386
- }
387
- }
388
- return result;
389
- } catch (error) {
390
- // dispose/取消中止直接放行,绝不能被误判成 effort 拒收而触发 fallback
391
- //(取消后重打一次不带 effort 的调用是浪费,且可能掩盖真实的取消意图)。
392
- if (error?.name === "AbortError") throw error;
393
- const message = String(error?.message ?? error);
394
- // matches both "reasoning effort" (natural language) and the bare
395
- // "UNSUPPORTED_REASONING_EFFORT" error code (underscore).
396
- if (!EFFORT_REJECT_RE.test(message)) throw error;
397
- ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected (${message}); retrying without it`);
398
- return fallback();
399
- }
400
- }
401
-
402
- /** 向量索引同步(总览与叙述条共用):fail-safe,失败只 warn 不反噬主流程。 */
403
- async function reEmbedMemory(semantic, memory, logger) {
404
- if (!semantic?.embedder || !semantic?.vectorIndex || !memory) return;
405
- try {
406
- const v = await semantic.embedder.embedSingle([memory.title, memory.content].filter(Boolean).join("\n"));
407
- if (v?.length) semantic.vectorIndex.saveEmbedding(memory.id, v);
408
- if (semantic.embedder.modelHash) semantic.vectorIndex.markModel?.(semantic.embedder.modelHash, semantic.embedder.dimension);
409
- } catch (error) {
410
- logger?.warn?.(`dsh-mneme dream: re-embed failed: ${String(error)}`);
411
- }
412
- }
413
-
414
- /**
415
- * 叙述条阶段(#164 对齐,opt-in dreamNarrativeEnabled):共享 tag 主题聚类 →
416
- * 单次 LLM 调用按簇合成叙述 → 证据求交(防捏造,dream/narratives.js 纯函数)
417
- * → saveWithDedupe(source="narrative", _overwrite) 落库。按需检索不常驻注入。
418
- * 任何失败降级为 0 条,绝不反噬 dream 主流程。
419
- */
420
- async function generateNarratives({ ctx, service, config, route, language, effort, semantic, logger }) {
421
- const inputs = service.all().filter((m) => !m.archived && !m.forgotten && m.type !== "summary" && m.type !== "document");
422
- const clusters = clusterByTag(inputs, { minCluster: config.dreamNarrativeMinCluster ?? 3 });
423
- if (!clusters.length) return 0;
424
-
425
- const listing = clusters
426
- .map(({ tag, members }) =>
427
- [`# ${tag}`, ...members.map((m) => `- id=${m.id} | title=${m.title} | ${m.content}`)].join("\n"))
428
- .join("\n\n");
429
- let streamFailure = "";
430
- const runNarratives = (withEffort) => {
431
- streamFailure = "";
432
- return runAuditedLlm(ctx, service, config, {
433
- triggerSource: "autoDream",
434
- operationType: "dream_narrative",
435
- modelId: `${route.provider}:${route.model}`,
436
- relatedMemoryIds: clusters.flatMap((c) => c.members.map((m) => m.id)),
437
- streamError: () => streamFailure
438
- }, (reportUsage) => streamText(ctx, {
439
- provider: route.provider,
440
- model: route.model,
441
- purpose: "compaction",
442
- maxTokens: config.dreamMaxTokens ?? 2048,
443
- ...(withEffort && effort ? { reasoningEffort: effort } : {}),
444
- messages: [
445
- { role: "system", content: [{ type: "text", text: STR.prompts.narrative[language] }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
446
- { role: "user", content: [{ type: "text", text: listing }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
447
- ]
448
- }, reportUsage, (reason) => { streamFailure = describeStreamFailure(reason); }));
449
- };
450
- const text = await withEffortFallback(ctx, effort, () => runNarratives(true), () => runNarratives(false), () => streamFailure);
451
-
452
- const entries = extractJsonArray(text);
453
- if (!Array.isArray(entries)) return 0;
454
- const clusterByOfferedTag = new Map(clusters.map((c) => [c.tag, c]));
455
- const now = new Date().toISOString();
456
- let stored = 0;
457
- for (const entry of entries) {
458
- if (!entry || typeof entry !== "object") continue;
459
- const cluster = clusterByOfferedTag.get(typeof entry.tag === "string" ? entry.tag : "");
460
- const content = String(entry.content ?? "").trim();
461
- if (!cluster || !content) continue; // 未提供的 tag / 空叙述 → 跳过
462
- const evidenceIds = intersectEvidence(entry.evidence, cluster.members);
463
- const { memory } = service.saveWithDedupe({
464
- type: "summary",
465
- title: STR.narrativeTitle[language](cluster.tag),
466
- content,
467
- importance: 3,
468
- tags: [cluster.tag],
469
- source: "narrative",
470
- evidence: evidenceIds.map((id) => ({ memory_id: id, op: "support", at: now })),
471
- _overwrite: true
472
- });
473
- if (!memory) continue;
474
- stored++;
475
- // 叙述条按需可检索:向量索引同步(与总览共用 reEmbedMemory,fail-safe)。
476
- await reEmbedMemory(semantic, memory, logger);
477
- }
478
- return stored;
479
- }
480
-
481
- /**
482
- * Resolve the reasoning effort to actually send for a dream/sleep route.
483
- *
484
- * Reasoning-effort config that the provider does not accept trips the harness's
485
- * UNSUPPORTED_REASONING_EFFORT, and the defaultEffort trap makes retrying
486
- * "without the field" useless: the harness substitutes `reasoning.defaultEffort`,
487
- * which may itself be unsupported (DSH Desktop volcano-engine adapter declares
488
- * defaultEffort=low that its model rejects). So instead of blind retries, ask
489
- * the harness for the model's declared capability and pick a value that is
490
- * actually accepted — or omit the field entirely when the model declares no
491
- * reasoning capability at all.
492
- *
493
- * Unset vs explicit 'none' (Issue #135 建议 4/5): these are different intents.
494
- * Explicit 'none' = the user asked to omit the field (provider default
495
- * applies). Unset is the out-of-the-box state — dream/sleep calls must produce
496
- * JSON, and omission lets the harness substitute the model's defaultEffort
497
- * (thinking-type models often default to high), which drains the token budget
498
- * and returns an empty body. So unset resolves to the LOWEST effort the model
499
- * declares instead of omitting; when the capability query is unavailable the
500
- * field stays omitted (fail-safe, retry guard unchanged).
501
- *
502
- * @returns a supported effort id, or null when no effort should be sent, or the
503
- * configured value unchanged when the capability query is unavailable.
504
- */
505
-
506
- // 常识档位排序(越靠前推理开销越低);未知档位排最后(宁可交给显式配置)。
507
- const EFFORT_RANK = { minimal: 0, off: 0, low: 1, medium: 2, high: 3, max: 4 };
508
-
509
- function lowestSupportedEffort(reasoning) {
510
- const ids = (reasoning?.efforts ?? []).map((e) => e?.id).filter(Boolean);
511
- if (ids.length === 0) return null;
512
- return [...ids].sort((a, b) => (EFFORT_RANK[a] ?? 99) - (EFFORT_RANK[b] ?? 99))[0];
513
- }
514
-
515
- async function resolveDreamEffort(ctx, route, configuredEffort, logger) {
516
- // 显式 'none':用户要求省略字段(服务商自带默认生效),照旧。
517
- if (configuredEffort === "none") return null;
518
- if (!configuredEffort) {
519
- // 未配置(开箱默认):取模型声明的最低档,避免 defaultEffort 顶上(建议 4/5)。
520
- if (typeof ctx?.llm?.resolveModelInfo !== "function") return null;
521
- try {
522
- const info = await ctx.llm.resolveModelInfo(route.provider, route.model);
523
- const reasoning = info?.reasoning;
524
- if (!reasoning) return null; // 无推理声明:省略即安全(无 defaultEffort 可顶上)
525
- const lowest = lowestSupportedEffort(reasoning);
526
- if (!lowest) return null;
527
- logger?.info?.(`dsh-mneme dream: no reasoningEffort configured for ${route.provider}:${route.model}; using lowest supported "${lowest}" instead of the model default "${reasoning.defaultEffort ?? "n/a"}"`);
528
- return lowest;
529
- } catch (error) {
530
- // 能力查询失败:省略字段(fail-safe),withEffortFallback 照旧兜底。
531
- logger?.warn?.(`dsh-mneme dream: resolveModelInfo failed (${String(error?.message ?? error)}); omitting reasoningEffort`);
532
- return null;
533
- }
534
- }
535
- // Capability query unavailable (older harness / minimal mocks): forward the
536
- // configured value as before — absence of the API proves nothing about the
537
- // model, and withEffortFallback still guards against rejection.
538
- if (typeof ctx?.llm?.resolveModelInfo !== "function") return configuredEffort;
539
- try {
540
- const info = await ctx.llm.resolveModelInfo(route.provider, route.model);
541
- const reasoning = info?.reasoning;
542
- if (!reasoning) {
543
- // Model declares no reasoning capability: the harness rejects ANY
544
- // explicit effort for such a model, and omitting the field is safe
545
- // (no reasoning capability → no defaultEffort substitution).
546
- logger?.warn?.(`dsh-mneme dream: model ${route.provider}:${route.model} declares no reasoning capability; ignoring configured effort "${configuredEffort}"`);
547
- return null;
548
- }
549
- const supported = reasoning.efforts?.map((effort) => effort.id) ?? [];
550
- if (supported.includes(configuredEffort)) return configuredEffort;
551
- // Configured effort unsupported → pick defaultEffort if it is supported,
552
- // else the first declared effort, so the run never trips
553
- // UNSUPPORTED_REASONING_EFFORT (nor the defaultEffort trap: we always
554
- // pass an explicit value, so the harness never falls back to a poison
555
- // default).
556
- const picked = reasoning.defaultEffort && supported.includes(reasoning.defaultEffort)
557
- ? reasoning.defaultEffort
558
- : supported[0];
559
- if (picked) {
560
- logger?.warn?.(`dsh-mneme dream: model ${route.provider}:${route.model} does not support effort "${configuredEffort}" (supported: ${supported.join(", ")}); using "${picked}"`);
561
- return picked;
562
- }
563
- return null;
564
- } catch (error) {
565
- // Capability query failed — forward the configured value; withEffortFallback
566
- // still retries on rejection as before.
567
- logger?.warn?.(`dsh-mneme dream: resolveModelInfo failed (${String(error?.message ?? error)}); forwarding effort as configured`);
568
- return configuredEffort;
569
- }
570
- }
571
-
572
- /**
573
- * Resolve the LLM route (Issue #25): an explicit plugin config
574
- * (dreamProvider/dreamModel) is the user's declared override and wins; the
575
- * agent default model (deployment) is only a fallback when no config route is
576
- * set. In a standard DSH install agentDefaultModel always resolves, so without
577
- * this ordering the config route would be dead code and dreamProvider/dreamModel
578
- * could never take effect (v0.7.11 regressed this; README §config documents
579
- * config-first). Falls through to undefined when no route exists — runDream
580
- * then fails safe. A config→default switch is logged so it is observable.
581
- */
582
- function resolveRoute(ctx, config, logger) {
583
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
584
- try {
585
- const sel = ctx.agentDefaultModel?.currentSelection?.();
586
- if (sel?.provider && sel?.model) {
587
- logger?.info?.("dsh-mneme dream: no dreamProvider/dreamModel config, falling back to agent default");
588
- return { provider: sel.provider, model: sel.model };
589
- }
590
- logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, no config route either");
591
- } catch (error) {
592
- logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed: ${String(error)}`);
593
- }
594
- return undefined;
595
- }
596
-
597
- // ------------------------------------------------------- semantic enhancement
598
- // Best-effort: any failure here degrades to plain consolidation. The dream
599
- // path must never be broken by an unavailable embedder/index.
600
-
601
- /** Backfill + return vectors for every memory; null when impossible. */
602
- async function collectVectors(memories, semantic) {
603
- const { embedder, vectorIndex } = semantic;
604
- if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return null;
605
- const vectors = new Array(memories.length);
606
- const missing = [];
607
- for (let i = 0; i < memories.length; i++) {
608
- const cached = vectorIndex.getEmbedding?.(memories[i].id);
609
- if (cached) vectors[i] = cached;
610
- else missing.push(i);
611
- }
612
- if (missing.length) {
613
- const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
614
- const rows = await embedder.embed(texts);
615
- missing.forEach((mi, j) => {
616
- if (rows[j]?.length) {
617
- vectors[mi] = rows[j];
618
- vectorIndex.saveEmbedding(memories[mi].id, rows[j]);
619
- }
620
- });
621
- }
622
- return vectors.some((v) => !v) ? null : vectors;
623
- }
624
-
625
- /**
626
- * Issue #125:把高相似对聚成**连通分量组**——一个簇 = 一个候选单元。直接按对展开
627
- * 会把同一簇拆成互相抢占的多个决策(校验器有 one-claim 规则),成组才是正确粒度
628
- * (与 sleep 冲突阶段的贪心"每记忆每轮最多进一对"同理)。
629
- * 组内最小相似度用于组间排序:最该处理的簇先入选。
630
- */
631
- function similarityGroups(pairs) {
632
- const parent = new Map();
633
- const find = (x) => {
634
- let root = x;
635
- while (parent.get(root) !== root) root = parent.get(root);
636
- return root;
637
- };
638
- for (const p of pairs) {
639
- if (!parent.has(p.a.id)) parent.set(p.a.id, p.a.id);
640
- if (!parent.has(p.b.id)) parent.set(p.b.id, p.b.id);
641
- const ra = find(p.a.id);
642
- const rb = find(p.b.id);
643
- if (ra !== rb) parent.set(ra, rb);
644
- }
645
- const byRoot = new Map();
646
- for (const p of pairs) {
647
- for (const m of [p.a, p.b]) {
648
- const root = find(m.id);
649
- if (!byRoot.has(root)) byRoot.set(root, new Map());
650
- byRoot.get(root).set(m.id, m);
651
- }
652
- }
653
- return [...byRoot.values()].map((members) => {
654
- const list = [...members.values()];
655
- const ids = new Set(list.map((m) => m.id));
656
- let minSim = 1;
657
- for (const p of pairs) {
658
- if (ids.has(p.a.id) && ids.has(p.b.id)) minSim = Math.min(minSim, p.similarity);
659
- }
660
- return { members: list, minSim };
661
- });
662
- }
663
-
664
- /**
665
- * Issue #125:为候选构造收集向量。与 collectVectors 的差别是**允许部分缺失**——
666
- * 全量库只要有几条嵌入失败就整场返回 null,会让 hybrid 在真实库上几乎永远回落;
667
- * 拿不到向量的条目只是不参与比较(cosineSimilarity 对非数组返回 0,不会误判)。
668
- */
669
- async function collectCandidateVectors(memories, semantic, logger) {
670
- const { embedder, vectorIndex } = semantic;
671
- const vectors = new Array(memories.length);
672
- const missing = [];
673
- for (let i = 0; i < memories.length; i++) {
674
- const cached = vectorIndex.getEmbedding?.(memories[i].id);
675
- if (cached) vectors[i] = cached;
676
- else missing.push(i);
677
- }
678
- if (missing.length) {
679
- try {
680
- const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
681
- const rows = await embedder.embed(texts);
682
- missing.forEach((mi, j) => {
683
- if (rows[j]?.length) {
684
- vectors[mi] = rows[j];
685
- vectorIndex.saveEmbedding?.(memories[mi].id, rows[j]);
686
- }
687
- });
688
- } catch (error) {
689
- logger?.warn?.(`[dsh-mneme] dream hybrid vector backfill failed: ${String(error)}`);
690
- }
691
- }
692
- return vectors;
693
- }
694
-
695
- /**
696
- * Issue #125:hybrid 候选成员,按"组内最小相似度"降序展平(高价值簇排前面,
697
- * 受上限截断时先入选)。同类型比较沿用 findPotentialConflicts;仅当
698
- * allowCrossTypeMerge 显式开启时再补跨类型高相似对。
699
- * 任何失败都返回空数组——调用方回落纯窗口,dream 路径绝不因向量层而失败。
700
- */
701
- async function hybridCandidateMembers(allMemories, config, semantic, logger) {
702
- try {
703
- const vectors = await collectCandidateVectors(allMemories, semantic, logger);
704
- const minSim = config.dreamCandidateMinSim ?? 0.85;
705
- const pairs = findPotentialConflicts(allMemories, vectors, minSim);
706
- if (config.allowCrossTypeMerge === true) {
707
- for (let i = 0; i < allMemories.length; i++) {
708
- for (let j = i + 1; j < allMemories.length; j++) {
709
- if (allMemories[i].type === allMemories[j].type) continue; // 同类型已由上面覆盖
710
- const sim = cosineSimilarity(vectors[i], vectors[j]);
711
- if (sim > minSim) pairs.push({ a: allMemories[i], b: allMemories[j], similarity: sim });
712
- }
713
- }
714
- }
715
- if (pairs.length === 0) return [];
716
- return similarityGroups(pairs)
717
- .sort((g1, g2) => g2.minSim - g1.minSim)
718
- .flatMap((g) => g.members);
719
- } catch (error) {
720
- logger?.warn?.(`[dsh-mneme] dream hybrid candidate expansion failed (falling back to window): ${String(error)}`);
721
- return [];
722
- }
723
- }
724
-
725
- /**
726
- * Rebuild the vector index after dream decisions so the store and the index
727
- * stay in sync: merged-away/archived/conflict-loser rows lose their vectors,
728
- * the merge keeper gets a fresh one.
729
- */
730
- export async function maintainIndexAfterDream(decisions, service, semantic) {
731
- const { embedder, vectorIndex } = semantic;
732
- if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return;
733
- const rebuild = new Map();
734
- for (const d of decisions ?? []) {
735
- if (d.action === "merge") {
736
- for (const id of d.ids ?? []) {
737
- if (id !== d.keepSource) vectorIndex.deleteEmbedding(id);
738
- }
739
- if (d.keepSource) {
740
- const keeper = service.getById(d.keepSource);
741
- if (keeper) rebuild.set(keeper.id, [keeper.title, keeper.content].filter(Boolean).join("\n"));
742
- }
743
- } else if (d.action === "archive" || d.action === "conflict") {
744
- for (const id of d.ids ?? [d.loser]) vectorIndex.deleteEmbedding(id);
745
- } else if (d.action === "supersede") {
746
- // Issue #126 review(Copilot):被取代的一方已归档 → 移除其向量(与 conflict 的
747
- // loser 同等处置)。winner 正文未变化,向量保持有效。
748
- vectorIndex.deleteEmbedding(d.loser);
749
- } else if (d.action === "differentiate") {
750
- // Issue #126 review(Copilot):双方正文都被追加了差异注记,而 update 在事务内
751
- // 会因 txDepth>0 跳过 scheduleEmbed —— 不在这里重嵌,注记就进不了 embedding,
752
- // 注释里承诺的"下一轮不再判成重复"就不成立。
753
- for (const id of d.ids ?? []) {
754
- const mem = service.getById(id);
755
- if (mem) rebuild.set(id, [mem.title, mem.content].filter(Boolean).join("\n"));
756
- }
757
- } else if (d.action === "update") {
758
- const id = d.ids[0];
759
- const mem = service.getById(id);
760
- if (mem) {
761
- vectorIndex.deleteEmbedding(id);
762
- try {
763
- const text = [mem.title, mem.content].filter(Boolean).join("\n");
764
- const v = await embedder.embedSingle(text);
765
- if (v?.length) vectorIndex.saveEmbedding(id, v);
766
- } catch { /* best-effort */ }
767
- }
768
- }
769
- }
770
- for (const [id, text] of rebuild) {
771
- try {
772
- const v = await embedder.embedSingle(text);
773
- if (v?.length) vectorIndex.saveEmbedding(id, v);
774
- } catch { /* best-effort */ }
775
- }
776
- if (embedder.modelHash) vectorIndex.markModel?.(embedder.modelHash, embedder.dimension);
777
- }
778
-
779
- // Issue #292:连续失败退避的间隔封顶(30 分钟)。封顶只拦指数「增长」,不把
780
- // 用户配得比这更大的 dreamMinIntervalMinutes 基数压小(见 effectiveMinIntervalMs)。
781
- const FAILURE_BACKOFF_CAP_MS = 30 * 60 * 1000;
782
-
783
- export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, minIntervalMs = 0, failureBackoff = false, logger, semantic = null, lastRunAtSeed = 0, baselineSeed = null, peakHours = "", peakMaxDeferMinutes = 120, auditPeakSkip = null, now = () => Date.now(), setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout }) {
784
- let pendingTimer = null;
785
- // Issue #239(第 4 项)镜像到巩固:高峰顺延定时器。与 pendingTimer 分开——两者
786
- // 语义不同(一个是「马上要跑」,一个是「等出高峰再跑」),合成一个变量会让
787
- // maybeSchedule 的守卫在顺延期间把新的写入触发误当成「已有待跑」而吞掉。
788
- let deferTimer = null;
789
- let running = false;
790
- let disposed = false;
791
- // Issue #89(基线半边):阈值基线跨重启持久化。baselineSeed 由调用方从
792
- // dream_runs 读上次成功轮结束时的库规模(store.lastDreamBaseline)——它只活在
793
- // 闭包内存里时进程重启即归零,而库里记忆远多于阈值,重启后第一条写入就满足
794
- // overBase、绕过阈值开跑整轮(#291 只补了 lastRunAt 那半边)。缺种子(新库、
795
- // 升级后还没跑过成功轮)或种子非法时退回 {0,0}:不假装知道基线,行为与升级前
796
- // 逐字节一致——修的是「知道却不认」,不是凭空造一个基线。
797
- let baseline = toBaseline(baselineSeed) ?? { count: 0, chars: 0 };
798
- let inFlight = null;
799
- // Issue #89(请求 2):上一次实际开跑时刻。失败/degraded 的 run 也占用
800
- // 最小间隔——节流的目的正是防止失败调用连发;间隔内的触发静默跳过。
801
- // lastRunAtSeed:调用方从 dream_runs 审计表读出的上次开跑时刻——
802
- // 内存变量进程重启即归零,闸门对新实例放行 → 重启后立刻连发(#89 根因)。
803
- let lastRunAt = lastRunAtSeed;
804
- // Issue #292(#135 派生):同会话内连续失败计数。失败(onRun 抛错或返回
805
- // ok:false)+1,成功清零;无返回结果的 run(no-op 桩)视为完成且无失败,
806
- // 不动计数。纯内存变量、宿主重启归零——跨重启的冷却由 lastRunAtSeed(#291)
807
- // 持久化负责,两者不重叠。
808
- let consecutiveFailures = 0;
809
-
810
- // Issue #292:有效最小间隔 = 基数 × 2^连续失败数,封顶 30 分钟。退避关闭或
811
- // 尚无失败时逐字节返回基数(默认关 = 行为与现状一致)。基数 0 无闸可翻倍
812
- // (本键不自己产生间隔);封顶取 max(基数, cap),指数再大也不会把用户配的
813
- // 大基数压小。2^N 溢出成 Infinity 由 Math.min 兜到 cap,无需另设上限位数。
814
- function effectiveMinIntervalMs() {
815
- if (!failureBackoff || consecutiveFailures <= 0) return minIntervalMs;
816
- const cap = Math.max(minIntervalMs, FAILURE_BACKOFF_CAP_MS);
817
- return Math.min(minIntervalMs * 2 ** consecutiveFailures, cap);
818
- }
819
-
820
- function shouldTrigger(service) {
821
- const { count, chars } = activeStoreSize(service);
822
- const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
823
- const overAbs = count >= thresholdCount || chars >= thresholdChars;
824
- return { trigger: overAbs && overBase, count, chars };
825
- }
826
-
827
- function maybeSchedule(service) {
828
- if (disposed || running || pendingTimer || deferTimer) return false;
829
- // Issue #89(请求 2):最小触发间隔闸门。#292 退避开启时改用指数放大的
830
- // 有效间隔:连续失败越多,下次放行越晚(恒定失败的模型不再按固定节奏连发,
831
- // 只会越打越稀)。失败 run 本就占用间隔(lastRunAt 在开跑时刷新,见 #89),
832
- // 这里放大的是同一道闸,不新增任何状态面。间隔内的触发静默跳过:没有调用
833
- // 发生,也就没有可审计的对象(与 #89 口径一致,不写审计行)。
834
- if (minIntervalMs > 0 && now() - lastRunAt < effectiveMinIntervalMs()) return false;
835
- const { trigger, count, chars } = shouldTrigger(service);
836
- if (!trigger) return false;
837
- // Issue #239(第 4 项,错峰队列)镜像到巩固:命中高峰就不调模型。与蒸馏的差别
838
- // 在于巩固是**全局单实例**(蒸馏按会话各挂一个定时器),所以这里只需要一个
839
- // deferTimer,且不需要 deferredRuns 那套按会话去重。
840
- // baseline 刻意不刷新:阈值继续累积,留到非高峰一次性巩固(一次大 run 比多次
841
- // 小 run 省)。审计只登记一行 skip——「为什么不再做梦了」必须对用户可观测。
842
- if (isInPeakWindow(new Date(now()), peakHours)) {
843
- try {
844
- auditPeakSkip?.({ count, chars });
845
- } catch (error) {
846
- // 记账是 best-effort:写审计行失败只 warn,绝不反噬调度本身。
847
- logger?.warn?.(`dsh-mneme dream: peak-hours audit failed: ${String(error)}`);
848
- }
849
- scheduleDeferredRun(service);
850
- return false;
851
- }
852
- pendingTimer = setTimeoutFn(() => {
853
- pendingTimer = null;
854
- startRun(service);
855
- }, delayMs);
856
- return true;
857
- }
858
-
859
- /**
860
- * Issue #239:高峰内择时补跑——挂到「距当前最近的一个高峰结束时刻」,被
861
- * peakMaxDeferMinutes 截断时到点照跑(bypassPeak),长高峰不会把巩固饿死。
862
- * 定时器 unref:不阻止宿主退出。重复触发不叠加(deferTimer 已在 maybeSchedule
863
- * 的守卫里,这里再判一次以防从其它路径进来)。
864
- */
865
- function scheduleDeferredRun(service) {
866
- if (disposed || deferTimer) return;
867
- const at = nextOffPeakAt(new Date(now()), peakHours);
868
- if (!at) return;
869
- const maxDeferMs = (peakMaxDeferMinutes ?? 0) * 60000;
870
- let delay = Math.max(0, at.getTime() - now());
871
- const capped = maxDeferMs > 0 && delay > maxDeferMs;
872
- if (capped) delay = maxDeferMs;
873
- deferTimer = setTimeoutFn(() => {
874
- deferTimer = null;
875
- if (disposed) return;
876
- // 截断放行时仍在高峰:不再重新顺延(否则长高峰里会无限顺延,等于把巩固
877
- // 关掉)。直接开跑,与蒸馏的 bypassPeak 同口径。
878
- if (!capped && isInPeakWindow(new Date(now()), peakHours)) {
879
- // 理论上到点已出高峰;时钟跳变/时段串被改小可能落回高峰内,此时再顺延一次。
880
- scheduleDeferredRun(service);
881
- return;
882
- }
883
- logger?.info?.(`dsh-mneme dream: peak-hours deferred run firing (capped=${capped}, delayMs=${delay})`);
884
- startRun(service);
885
- }, delay);
886
- deferTimer.unref?.();
887
- }
888
-
889
- /**
890
- * 真正开跑。抽出来是因为两条路径都要用:写入触发的正常路径,与高峰顺延后的
891
- * 补跑路径。onRun 的调用刻意放在 Promise 里——同步抛出的异常若逃出 timer 回调
892
- * 会直接崩掉进程并跳过收尾。inFlight 让 dispose() 能等完这一轮再关库。
893
- */
894
- function startRun(service) {
895
- running = true;
896
- lastRunAt = now();
897
- inFlight = Promise.resolve()
898
- .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
899
- .then((result) => {
900
- // Refresh the baseline only for a successful run (design §5.3: an
901
- // LLM failure must not move the baseline, so the next write can
902
- // immediately re-trigger a retry). A `{ok:false}` result or a throw
903
- // keeps the old baseline. A run that reports nothing is treated as
904
- // completed without failure (no-op hooks / minimal test doubles).
905
- if (result && result.ok) {
906
- consecutiveFailures = 0; // Issue #292:成功清零,下次触发回到基数间隔
907
- try {
908
- // Issue #89(基线半边):run 自报的基线(与审计行同一份数字)优先——重启
909
- // 播种读的就是它,两条路径共用唯一口径;no-op 桩不回这个字段时退回现场
910
- // 计算,最小测试替身的行为逐字节不变。
911
- baseline = toBaseline(result.baseline) ?? shouldTrigger(service);
912
- } catch (error) {
913
- // Store closed mid-flight: keep the last known baseline.
914
- logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
915
- }
916
- } else if (result) {
917
- // Issue #292:ok:false(LLM 失败 / 空体 / 整单拒绝)计入连败;degraded
918
- // 的 run 走 ok:true(LLM 本身成功了,只是决策被部分应用)→ 算成功、清零。
919
- // 退避关闭时该计数没有消费者,行为与此前逐字节一致。
920
- consecutiveFailures += 1;
921
- }
922
- // result 为空(no-op 桩 / 最小测试替身)=完成且无失败:基线与连败计数都不动。
923
- })
924
- .catch((error) => {
925
- logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
926
- // Failed runs do not refresh the baseline.
927
- consecutiveFailures += 1; // Issue #292:抛错同样计入连败
928
- })
929
- .finally(() => {
930
- running = false;
931
- inFlight = null;
932
- });
933
- }
934
-
935
- async function dispose() {
936
- disposed = true;
937
- if (pendingTimer) { clearTimeoutFn(pendingTimer); pendingTimer = null; }
938
- // Issue #239:高峰顺延定时器同样要清,否则进程关闭后仍会触发一次巩固。
939
- if (deferTimer) { clearTimeoutFn(deferTimer); deferTimer = null; }
940
- // An in-flight run is left to complete naturally (its LLM calls are
941
- // already paid for and aborting would discard the work). Await it so the
942
- // caller can close the store only after every write has landed.
943
- if (inFlight) await inFlight.catch(() => {});
944
- }
945
-
946
- async function runDream(ctx, service, config) {
947
- const language = langOf(config);
948
- const logger = ctx.logger;
949
- let memories = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
950
- if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
951
- // Issue #89:开跑时刻既喂给审计行(created_at),也是调度器闸门的时间基准。
952
- const dreamStartedAt = Date.now();
953
- // v0.4.4 滑动窗口:只 consolidation 最近 dreamMaxSnapshotSize 条记忆,
954
- // 窗口外的旧记忆不进 snapshot(大记忆量下全量快照会撑爆 LLM 输入,配合
955
- // 隐式 keep 让 run 始终可收敛)。按 updated_at 倒序取前 maxSize 条。
956
- const maxSize = Number.isInteger(config.dreamMaxSnapshotSize) ? config.dreamMaxSnapshotSize : 200;
957
- const windowMemories = [...memories]
958
- .sort((a, b) => {
959
- const ta = String(a.updated_at ?? "");
960
- const tb = String(b.updated_at ?? "");
961
- if (ta < tb) return 1;
962
- if (ta > tb) return -1;
963
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
964
- })
965
- .slice(0, Math.max(1, maxSize));
966
- // Issue #125:hybrid 档在窗口之外并入向量翻出的高相似组。候选**总量**仍由
967
- // maxSize(或显式 dreamCandidateMax)封顶、与库总量解耦——用"按相似度取候选"
968
- // 替代"调大窗口",输入成本才不随库增长。封顶截断时向量组优先于窗口尾部,
969
- // 否则"该合并的一对"仍会被时间窗挤掉。
970
- let selected = windowMemories;
971
- if ((config.dreamCandidateMode ?? "window") === "hybrid" && semantic?.embedder && semantic?.vectorIndex) {
972
- const extra = await hybridCandidateMembers(memories, config, semantic, logger);
973
- if (extra.length > 0) {
974
- const cap = Math.max(
975
- Math.max(1, maxSize),
976
- Number.isInteger(config.dreamCandidateMax) && config.dreamCandidateMax > 0 ? config.dreamCandidateMax : 0
977
- );
978
- const merged = [];
979
- const seen = new Set();
980
- for (const m of [...extra, ...windowMemories]) {
981
- if (seen.has(m.id)) continue;
982
- seen.add(m.id);
983
- merged.push(m);
984
- if (merged.length >= cap) break;
985
- }
986
- selected = merged;
987
- logger?.info?.(`[dsh-mneme] dream hybrid candidates: ${merged.length} (window ${windowMemories.length}, vector ${extra.length}, cap ${cap})`);
988
- }
989
- }
990
- memories = selected;
991
- const snapshot = new Map(memories.map((m) => [m.id, m]));
992
- const route = resolveRoute(ctx, config, logger);
993
- const runId = randomUUID();
994
- const snapshotHash = hashSnapshot([...snapshot.values()]);
995
- // Conflict freeze (opt-in): when enabled, conflict decisions are parked for
996
- // manual review instead of auto-adjudicated. Read once up front so the
997
- // prompt hint and the apply-split agree on the same gate.
998
- const freezeEnabled = config.conflictFreezeEnabled === true;
999
- // Every exit (success or failure) funnels through `finish`, which writes
1000
- // the audit row + receipt. A record failure is logged, never thrown —
1001
- // auditing must not break the consolidation path. Failed runs still
1002
- // capture their decisions/outcome when the LLM produced a validated list
1003
- // (e.g. summary step failed after consolidation), so the partial write is
1004
- // replayable too.
1005
- const finish = (result) => {
1006
- // status is derived from what actually committed: ok only when the full
1007
- // decision list landed (or a summary was refreshed); noop when nothing
1008
- // changed; degraded when real changes landed without a summary;
1009
- // reconcile when decisions were validated but some did not commit (CAS
1010
- // conflict / rollback); failed on any LLM/validation error. No fake "ok"
1011
- // for an empty or partial run.
1012
- const status = result.status ?? (result.ok ? "ok" : "failed");
1013
- const applied = result.applied ?? 0;
1014
- const summaryStored = result.summary ?? false;
1015
- const receipt = buildReceipt({ runId, status, snapshotHash, inputCount: snapshot.size, applied, summaryStored });
1016
- // Issue #89(基线半边):成功轮把「本轮结束后的库规模」落进审计行 = 阈值基线的
1017
- // 持久化副本,重启后由 store.lastDreamBaseline 播种。判定条件必须与调度器刷新
1018
- // 基线的条件严格一致(result.ok)——非 ok 轮不推进基线是既有语义,若这里也落值,
1019
- // 重启后播种就会拿到一个「其实没推进过」的假基线,阈值反而被抬高。
1020
- // 取不到(库已关闭等)就落 NULL:宁可不持久化,也不写一个错的基线。
1021
- let baselineSnapshot = null;
1022
- if (result.ok) {
1023
- try {
1024
- baselineSnapshot = activeStoreSize(service);
1025
- } catch {
1026
- baselineSnapshot = null;
1027
- }
1028
- }
1029
- try {
1030
- service.saveDreamRun({
1031
- id: runId,
1032
- // Issue #89:审计行记开跑时刻而非完成时刻——lastDreamRunAt 以它做
1033
- // 重启后的间隔种子,落完成时刻会让 run 耗时白白计入下一轮最小间隔。
1034
- created_at: new Date(dreamStartedAt).toISOString(),
1035
- status,
1036
- error: result.error,
1037
- provider: route?.provider,
1038
- model: route?.model,
1039
- snapshot_hash: snapshotHash,
1040
- input_count: snapshot.size,
1041
- // 裁决规则版本号:config.policyEpoch(默认 0)。规则升级后该行保留
1042
- // 当时的 epoch,旧裁决据此降级为历史证据(store 层 getLatestPolicyEpoch
1043
- // 只负责读取当前生效版本,写入由这里完成)。
1044
- policy_epoch: config.policyEpoch ?? 0,
1045
- // Full input snapshot (canonical fields) so the exact arbitration
1046
- // input can be rebuilt offline from the audit row alone — the
1047
- // digest + decisions + outcome triple makes silent errors locatable
1048
- // even after the store has moved on.
1049
- input: [...snapshot.values()].map((m) => ({
1050
- id: m.id,
1051
- type: m.type,
1052
- title: m.title,
1053
- content: m.content,
1054
- importance: m.importance,
1055
- updated_at: m.updated_at
1056
- })),
1057
- decisions: result.decisions,
1058
- outcome: result.outcome,
1059
- applied,
1060
- summary_stored: summaryStored,
1061
- receipt,
1062
- // Issue #104:degraded(合法子集已应用)轮被跳过的决策明细。写成独立字段
1063
- // 而非内联进 decisions——degraded 的 decisions 是合法子集,下游按「决策
1064
- // 数组」消费,内联标记会污染其它读者(失败轮的 _validationFailed 是整单
1065
- // 拒绝哨兵,语义与「部分应用」不同,也不复用)。
1066
- skipped: result.skipped,
1067
- // Issue #89(基线半边):成功的 run 才带这两个值(见上方 baselineSnapshot
1068
- // 的注释)。两列要么同时有值、要么同时为 NULL,读侧以「同时有值」认账。
1069
- store_count: baselineSnapshot?.count,
1070
- store_chars: baselineSnapshot?.chars
1071
- });
1072
- } catch (error) {
1073
- logger?.warn?.(`dsh-mneme dream: failed to record audit run: ${String(error)}`);
1074
- }
1075
- // Issue #89(基线半边):把「与审计行同一份数字」的基线回给调度器,两条路径
1076
- // (进程内刷新 / 跨重启播种)因此共享唯一口径;调度器拿不到时会退出现场计算。
1077
- return { ...result, runId, receipt, snapshotHash, baseline: baselineSnapshot ?? undefined };
1078
- };
1079
- if (!route) {
1080
- logger?.warn?.("dsh-mneme dream: no llm route available");
1081
- return finish({ ok: false, error: "no llm route", summary: false });
1082
- }
1083
-
1084
- let listText;
1085
- if (semantic?.embedder && semantic?.vectorIndex) {
1086
- try {
1087
- const vectors = await collectVectors(memories, semantic);
1088
- if (vectors) {
1089
- const k = Math.min(10, Math.max(1, Math.floor(Math.sqrt(memories.length / 2))));
1090
- const clusters = clusterMemories(memories, vectors, k);
1091
- const conflicts = findPotentialConflicts(memories, vectors, 0.85);
1092
- const conflictIds = new Set(conflicts.flatMap((c) => [c.a.id, c.b.id]));
1093
- const parts = [];
1094
- clusters.forEach((cluster, ci) => {
1095
- parts.push(STR.clusterHeader[language](ci + 1));
1096
- for (const m of cluster) {
1097
- parts.push(
1098
- `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}` +
1099
- (conflictIds.has(m.id) ? STR.conflictMark[language] : "")
1100
- );
1101
- }
1102
- });
1103
- listText = parts.join("\n");
1104
- logger?.info?.(`[dsh-mneme] dream semantic pre-group: ${clusters.length} clusters, ${conflicts.length} conflict pairs`);
1105
- }
1106
- } catch (error) {
1107
- logger?.warn?.(`[dsh-mneme] dream semantic pre-group failed: ${String(error)}`);
1108
- }
1109
- }
1110
- if (!listText) {
1111
- listText = [...snapshot.values()].map((m) =>
1112
- `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
1113
- ).join("\n");
1114
- }
1115
-
1116
- // Freeze-aware prompt: in freeze mode the conflict branch still outputs
1117
- // winner/loser (validation requires them) but they are treated as tentative
1118
- // candidates — the human makes the final call, not the model.
1119
- const consolidationPrompt = freezeEnabled
1120
- ? STR.prompts.consolidation[language] + STR.prompts.freezeSuffix[language]
1121
- : STR.prompts.consolidation[language];
1122
- let decisionText;
1123
- // 加固(v0.8.1):配置的 reasoningEffort 被 provider 拒收时回退重试一次
1124
- // (不带该字段),避免 thinking 模型配置 low/medium 直接整单失败。解析放
1125
- // 在 auditError 检查器里、闭包交回主流程,避免二次解析;解析失败同时如实
1126
- // 记 audit error 并在日志带原始输出前 300 字节,便于定位"推理吞预算返回空体"。
1127
- const effort = await resolveDreamEffort(ctx, route, config.dreamReasoningEffort, logger);
1128
- let decisions = null;
1129
- let streamFailure = "";
1130
- const runConsolidation = (withEffort) => {
1131
- streamFailure = "";
1132
- return runAuditedLlm(ctx, service, config, {
1133
- triggerSource: "autoDream",
1134
- operationType: "dream_consolidate",
1135
- modelId: `${route.provider}:${route.model}`,
1136
- relatedMemoryIds: [...snapshot.keys()],
1137
- streamError: () => streamFailure,
1138
- auditError: (text) => {
1139
- decisions = extractJsonArray(text);
1140
- return Array.isArray(decisions) ? null : "no json array in llm output";
1141
- }
1142
- }, (reportUsage) => streamText(ctx, {
1143
- provider: route.provider,
1144
- model: route.model,
1145
- purpose: "compaction",
1146
- maxTokens: config.dreamMaxTokens ?? 4096,
1147
- ...(withEffort && effort ? { reasoningEffort: effort } : {}),
1148
- messages: [
1149
- { role: "system", content: [{ type: "text", text: consolidationPrompt }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
1150
- { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
1151
- ]
1152
- }, reportUsage, (reason) => { streamFailure = describeStreamFailure(reason); }));
1153
- };
1154
- try {
1155
- // Bug8: the consolidation call is audited (tokens/time/status). A throw
1156
- // re-propagates to the catch below; an aborted stream returns undefined
1157
- // and is treated as a failed run after the check below.
1158
- decisionText = await withEffortFallback(ctx, effort, () => runConsolidation(true), () => runConsolidation(false), () => streamFailure);
1159
- } catch (error) {
1160
- logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
1161
- return finish({ ok: false, error: "llm failed", summary: false });
1162
- }
1163
- if (decisionText === undefined) {
1164
- logger?.warn?.(`dsh-mneme dream: consolidation llm stream aborted or errored${streamFailure ? ` (${streamFailure})` : ""}`);
1165
- return finish({ ok: false, error: "llm failed", summary: false });
1166
- }
1167
- if (!Array.isArray(decisions)) {
1168
- const head = (decisionText ?? "").slice(0, 300).replace(/\s+/g, " ").trim();
1169
- logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0}; head: ${head})`);
1170
- return finish({ ok: false, error: "no json array in llm output", summary: false });
1171
- }
1172
- const { ok, errors, skipped, resolvedShortIds, coverageShortfall } = validateDecisions(decisions, snapshot, {
1173
- maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
1174
- // Issue #104 方向 2:archive 批量上限(全局闸门,超限整单拒绝)。
1175
- maxArchivePerRun: config.dreamMaxArchivePerRun,
1176
- minAgeHours: config.reflectionUpdateMinAgeHours,
1177
- // v0.4.4 fix:显式透传,用户配 dreamImplicitKeep:false 时严格模式必须
1178
- // 真正生效,dreamMinExplicitCoverage 决定隐式 keep 下的覆盖率下限。
1179
- dreamImplicitKeep: config.dreamImplicitKeep,
1180
- dreamMinExplicitCoverage: config.dreamMinExplicitCoverage,
1181
- // Issue #89:v0.6.9(Issue #26)的宽容路径在 v0.7.11 重写中丢失——单条
1182
- // 非法决策重新只跳过该条、合法子集照常应用(run 记为 degraded)。
1183
- skipInvalid: config.dreamSkipInvalid !== false,
1184
- allowCrossTypeMerge: config.allowCrossTypeMerge === true,
1185
- // issue #339 / E8:guarded 类型 merge 护栏(opt-in,dreamMergeGuard)。
1186
- mergeGuard: config.dreamMergeGuard === true
1187
- });
1188
- // Issue #135:模型把 UUID 缩写成前缀时,唯一前缀已在校验前被解析回完整 id。
1189
- // 解析量是模型输出质量的一个直接信号(>0 意味着模型在缩写 id),记一条 info
1190
- // 便于事后从日志侧观察该行为的分布。
1191
- if (resolvedShortIds > 0) {
1192
- logger?.info?.(`[dsh-mneme] dream: resolved ${resolvedShortIds} short id prefix(es) to full ids`);
1193
- }
1194
- if (!ok) {
1195
- // Issue #135(观测缺口):失败轮的逐条校验明细此前既不落库也基本不可见——
1196
- // skipped 的 warn 写在 return 之后(失败路径到不了),dream_runs.decisions
1197
- // 落 NULL,上百轮失败零现场。这里把明细前置到日志,并把
1198
- // { _validationFailed, errors, skipped } 随失败行持久化,事后可从审计行
1199
- // 直接定位「模型输出了什么、为何逐条非法」。
1200
- logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
1201
- if (skipped.length > 0) {
1202
- logger?.warn?.(`dsh-mneme dream: ${skipped.length} invalid decision(s) skipped: ${skipped.map((s) => `decision[${s.index}]: ${s.error}`).join("; ")}`);
1203
- }
1204
- return finish({
1205
- ok: false,
1206
- error: `invalid decisions: ${errors.length} errors`,
1207
- summary: false,
1208
- decisions: [{ _validationFailed: true, errors, skipped }]
1209
- });
1210
- }
1211
- const skippedInvalid = skipped.length > 0;
1212
- if (skippedInvalid) {
1213
- logger?.warn?.(`dsh-mneme dream: ${skipped.length} invalid decision(s) skipped (run degrades): ${skipped.map((s) => s.error).join("; ")}`);
1214
- }
1215
- // Issue #104 方向 1:覆盖率不足降级为 degraded(不再整单拒绝)——合法子集
1216
- // 照常应用、未提及条目隐式 keep,理由随 outcome.degradations 落库供离线定位。
1217
- const coverageDegraded = typeof coverageShortfall === "string" && coverageShortfall.length > 0;
1218
- if (coverageDegraded) {
1219
- logger?.warn?.(`dsh-mneme dream: ${coverageShortfall} (run degrades: valid subset applied, unclaimed ids kept implicitly)`);
1220
- }
1221
-
1222
- // Capture pre-update snapshots so the audit records what each update changed.
1223
- const updateSnapshots = {};
1224
- for (const d of decisions) {
1225
- if (d.action === "update") {
1226
- const mem = snapshot.get(d.ids[0]);
1227
- if (mem) updateSnapshots[d.ids[0]] = { title: mem.title, content: mem.content, importance: mem.importance };
1228
- }
1229
- }
1230
-
1231
- // Conflict freeze (opt-in): when enabled, conflict decisions are not
1232
- // auto-adjudicated — no winner kept, no loser archived. The pair is parked
1233
- // in conflict_pending for human review instead. Best-effort: a store
1234
- // failure here must never block the run (fail-safe — the memories are left
1235
- // untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
1236
- // bounds the review queue; overflow is skipped with a warning.
1237
- let frozenCount = 0;
1238
- const frozenIds = [];
1239
- // v0.8.1(issue #170 复核项 3):跨 scope 的 conflict 决策两种模式都一律
1240
- // 停车人工裁决、绝不自动归档——否则普通 dream 的 LLM 能归档别的 scope 的
1241
- // 唯一副本,sleep 路径(scope-candidate-queue)的保护在这里缺位。同 scope
1242
- // 的 conflict 决策照旧:freeze 停车 / 非 freeze 自动裁决。
1243
- const isCrossScopeDecision = (d) => {
1244
- const a = snapshot.get(d.winner);
1245
- const b = snapshot.get(d.loser);
1246
- return !!a && !!b && (
1247
- scopeKeyOf(a.agent_scope) !== scopeKeyOf(b.agent_scope)
1248
- || scopeKeyOf(a.workspace_scope) !== scopeKeyOf(b.workspace_scope)
1249
- );
1250
- };
1251
- const applyList = freezeEnabled
1252
- ? decisions.filter((d) => d.action !== "conflict")
1253
- : decisions.filter((d) => d.action !== "conflict" || !isCrossScopeDecision(d));
1254
- if (freezeEnabled) {
1255
- const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
1256
- if (conflictsToFreeze.length > 0) {
1257
- try {
1258
- const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
1259
- const pendingNow = service.countConflictPending();
1260
- const budget = Math.max(0, maxPending - pendingNow);
1261
- const toFreeze = conflictsToFreeze.slice(0, budget);
1262
- if (conflictsToFreeze.length > budget) {
1263
- logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
1264
- }
1265
- for (const d of toFreeze) {
1266
- try {
1267
- // 返回 undefined = 该对已被人工裁决且两侧内容未变(issue #170 复核
1268
- // 项 4:内容变了才重新入队)——不算停车、不进 frozenIds。
1269
- const parked = service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
1270
- if (parked == null) continue;
1271
- frozenCount++;
1272
- frozenIds.push(d.winner, d.loser);
1273
- } catch (error) {
1274
- logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
1275
- }
1276
- }
1277
- } catch (error) {
1278
- logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
1279
- }
1280
- }
1281
- } else {
1282
- // 非 freeze:跨 scope conflict 停车(绝不进 applyDecisions)。带专属
1283
- // reason + 模型给出的裁决理由,队列里读起来是「归属裁决」而非重复项。
1284
- const crossScope = decisions.filter((d) => d.action === "conflict" && isCrossScopeDecision(d));
1285
- for (const d of crossScope) {
1286
- try {
1287
- const parked = service.saveConflictPending({
1288
- run_id: runId,
1289
- memory_a: d.winner,
1290
- memory_b: d.loser,
1291
- reason: STR.scopeConflictParkReason[language](d.reason)
1292
- });
1293
- if (parked != null) {
1294
- frozenCount++;
1295
- frozenIds.push(d.winner, d.loser);
1296
- }
1297
- } catch (error) {
1298
- logger?.warn?.(`dsh-mneme dream: failed to park cross-scope conflict ${d.winner}/${d.loser}: ${String(error)}`);
1299
- }
1300
- }
1301
- if (crossScope.length > 0) {
1302
- logger?.info?.(`[dsh-mneme] dream: parked ${crossScope.length} cross-scope conflict(s) for human ownership review`);
1303
- }
1304
- }
1305
-
1306
- // CAS-guarded, per-decision-transactional apply against the run snapshot:
1307
- // a target changed during the LLM call is skipped and reported as a
1308
- // conflict instead of being overwritten (item ①). Frozen conflicts are
1309
- // excluded from this list (they are parked, not applied).
1310
- const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot, config);
1311
- // Per-record receipt chain: one row per actually-committed merge/conflict/
1312
- // update verdict, stamped with the decision-basis digest + idempotency
1313
- // counters (count_before → count_after). Written here, before the run audit
1314
- // row, so the verdict trail always precedes the run trail it belongs to.
1315
- // Bookkeeping: a write failure is logged and swallowed — it must never
1316
- // block the consolidation flow.
1317
- try {
1318
- for (const r of buildRecordReceipts({ runId, committed, snapshot, policyEpoch: config.policyEpoch ?? 0 })) {
1319
- service.saveReceipt(r);
1320
- }
1321
- } catch (error) {
1322
- logger?.warn?.(`dsh-mneme dream: failed to write per-record receipt: ${String(error)}`);
1323
- }
1324
- // Attach the pre-update snapshot to the audit copy of each update decision
1325
- // so the recorded row shows the before/after delta, not just the target.
1326
- const auditDecisions = decisions.map((d) =>
1327
- d.action === "update" && updateSnapshots[d.ids[0]]
1328
- ? { ...d, _before: updateSnapshots[d.ids[0]] }
1329
- : d
1330
- );
1331
- // Outcome is derived from the ACTUALLY committed sub-steps, never from the
1332
- // raw LLM decision list — a merge whose archive step rolled back must not
1333
- // claim "merge-archived" (item ②). Conflicts/failures ride along so the
1334
- // audit row records why the run diverged.
1335
- const outcome = { ...buildOutcome(committed), conflicts, failures };
1336
- if (coverageDegraded) outcome.degradations = [coverageShortfall];
1337
- // Frozen conflicts were not adjudicated: mark both sides pending in the
1338
- // per-id outcome so the audit row shows they were parked, not skipped.
1339
- if (frozenIds.length) {
1340
- for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
1341
- }
1342
- // Decisions validated but not fully committed → reconcile (not ok).
1343
- const partial = conflicts.length > 0 || failures.length > 0;
1344
- // No decision landed (all-keep, or every decision skipped as an idempotent
1345
- // replay) → nothing substantive changed. Distinct from a success: such a
1346
- // run must never be reported as ok, or the audit claims work that never
1347
- // happened and the scheduler refreshes the baseline on a false positive.
1348
- // Frozen conflicts are substantive output (parked for review), so a run
1349
- // that only froze conflicts is not a noop.
1350
- const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
1351
-
1352
- // Keep the vector index consistent with the post-dream store state.
1353
- if (semantic?.embedder && semantic?.vectorIndex) {
1354
- try {
1355
- await maintainIndexAfterDream(applyList, service, semantic);
1356
- } catch (error) {
1357
- logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
1358
- }
1359
- }
1360
-
1361
- // Summary generation (second LLM call). A throwing stream is reported as
1362
- // a failed run; summary:false marks a run that produced no summary.
1363
- let summaryText;
1364
- let summaryStreamFailure = "";
1365
- const runSummary = (withEffort) => {
1366
- summaryStreamFailure = "";
1367
- // Issue #258:总览阶段可用 dreamSummaryProvider/dreamSummaryModel 走独立路由
1368
- //(默认空 = 沿用 dream 路由);输入侧有 dreamSummaryMaxInputs 硬上限,
1369
- // 按窗口同款 updated_at 倒序保留最新的(见下方 summaryInputs)。
1370
- const summaryRoute = (config.dreamSummaryProvider && config.dreamSummaryModel)
1371
- ? { provider: config.dreamSummaryProvider, model: config.dreamSummaryModel }
1372
- : route;
1373
- return runAuditedLlm(ctx, service, config, {
1374
- triggerSource: "autoDream",
1375
- operationType: "dream_summarize",
1376
- modelId: `${summaryRoute.provider}:${summaryRoute.model}`,
1377
- relatedMemoryIds: [],
1378
- streamError: () => summaryStreamFailure
1379
- }, (reportUsage) => streamText(ctx, {
1380
- provider: summaryRoute.provider,
1381
- model: summaryRoute.model,
1382
- purpose: "compaction",
1383
- maxTokens: config.dreamMaxTokens ?? 2048,
1384
- ...(withEffort && effort ? { reasoningEffort: effort } : {}),
1385
- messages: [
1386
- { role: "system", content: [{ type: "text", text: STR.prompts.dreamSummary[language] }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
1387
- { role: "user", content: [{ type: "text", text: summaryInputs.map((m) => `- ${m.title}: ${m.content}`).join("\n") }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
1388
- ]
1389
- }, reportUsage, (reason) => { summaryStreamFailure = describeStreamFailure(reason); }));
1390
- };
1391
- // Resident status bar (#164 alignment): the overview is THE one resident
1392
- // narrative — summary tier 0, refreshed every run via _overwrite (supersede
1393
- // v1, content_history traceable). Its 口径 (what snapshot produced it) is
1394
- // stamped into the content so the standing answer is always auditable; the
1395
- // formal evidence column lands with the narrative-bars batch.
1396
- // Issue #258:输入硬上限(条数)——原全库无界,把 dream 路由指向小 ctx
1397
- // 模型时 120k token 当场 CONTEXT_WINDOW_EXCEEDED(#258 实测),且随库增长
1398
- // 渐进恶化。倒序排序与 consolidate 窗口同款(updated_at desc, id tiebreak),
1399
- // 保留最新的;0 = 关闭上限(回归全库行为,调用方自担 ctx)。
1400
- // #230:document 指针行不进总览(与 dream/sleep 五个候选池的同款排除)。
1401
- const summaryAll = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
1402
- const summaryMaxInputs = Number.isInteger(config.dreamSummaryMaxInputs) ? config.dreamSummaryMaxInputs : 0;
1403
- const summaryInputs = summaryMaxInputs > 0 && summaryAll.length > summaryMaxInputs
1404
- ? [...summaryAll]
1405
- .sort((a, b) => {
1406
- const ta = String(a.updated_at ?? "");
1407
- const tb = String(b.updated_at ?? "");
1408
- if (ta < tb) return 1;
1409
- if (ta > tb) return -1;
1410
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
1411
- })
1412
- .slice(0, summaryMaxInputs)
1413
- : summaryAll;
1414
-
1415
- const summaryScope = STR.summaryScope[language](
1416
- summaryInputs.length,
1417
- runId.slice(0, 8),
1418
- new Date().toISOString().slice(0, 10)
1419
- );
1420
- try {
1421
- // Bug8: the summary call is audited too (operation dream_summarize).
1422
- summaryText = await withEffortFallback(ctx, effort, () => runSummary(true), () => runSummary(false), () => summaryStreamFailure);
1423
- } catch (error) {
1424
- logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
1425
- return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
1426
- }
1427
- let summaryStored = false;
1428
- if (summaryText !== undefined && summaryText.trim()) {
1429
- // Bug5 carve-out: the library overview is regenerated every run, so it
1430
- // must REPLACE the previous overview (not append — that would grow the
1431
- // summary unboundedly). `_overwrite` still archives the old overview into
1432
- // content_history before replacing it. Content carries the snapshot-scope
1433
- // footer computed above — the resident bar states its own 口径.
1434
- service.saveWithDedupe({ type: "summary", title: STR.summaryTitle[language], content: `${summaryText.trim()}${summaryScope}`, importance: 5, source: "dream", _overwrite: true });
1435
- summaryStored = true;
1436
- // Re-embed the fresh summary so the index stays in sync with the store.
1437
- if (semantic?.embedder && semantic?.vectorIndex) {
1438
- try {
1439
- // source="dream" 限定:叙述条(source=narrative)同为 summary 类型,
1440
- // 不加限定时 find 可能截胡,把总览的 re-embed 花在叙述条上。
1441
- const summary = service.all().find((m) => m.type === "summary" && m.source === "dream");
1442
- if (summary) await reEmbedMemory(semantic, summary, logger);
1443
- } catch { /* best-effort */ }
1444
- }
1445
- }
1446
- // Narrative bars (#164 alignment, opt-in dreamNarrativeEnabled): per-topic
1447
- // on-demand narratives after consolidation + summary. Additive phase —
1448
- // failures degrade to zero narratives, never break the run.
1449
- let narrativesStored = 0;
1450
- if (config.dreamNarrativeEnabled === true) {
1451
- try {
1452
- narrativesStored = await generateNarratives({ ctx, service, config, route, language, effort, semantic, logger });
1453
- } catch (error) {
1454
- logger?.warn?.(`dsh-mneme dream: narrative phase failed: ${String(error)}`);
1455
- }
1456
- }
1457
-
1458
- // Honest status assignment (never a fake ok):
1459
- // reconcile — some decisions validated but did not commit (CAS/rollback).
1460
- // noop — nothing changed and no summary persisted: truly an empty
1461
- // run. ok:false keeps the scheduler from moving the baseline.
1462
- // ok — either real changes landed, or a fresh summary was stored
1463
- // (all-keep + summary is a substantive summary refresh).
1464
- // degraded — real consolidation landed but the run did not produce its
1465
- // full output: the summary came back empty/missing, or
1466
- // skipInvalid dropped individually-invalid decisions
1467
- // (Issue #89 — marked, not faked), or the explicit-decision
1468
- // coverage fell below dreamMinExplicitCoverage (Issue #104
1469
- // 方向 1 — degrade, don't reject). The valid subset was
1470
- // absorbed (ok for the baseline).
1471
- let status;
1472
- let okResult;
1473
- if (partial) {
1474
- status = "reconcile";
1475
- okResult = false;
1476
- } else if (noChange) {
1477
- status = summaryStored ? "ok" : "noop";
1478
- okResult = summaryStored;
1479
- } else {
1480
- status = summaryStored && !skippedInvalid && !coverageDegraded ? "ok" : "degraded";
1481
- okResult = true;
1482
- }
1483
- return finish({
1484
- ok: okResult,
1485
- status,
1486
- applied,
1487
- decisions: auditDecisions,
1488
- outcome,
1489
- conflicts,
1490
- failures,
1491
- frozen: frozenCount,
1492
- summary: summaryStored,
1493
- narratives: narrativesStored,
1494
- // Issue #104:只有真发生跳过时才落库(degraded 也可能仅因 summary 为空),
1495
- // ok 轮留 NULL,避免「空数组」与「无此字段」两种假明细占据审计行。
1496
- skipped: skippedInvalid ? skipped : undefined
1497
- });
1498
- }
1499
-
1500
- return { maybeSchedule, runDream, dispose };
1501
- }
1
+ import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
+ import { clusterMemories, findPotentialConflicts, cosineSimilarity } from "./dream/clustering.js";
3
+ import { clusterByTag, intersectEvidence } from "./dream/narratives.js";
4
+ import { scopeKeyOf } from "./scope.js";
5
+ // Issue #239(第 4 项)镜像到巩固:错峰时段解析与「最近的高峰结束时刻」从独立的
6
+ // 零依赖模块 peak-hours.js 取(该模块从 summarize.js 抽出,PR #320 review)——
7
+ // 不另写一份解析器,两份实现漂移会让「同一个时段串在两处行为不同」,那比没有
8
+ // 这个功能更糟。此前直接 import summarize.js,#316 后 summarize 反向依赖 dream
9
+ // (withEffortFallback 复用),会成真循环,故抽模块。
10
+ import { isInPeakWindow, nextOffPeakAt } from "./peak-hours.js";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { STR, langOf } from "./lang.js";
13
+ export { validateDecisions, applyDecisions, withEffortFallback, describeStreamFailure, resolveDreamEffort, resolveRoute };
14
+
15
+ // Extract the first JSON array from LLM output, tolerating markdown fences,
16
+ // leading/trailing prose, and common wrapper noise. Returns an array or null.
17
+ function extractJsonArray(text) {
18
+ if (typeof text !== "string" || text.trim().length === 0) return null;
19
+
20
+ // 1. Strip markdown code fences (```json ... ``` or ``` ... ```).
21
+ let cleaned = text.replace(/```(?:json)?\s*([\s\S]*?)```/gi, "$1");
22
+ cleaned = cleaned.trim();
23
+
24
+ // 2. Find the first '[' and the matching last ']' that yields valid JSON.
25
+ const start = cleaned.indexOf("[");
26
+ if (start === -1) return null;
27
+ for (let end = cleaned.lastIndexOf("]"); end > start; end = cleaned.lastIndexOf("]", end - 1)) {
28
+ const candidate = cleaned.slice(start, end + 1);
29
+ try {
30
+ return JSON.parse(candidate);
31
+ } catch {
32
+ // Light repair: remove trailing commas before ] or }.
33
+ try {
34
+ const repaired = candidate.replace(/,(\s*[}\]])/g, "$1");
35
+ return JSON.parse(repaired);
36
+ } catch {
37
+ // keep searching backwards
38
+ }
39
+ }
40
+ }
41
+
42
+ // 3. Fallback: a broader regex extraction.
43
+ try {
44
+ const match = cleaned.match(/\[[\s\S]*\]/);
45
+ if (match) return JSON.parse(match[0]);
46
+ } catch {
47
+ // fall through
48
+ }
49
+ return null;
50
+ }
51
+ function totalChars(memories) {
52
+ return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
53
+ }
54
+
55
+ // 阈值口径的唯一实现:活跃记忆(未归档、非 summary/document)的条数与正文字符数。
56
+ // 触发判定(shouldTrigger)与「成功轮把基线落库」(runDream 的 finish)都走这里——
57
+ // 两处若各写一份过滤条件,重启播种读到的基线就会和运行期判定口径漂移(一个把
58
+ // document 算进去、一个不算),阈值随之失真,且这种漂移只会在重启后才显形。
59
+ function activeStoreSize(service) {
60
+ const memories = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
61
+ return { count: memories.length, chars: totalChars(memories) };
62
+ }
63
+
64
+ // 基线的唯一合法形状:两个非负整数;其余(缺字段、负数、非整数、整个对象缺失)
65
+ // 一律视为「没有基线」→ 调用方退回 {0,0}。播种值来自持久化列,可能是老库的 NULL
66
+ // 或手工改坏的库,判定必须比调用点更严格,而不是相信数据库里存的一定合法。
67
+ function toBaseline(raw) {
68
+ if (!raw || typeof raw !== "object") return null;
69
+ const count = Number.isInteger(raw.count) && raw.count >= 0 ? raw.count : null;
70
+ const chars = Number.isInteger(raw.chars) && raw.chars >= 0 ? raw.chars : null;
71
+ if (count === null || chars === null) return null;
72
+ return { count, chars };
73
+ }
74
+
75
+ // ---------------------------------------------------------------- audit
76
+
77
+ /**
78
+ * Canonical digest of the consolidation input snapshot. Built from stable
79
+ * fields sorted by id, so identical inputs always yield the same hash — the
80
+ * basis for replaying/verifying a recorded decision (receipt check).
81
+ */
82
+ export function hashSnapshot(memories) {
83
+ const canon = memories
84
+ .map((m) => [m.id, m.type, m.title, m.content, m.importance, m.updated_at])
85
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
86
+ .map((parts) => parts.map((p) => String(p ?? "")).join("\u0001"))
87
+ .join("\u0002");
88
+ return createHash("sha256").update(canon).digest("hex");
89
+ }
90
+
91
+ /**
92
+ * Compact machine-verifiable receipt for one autoDream run. Format:
93
+ * dsh-mneme:run:<runId>:<status>:<snapshotHash(12)>:<inputCount>:<applied>:<summaryFlag>
94
+ * Enough to correlate a run with its persisted audit row and to spot silent
95
+ * drift (same snapshot hash + same decisions must reproduce the same outcome).
96
+ */
97
+ export function buildReceipt({ runId, status, snapshotHash, inputCount, applied, summaryStored }) {
98
+ return `dsh-mneme:run:${runId}:${status}:${snapshotHash.slice(0, 12)}:${inputCount}:${applied}:${summaryStored ? 1 : 0}`;
99
+ }
100
+
101
+ /**
102
+ * Parse a receipt back into fields; returns undefined for malformed input.
103
+ */
104
+ export function parseReceipt(receipt) {
105
+ if (typeof receipt !== "string") return undefined;
106
+ const parts = receipt.split(":");
107
+ if (parts.length !== 8 || parts[0] !== "dsh-mneme" || parts[1] !== "run") return undefined;
108
+ const [, , runId, status, snapshotHash, inputCount, applied, summaryStored] = parts;
109
+ // reconcile = decisions validated but one or more did not commit (CAS
110
+ // conflict / transaction rollback) — the store diverges from the decision
111
+ // list and the run must be reconciled, never reported as a fake ok.
112
+ if (!runId || !/^(ok|noop|degraded|reconcile|failed)$/.test(status)) return undefined;
113
+ const count = Number(inputCount);
114
+ const appliedN = Number(applied);
115
+ if (!Number.isInteger(count) || !Number.isInteger(appliedN)) return undefined;
116
+ return { runId, status, snapshotHash, inputCount: count, applied: appliedN, summaryStored: summaryStored === "1" };
117
+ }
118
+
119
+ /**
120
+ * Derive the per-id disposition (keep / merge-keep / merge-archived /
121
+ * archived / conflict-winner / conflict-archived) from a validated decision
122
+ * list. Stored in the audit row so a run can be replayed without re-running
123
+ * the LLM.
124
+ */
125
+ export function buildOutcome(decisions) {
126
+ const byId = {};
127
+ for (const d of decisions ?? []) {
128
+ if (d.action === "keep") {
129
+ for (const id of d.ids) byId[id] = "keep";
130
+ } else if (d.action === "archive") {
131
+ for (const id of d.ids) byId[id] = "archived";
132
+ } else if (d.action === "merge") {
133
+ for (const id of d.ids) byId[id] = id === d.keepSource ? "merge-keep" : "merge-archived";
134
+ } else if (d.action === "conflict") {
135
+ byId[d.winner] = "conflict-winner";
136
+ byId[d.loser] = "conflict-archived";
137
+ } else if (d.action === "update") {
138
+ for (const id of d.ids) byId[id] = "updated";
139
+ } else if (d.action === "supersede") {
140
+ // Issue #126 review(Copilot):新动作此前在 outcome.byId 里没有 disposition,
141
+ // 审计行产了 receipt 却看不出这些目标被如何处置。
142
+ byId[d.winner] = "supersede-winner";
143
+ byId[d.loser] = "superseded-archived";
144
+ } else if (d.action === "differentiate") {
145
+ for (const id of d.ids ?? []) byId[id] = "differentiated";
146
+ }
147
+ }
148
+ return { byId };
149
+ }
150
+
151
+ /**
152
+ * Content-addressed digest of the memories a verdict was decided against
153
+ * (id + title + content + importance), sorted by id so identical inputs always
154
+ * hash the same. This is the per-record "判定依据" fingerprint: a receipt whose
155
+ * digest cannot be reproduced from the involved memories is a bare claim, and a
156
+ * digest match with a divergent outcome pinpoints drift to the exact record.
157
+ */
158
+ export function hashDecisionInput(memories) {
159
+ const canon = (memories ?? [])
160
+ .map((m) => [m.id, m.title, m.content, m.importance])
161
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
162
+ .map((p) => p.map((x) => String(x ?? "")).join(""))
163
+ .join("");
164
+ return createHash("sha256").update(canon).digest("hex");
165
+ }
166
+
167
+ /**
168
+ * Build the per-record receipts for a run's actually-committed mutable verdicts
169
+ * (merge/conflict/update) — one row per verdict in the receipt_chain. Inputs
170
+ * are drawn from the run snapshot (what the LLM actually arbitrated against),
171
+ * and the idempotency counters count_before → count_after come from the
172
+ * committed sub-step, so replaying the same decision must reproduce the same
173
+ * numbers. verdict starts "live"; a later policy_epoch upgrade will batch-mark
174
+ * older verdicts "historical" (a receipt_chain rewrite driven by the store's
175
+ * getLatestPolicyEpoch — out of scope for this pass), while "revoked" is
176
+ * reserved for verdicts later overturned by an explicit human decision.
177
+ */
178
+ function buildRecordReceipts({ runId, committed, snapshot, policyEpoch }) {
179
+ const at = (id) => snapshot?.get?.(id);
180
+ const receipts = [];
181
+ for (const c of committed ?? []) {
182
+ const base = {
183
+ run_id: runId,
184
+ verdict: "live",
185
+ count_before: c.count_before,
186
+ count_after: c.count_after,
187
+ policy_epoch: policyEpoch,
188
+ created_at: new Date().toISOString()
189
+ };
190
+ if (c.action === "merge") {
191
+ receipts.push({
192
+ ...base,
193
+ receipt_id: randomUUID(),
194
+ record_id: c.keepSource,
195
+ kind: "merge",
196
+ input_digest: hashDecisionInput((c.ids ?? []).map(at).filter(Boolean)),
197
+ keep_source: c.keepSource,
198
+ sources: c.ids
199
+ });
200
+ } else if (c.action === "conflict") {
201
+ receipts.push({
202
+ ...base,
203
+ receipt_id: randomUUID(),
204
+ record_id: c.winner,
205
+ kind: "conflict",
206
+ input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
207
+ winner_id: c.winner,
208
+ loser_id: c.loser
209
+ });
210
+ } else if (c.action === "update") {
211
+ receipts.push({
212
+ ...base,
213
+ receipt_id: randomUUID(),
214
+ record_id: c.ids[0],
215
+ kind: "update",
216
+ input_digest: hashDecisionInput([at(c.ids[0])].filter(Boolean))
217
+ });
218
+ } else if (c.action === "supersede") {
219
+ // Issue #126:演进型裁决——record 记被取代的一方。winner 正文未被改动,
220
+ // 不需要自己的 receipt;loser 归档并追加"已被取代"注记。
221
+ receipts.push({
222
+ ...base,
223
+ receipt_id: randomUUID(),
224
+ record_id: c.loser,
225
+ kind: "supersede",
226
+ input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
227
+ winner_id: c.winner,
228
+ loser_id: c.loser
229
+ });
230
+ } else if (c.action === "differentiate") {
231
+ // Issue #126:互补型裁决——两条都保留,各记一条 receipt。数量没有变化,
232
+ // count_before/after 固定 1/1(该记录只是被追加了差异注记)。
233
+ for (const id of c.ids ?? []) {
234
+ receipts.push({
235
+ ...base,
236
+ receipt_id: randomUUID(),
237
+ record_id: id,
238
+ kind: "differentiate",
239
+ input_digest: hashDecisionInput([at(id)].filter(Boolean)),
240
+ count_before: 1,
241
+ count_after: 1
242
+ });
243
+ }
244
+ }
245
+ }
246
+ return receipts;
247
+ }
248
+
249
+ /**
250
+ * Consume an LLM stream and return the accumulated text. Direct text-delta
251
+ * accumulation covers both the real protocol ({type:"text-delta", index, text})
252
+ * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
253
+ * surfaces as undefined. The caller decides how to treat an empty result.
254
+ * `onUsage` (optional, Bug8) receives any usage chunk for token accounting.
255
+ */
256
+ async function streamText(ctx, options, onUsage, onStreamError) {
257
+ let text = "";
258
+ for await (const chunk of ctx.llm.stream(options)) {
259
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
260
+ // DSH 的 StreamChunk 契约把用量嵌在 chunk.usage(TokenUsage:inputTokens /
261
+ // outputTokens / …),chunk 顶层没有 token 字段——把整个 chunk 当用量对象交给
262
+ // reporter,input/output 恒为 undefined,审计行落 0(v0.8.4 实测:7 天 49 次
263
+ // success 调用 token 全 0,面板「LLM 消耗」长期显示 0)。`?? chunk` 兜底把用量
264
+ // 平铺在顶层的替身。
265
+ if (chunk.type === "usage" && typeof onUsage === "function") onUsage(chunk.usage ?? chunk);
266
+ if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
267
+ // dsh-llm rc.1 turns adapter-stage failures (unknown provider route,
268
+ // UNSUPPORTED_REASONING_EFFORT from resolveCallWithInfo, …) into a
269
+ // terminal finish chunk instead of a throw — the cause rides in
270
+ // chunk.reason.failure {message, code}. Surface it, never swallow it.
271
+ if (typeof onStreamError === "function") {
272
+ try { onStreamError(chunk.reason); } catch { /* diagnostics only */ }
273
+ }
274
+ return undefined;
275
+ }
276
+ }
277
+ return text;
278
+ }
279
+
280
+ /** One-line human-readable cause from a finish-chunk failure reason. */
281
+ function describeStreamFailure(reason) {
282
+ const failure = reason?.failure ?? reason ?? {};
283
+ const code = failure.code ? String(failure.code) : "";
284
+ const message = String(failure.message ?? failure.error ?? "");
285
+ if (code && message) return message.includes(code) ? message : `${code}: ${message}`;
286
+ return code || message;
287
+ }
288
+
289
+ /**
290
+ * Bug8: wrap a background LLM call so its token/time/status are recorded in the
291
+ * llm_audit_logs table. Best-effort bookkeeping: a failure to WRITE the audit
292
+ * row is swallowed (never blocks the LLM call), while a failure of the call
293
+ * itself is captured as status='error' and re-thrown so the caller keeps its
294
+ * existing error path. `spec` carries the static metadata (trigger_source,
295
+ * operation_type, model_id, related_memory_ids); `body(reportUsage)` performs
296
+ * the actual stream consumption and is handed a usage reporter for the chunks.
297
+ */
298
+ async function runAuditedLlm(ctx, service, config, spec, body) {
299
+ const audit = config?.llmAudit;
300
+ if (audit?.enabled === false || typeof service?.saveLlmAudit !== "function") return body(() => {});
301
+ const startedAt = Date.now();
302
+ const timestamp = new Date(startedAt).toISOString();
303
+ let inputTokens = 0;
304
+ let outputTokens = 0;
305
+ let status = "success";
306
+ let errorMessage = null;
307
+ let result;
308
+ try {
309
+ result = await body((usage) => {
310
+ if (!usage) return;
311
+ const i = usage.input_tokens ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens;
312
+ const o = usage.output_tokens ?? usage.outputTokens ?? usage.completion_tokens ?? usage.completionTokens;
313
+ if (Number.isFinite(i)) inputTokens = i;
314
+ if (Number.isFinite(o)) outputTokens = o;
315
+ });
316
+ if (result === undefined) {
317
+ // stream aborted/errored: the caller treats undefined as a failed run;
318
+ // record it as error here so the audit shows the truth. spec.streamError
319
+ // (a getter) lets the caller attach the finish-chunk cause so the audit
320
+ // row names it instead of a bare "aborted".
321
+ status = "error";
322
+ const streamErr = typeof spec.streamError === "function" ? String(spec.streamError() ?? "") : "";
323
+ errorMessage = errorMessage ?? (streamErr ? `llm stream aborted or errored (${streamErr})` : "llm stream aborted or errored");
324
+ } else if (typeof spec.auditError === "function") {
325
+ // A stream that returned text but yields nothing usable is still a
326
+ // failed call — record it as error, not the default success, so the
327
+ // audit no longer contradicts a failed run (dream "no json array").
328
+ const message = spec.auditError(result);
329
+ if (message) {
330
+ status = "error";
331
+ errorMessage = message;
332
+ }
333
+ }
334
+ return result;
335
+ } catch (error) {
336
+ status = "error";
337
+ errorMessage = String(error?.message ?? error);
338
+ throw error;
339
+ } finally {
340
+ try {
341
+ service.saveLlmAudit({
342
+ timestamp,
343
+ trigger_source: spec.triggerSource,
344
+ operation_type: spec.operationType,
345
+ model_id: spec.modelId,
346
+ input_tokens: inputTokens,
347
+ output_tokens: outputTokens,
348
+ total_tokens: inputTokens + outputTokens,
349
+ cost_usd: 0,
350
+ duration_ms: Date.now() - startedAt,
351
+ status,
352
+ error_message: errorMessage,
353
+ related_memory_ids: spec.relatedMemoryIds ?? []
354
+ });
355
+ } catch (auditError) {
356
+ ctx.logger?.warn?.(`dsh-mneme: llm audit write failed: ${String(auditError)}`);
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Reasoning-effort rejection fallback (v0.8.1): a configured dreamReasoningEffort
363
+ * / sleepReasoningEffort may be rejected by the provider (volcano-engine returns
364
+ * UNSUPPORTED_REASONING_EFFORT for values it does not accept — "off" is known
365
+ * rejected there). When that happens, retry once WITHOUT the reasoning field
366
+ * instead of hard-failing the run, so effort config is safe to experiment with:
367
+ * accepted → reasoning capped; rejected → provider default (old behavior),
368
+ * logged so the rejection is observable.
369
+ */
370
+ // Issue #315:effort 拒收判别式的单一来源。summarize 的流失败以 aborted 结果
371
+ // 返回,需在折叠成 undefined 前用同一甄别(各处手写会漂移)。
372
+ export const EFFORT_REJECT_RE = /reasoning[\s_]*effort|UNSUPPORTED_REASONING_EFFORT/i;
373
+ async function withEffortFallback(ctx, effort, attempt, fallback, getStreamError) {
374
+ if (!effort || effort === "none") return attempt();
375
+ try {
376
+ const result = await attempt();
377
+ if (result === undefined) {
378
+ // dsh-llm rc.1 streams a provider effort-rejection as a terminal error
379
+ // finish chunk (adapterStream catches everything, never throws) — match
380
+ // on the chunk's failure reason here or the retry below is dead code
381
+ // for the stream path.
382
+ const reason = String(getStreamError?.() ?? "");
383
+ if (EFFORT_REJECT_RE.test(reason)) {
384
+ ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected via stream (${reason}); retrying without it`);
385
+ return fallback();
386
+ }
387
+ }
388
+ return result;
389
+ } catch (error) {
390
+ // dispose/取消中止直接放行,绝不能被误判成 effort 拒收而触发 fallback
391
+ //(取消后重打一次不带 effort 的调用是浪费,且可能掩盖真实的取消意图)。
392
+ if (error?.name === "AbortError") throw error;
393
+ const message = String(error?.message ?? error);
394
+ // matches both "reasoning effort" (natural language) and the bare
395
+ // "UNSUPPORTED_REASONING_EFFORT" error code (underscore).
396
+ if (!EFFORT_REJECT_RE.test(message)) throw error;
397
+ ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected (${message}); retrying without it`);
398
+ return fallback();
399
+ }
400
+ }
401
+
402
+ /** 向量索引同步(总览与叙述条共用):fail-safe,失败只 warn 不反噬主流程。 */
403
+ async function reEmbedMemory(semantic, memory, logger) {
404
+ if (!semantic?.embedder || !semantic?.vectorIndex || !memory) return;
405
+ try {
406
+ const v = await semantic.embedder.embedSingle([memory.title, memory.content].filter(Boolean).join("\n"));
407
+ if (v?.length) semantic.vectorIndex.saveEmbedding(memory.id, v);
408
+ if (semantic.embedder.modelHash) semantic.vectorIndex.markModel?.(semantic.embedder.modelHash, semantic.embedder.dimension);
409
+ } catch (error) {
410
+ logger?.warn?.(`dsh-mneme dream: re-embed failed: ${String(error)}`);
411
+ }
412
+ }
413
+
414
+ /**
415
+ * 叙述条阶段(#164 对齐,opt-in dreamNarrativeEnabled):共享 tag 主题聚类 →
416
+ * 单次 LLM 调用按簇合成叙述 → 证据求交(防捏造,dream/narratives.js 纯函数)
417
+ * → saveWithDedupe(source="narrative", _overwrite) 落库。按需检索不常驻注入。
418
+ * 任何失败降级为 0 条,绝不反噬 dream 主流程。
419
+ */
420
+ async function generateNarratives({ ctx, service, config, route, language, effort, semantic, logger }) {
421
+ const inputs = service.all().filter((m) => !m.archived && !m.forgotten && m.type !== "summary" && m.type !== "document");
422
+ const clusters = clusterByTag(inputs, { minCluster: config.dreamNarrativeMinCluster ?? 3 });
423
+ if (!clusters.length) return 0;
424
+
425
+ const listing = clusters
426
+ .map(({ tag, members }) =>
427
+ [`# ${tag}`, ...members.map((m) => `- id=${m.id} | title=${m.title} | ${m.content}`)].join("\n"))
428
+ .join("\n\n");
429
+ let streamFailure = "";
430
+ const runNarratives = (withEffort) => {
431
+ streamFailure = "";
432
+ return runAuditedLlm(ctx, service, config, {
433
+ triggerSource: "autoDream",
434
+ operationType: "dream_narrative",
435
+ modelId: `${route.provider}:${route.model}`,
436
+ relatedMemoryIds: clusters.flatMap((c) => c.members.map((m) => m.id)),
437
+ streamError: () => streamFailure
438
+ }, (reportUsage) => streamText(ctx, {
439
+ provider: route.provider,
440
+ model: route.model,
441
+ purpose: "compaction",
442
+ maxTokens: config.dreamMaxTokens ?? 2048,
443
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
444
+ messages: [
445
+ { role: "system", content: [{ type: "text", text: STR.prompts.narrative[language] }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
446
+ { role: "user", content: [{ type: "text", text: listing }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
447
+ ]
448
+ }, reportUsage, (reason) => { streamFailure = describeStreamFailure(reason); }));
449
+ };
450
+ const text = await withEffortFallback(ctx, effort, () => runNarratives(true), () => runNarratives(false), () => streamFailure);
451
+
452
+ const entries = extractJsonArray(text);
453
+ if (!Array.isArray(entries)) return 0;
454
+ const clusterByOfferedTag = new Map(clusters.map((c) => [c.tag, c]));
455
+ const now = new Date().toISOString();
456
+ let stored = 0;
457
+ for (const entry of entries) {
458
+ if (!entry || typeof entry !== "object") continue;
459
+ const cluster = clusterByOfferedTag.get(typeof entry.tag === "string" ? entry.tag : "");
460
+ const content = String(entry.content ?? "").trim();
461
+ if (!cluster || !content) continue; // 未提供的 tag / 空叙述 → 跳过
462
+ const evidenceIds = intersectEvidence(entry.evidence, cluster.members);
463
+ const { memory } = service.saveWithDedupe({
464
+ type: "summary",
465
+ title: STR.narrativeTitle[language](cluster.tag),
466
+ content,
467
+ importance: 3,
468
+ tags: [cluster.tag],
469
+ source: "narrative",
470
+ evidence: evidenceIds.map((id) => ({ memory_id: id, op: "support", at: now })),
471
+ _overwrite: true
472
+ });
473
+ if (!memory) continue;
474
+ stored++;
475
+ // 叙述条按需可检索:向量索引同步(与总览共用 reEmbedMemory,fail-safe)。
476
+ await reEmbedMemory(semantic, memory, logger);
477
+ }
478
+ return stored;
479
+ }
480
+
481
+ /**
482
+ * Resolve the reasoning effort to actually send for a dream/sleep route.
483
+ *
484
+ * Reasoning-effort config that the provider does not accept trips the harness's
485
+ * UNSUPPORTED_REASONING_EFFORT, and the defaultEffort trap makes retrying
486
+ * "without the field" useless: the harness substitutes `reasoning.defaultEffort`,
487
+ * which may itself be unsupported (DSH Desktop volcano-engine adapter declares
488
+ * defaultEffort=low that its model rejects). So instead of blind retries, ask
489
+ * the harness for the model's declared capability and pick a value that is
490
+ * actually accepted — or omit the field entirely when the model declares no
491
+ * reasoning capability at all.
492
+ *
493
+ * Unset vs explicit 'none' (Issue #135 建议 4/5): these are different intents.
494
+ * Explicit 'none' = the user asked to omit the field (provider default
495
+ * applies). Unset is the out-of-the-box state — dream/sleep calls must produce
496
+ * JSON, and omission lets the harness substitute the model's defaultEffort
497
+ * (thinking-type models often default to high), which drains the token budget
498
+ * and returns an empty body. So unset resolves to the LOWEST effort the model
499
+ * declares instead of omitting; when the capability query is unavailable the
500
+ * field stays omitted (fail-safe, retry guard unchanged).
501
+ *
502
+ * @returns a supported effort id, or null when no effort should be sent, or the
503
+ * configured value unchanged when the capability query is unavailable.
504
+ */
505
+
506
+ // 常识档位排序(越靠前推理开销越低);未知档位排最后(宁可交给显式配置)。
507
+ const EFFORT_RANK = { minimal: 0, off: 0, low: 1, medium: 2, high: 3, max: 4 };
508
+
509
+ function lowestSupportedEffort(reasoning) {
510
+ const ids = (reasoning?.efforts ?? []).map((e) => e?.id).filter(Boolean);
511
+ if (ids.length === 0) return null;
512
+ return [...ids].sort((a, b) => (EFFORT_RANK[a] ?? 99) - (EFFORT_RANK[b] ?? 99))[0];
513
+ }
514
+
515
+ async function resolveDreamEffort(ctx, route, configuredEffort, logger) {
516
+ // 显式 'none':用户要求省略字段(服务商自带默认生效),照旧。
517
+ if (configuredEffort === "none") return null;
518
+ if (!configuredEffort) {
519
+ // 未配置(开箱默认):取模型声明的最低档,避免 defaultEffort 顶上(建议 4/5)。
520
+ if (typeof ctx?.llm?.resolveModelInfo !== "function") return null;
521
+ try {
522
+ const info = await ctx.llm.resolveModelInfo(route.provider, route.model);
523
+ const reasoning = info?.reasoning;
524
+ if (!reasoning) return null; // 无推理声明:省略即安全(无 defaultEffort 可顶上)
525
+ const lowest = lowestSupportedEffort(reasoning);
526
+ if (!lowest) return null;
527
+ logger?.info?.(`dsh-mneme dream: no reasoningEffort configured for ${route.provider}:${route.model}; using lowest supported "${lowest}" instead of the model default "${reasoning.defaultEffort ?? "n/a"}"`);
528
+ return lowest;
529
+ } catch (error) {
530
+ // 能力查询失败:省略字段(fail-safe),withEffortFallback 照旧兜底。
531
+ logger?.warn?.(`dsh-mneme dream: resolveModelInfo failed (${String(error?.message ?? error)}); omitting reasoningEffort`);
532
+ return null;
533
+ }
534
+ }
535
+ // Capability query unavailable (older harness / minimal mocks): forward the
536
+ // configured value as before — absence of the API proves nothing about the
537
+ // model, and withEffortFallback still guards against rejection.
538
+ if (typeof ctx?.llm?.resolveModelInfo !== "function") return configuredEffort;
539
+ try {
540
+ const info = await ctx.llm.resolveModelInfo(route.provider, route.model);
541
+ const reasoning = info?.reasoning;
542
+ if (!reasoning) {
543
+ // Model declares no reasoning capability: the harness rejects ANY
544
+ // explicit effort for such a model, and omitting the field is safe
545
+ // (no reasoning capability → no defaultEffort substitution).
546
+ logger?.warn?.(`dsh-mneme dream: model ${route.provider}:${route.model} declares no reasoning capability; ignoring configured effort "${configuredEffort}"`);
547
+ return null;
548
+ }
549
+ const supported = reasoning.efforts?.map((effort) => effort.id) ?? [];
550
+ if (supported.includes(configuredEffort)) return configuredEffort;
551
+ // Configured effort unsupported → pick defaultEffort if it is supported,
552
+ // else the first declared effort, so the run never trips
553
+ // UNSUPPORTED_REASONING_EFFORT (nor the defaultEffort trap: we always
554
+ // pass an explicit value, so the harness never falls back to a poison
555
+ // default).
556
+ const picked = reasoning.defaultEffort && supported.includes(reasoning.defaultEffort)
557
+ ? reasoning.defaultEffort
558
+ : supported[0];
559
+ if (picked) {
560
+ logger?.warn?.(`dsh-mneme dream: model ${route.provider}:${route.model} does not support effort "${configuredEffort}" (supported: ${supported.join(", ")}); using "${picked}"`);
561
+ return picked;
562
+ }
563
+ return null;
564
+ } catch (error) {
565
+ // Capability query failed — forward the configured value; withEffortFallback
566
+ // still retries on rejection as before.
567
+ logger?.warn?.(`dsh-mneme dream: resolveModelInfo failed (${String(error?.message ?? error)}); forwarding effort as configured`);
568
+ return configuredEffort;
569
+ }
570
+ }
571
+
572
+ /**
573
+ * Resolve the LLM route (Issue #25): an explicit plugin config
574
+ * (dreamProvider/dreamModel) is the user's declared override and wins; the
575
+ * agent default model (deployment) is only a fallback when no config route is
576
+ * set. In a standard DSH install agentDefaultModel always resolves, so without
577
+ * this ordering the config route would be dead code and dreamProvider/dreamModel
578
+ * could never take effect (v0.7.11 regressed this; README §config documents
579
+ * config-first). Falls through to undefined when no route exists — runDream
580
+ * then fails safe. A config→default switch is logged so it is observable.
581
+ */
582
+ function resolveRoute(ctx, config, logger) {
583
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
584
+ try {
585
+ const sel = ctx.agentDefaultModel?.currentSelection?.();
586
+ if (sel?.provider && sel?.model) {
587
+ logger?.info?.("dsh-mneme dream: no dreamProvider/dreamModel config, falling back to agent default");
588
+ return { provider: sel.provider, model: sel.model };
589
+ }
590
+ logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, no config route either");
591
+ } catch (error) {
592
+ logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed: ${String(error)}`);
593
+ }
594
+ return undefined;
595
+ }
596
+
597
+ // ------------------------------------------------------- semantic enhancement
598
+ // Best-effort: any failure here degrades to plain consolidation. The dream
599
+ // path must never be broken by an unavailable embedder/index.
600
+
601
+ /** Backfill + return vectors for every memory; null when impossible. */
602
+ async function collectVectors(memories, semantic) {
603
+ const { embedder, vectorIndex } = semantic;
604
+ if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return null;
605
+ const vectors = new Array(memories.length);
606
+ const missing = [];
607
+ for (let i = 0; i < memories.length; i++) {
608
+ const cached = vectorIndex.getEmbedding?.(memories[i].id);
609
+ if (cached) vectors[i] = cached;
610
+ else missing.push(i);
611
+ }
612
+ if (missing.length) {
613
+ const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
614
+ const rows = await embedder.embed(texts);
615
+ missing.forEach((mi, j) => {
616
+ if (rows[j]?.length) {
617
+ vectors[mi] = rows[j];
618
+ vectorIndex.saveEmbedding(memories[mi].id, rows[j]);
619
+ }
620
+ });
621
+ }
622
+ return vectors.some((v) => !v) ? null : vectors;
623
+ }
624
+
625
+ /**
626
+ * Issue #125:把高相似对聚成**连通分量组**——一个簇 = 一个候选单元。直接按对展开
627
+ * 会把同一簇拆成互相抢占的多个决策(校验器有 one-claim 规则),成组才是正确粒度
628
+ * (与 sleep 冲突阶段的贪心"每记忆每轮最多进一对"同理)。
629
+ * 组内最小相似度用于组间排序:最该处理的簇先入选。
630
+ */
631
+ function similarityGroups(pairs) {
632
+ const parent = new Map();
633
+ const find = (x) => {
634
+ let root = x;
635
+ while (parent.get(root) !== root) root = parent.get(root);
636
+ return root;
637
+ };
638
+ for (const p of pairs) {
639
+ if (!parent.has(p.a.id)) parent.set(p.a.id, p.a.id);
640
+ if (!parent.has(p.b.id)) parent.set(p.b.id, p.b.id);
641
+ const ra = find(p.a.id);
642
+ const rb = find(p.b.id);
643
+ if (ra !== rb) parent.set(ra, rb);
644
+ }
645
+ const byRoot = new Map();
646
+ for (const p of pairs) {
647
+ for (const m of [p.a, p.b]) {
648
+ const root = find(m.id);
649
+ if (!byRoot.has(root)) byRoot.set(root, new Map());
650
+ byRoot.get(root).set(m.id, m);
651
+ }
652
+ }
653
+ return [...byRoot.values()].map((members) => {
654
+ const list = [...members.values()];
655
+ const ids = new Set(list.map((m) => m.id));
656
+ let minSim = 1;
657
+ for (const p of pairs) {
658
+ if (ids.has(p.a.id) && ids.has(p.b.id)) minSim = Math.min(minSim, p.similarity);
659
+ }
660
+ return { members: list, minSim };
661
+ });
662
+ }
663
+
664
+ /**
665
+ * Issue #125:为候选构造收集向量。与 collectVectors 的差别是**允许部分缺失**——
666
+ * 全量库只要有几条嵌入失败就整场返回 null,会让 hybrid 在真实库上几乎永远回落;
667
+ * 拿不到向量的条目只是不参与比较(cosineSimilarity 对非数组返回 0,不会误判)。
668
+ */
669
+ async function collectCandidateVectors(memories, semantic, logger) {
670
+ const { embedder, vectorIndex } = semantic;
671
+ const vectors = new Array(memories.length);
672
+ const missing = [];
673
+ for (let i = 0; i < memories.length; i++) {
674
+ const cached = vectorIndex.getEmbedding?.(memories[i].id);
675
+ if (cached) vectors[i] = cached;
676
+ else missing.push(i);
677
+ }
678
+ if (missing.length) {
679
+ try {
680
+ const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
681
+ const rows = await embedder.embed(texts);
682
+ missing.forEach((mi, j) => {
683
+ if (rows[j]?.length) {
684
+ vectors[mi] = rows[j];
685
+ vectorIndex.saveEmbedding?.(memories[mi].id, rows[j]);
686
+ }
687
+ });
688
+ } catch (error) {
689
+ logger?.warn?.(`[dsh-mneme] dream hybrid vector backfill failed: ${String(error)}`);
690
+ }
691
+ }
692
+ return vectors;
693
+ }
694
+
695
+ /**
696
+ * Issue #125:hybrid 候选成员,按"组内最小相似度"降序展平(高价值簇排前面,
697
+ * 受上限截断时先入选)。同类型比较沿用 findPotentialConflicts;仅当
698
+ * allowCrossTypeMerge 显式开启时再补跨类型高相似对。
699
+ * 任何失败都返回空数组——调用方回落纯窗口,dream 路径绝不因向量层而失败。
700
+ */
701
+ async function hybridCandidateMembers(allMemories, config, semantic, logger) {
702
+ try {
703
+ const vectors = await collectCandidateVectors(allMemories, semantic, logger);
704
+ const minSim = config.dreamCandidateMinSim ?? 0.85;
705
+ const pairs = findPotentialConflicts(allMemories, vectors, minSim);
706
+ if (config.allowCrossTypeMerge === true) {
707
+ for (let i = 0; i < allMemories.length; i++) {
708
+ for (let j = i + 1; j < allMemories.length; j++) {
709
+ if (allMemories[i].type === allMemories[j].type) continue; // 同类型已由上面覆盖
710
+ const sim = cosineSimilarity(vectors[i], vectors[j]);
711
+ if (sim > minSim) pairs.push({ a: allMemories[i], b: allMemories[j], similarity: sim });
712
+ }
713
+ }
714
+ }
715
+ if (pairs.length === 0) return [];
716
+ return similarityGroups(pairs)
717
+ .sort((g1, g2) => g2.minSim - g1.minSim)
718
+ .flatMap((g) => g.members);
719
+ } catch (error) {
720
+ logger?.warn?.(`[dsh-mneme] dream hybrid candidate expansion failed (falling back to window): ${String(error)}`);
721
+ return [];
722
+ }
723
+ }
724
+
725
+ /**
726
+ * Rebuild the vector index after dream decisions so the store and the index
727
+ * stay in sync: merged-away/archived/conflict-loser rows lose their vectors,
728
+ * the merge keeper gets a fresh one.
729
+ */
730
+ export async function maintainIndexAfterDream(decisions, service, semantic) {
731
+ const { embedder, vectorIndex } = semantic;
732
+ if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return;
733
+ const rebuild = new Map();
734
+ for (const d of decisions ?? []) {
735
+ if (d.action === "merge") {
736
+ for (const id of d.ids ?? []) {
737
+ if (id !== d.keepSource) vectorIndex.deleteEmbedding(id);
738
+ }
739
+ if (d.keepSource) {
740
+ const keeper = service.getById(d.keepSource);
741
+ if (keeper) rebuild.set(keeper.id, [keeper.title, keeper.content].filter(Boolean).join("\n"));
742
+ }
743
+ } else if (d.action === "archive" || d.action === "conflict") {
744
+ for (const id of d.ids ?? [d.loser]) vectorIndex.deleteEmbedding(id);
745
+ } else if (d.action === "supersede") {
746
+ // Issue #126 review(Copilot):被取代的一方已归档 → 移除其向量(与 conflict 的
747
+ // loser 同等处置)。winner 正文未变化,向量保持有效。
748
+ vectorIndex.deleteEmbedding(d.loser);
749
+ } else if (d.action === "differentiate") {
750
+ // Issue #126 review(Copilot):双方正文都被追加了差异注记,而 update 在事务内
751
+ // 会因 txDepth>0 跳过 scheduleEmbed —— 不在这里重嵌,注记就进不了 embedding,
752
+ // 注释里承诺的"下一轮不再判成重复"就不成立。
753
+ for (const id of d.ids ?? []) {
754
+ const mem = service.getById(id);
755
+ if (mem) rebuild.set(id, [mem.title, mem.content].filter(Boolean).join("\n"));
756
+ }
757
+ } else if (d.action === "update") {
758
+ const id = d.ids[0];
759
+ const mem = service.getById(id);
760
+ if (mem) {
761
+ vectorIndex.deleteEmbedding(id);
762
+ try {
763
+ const text = [mem.title, mem.content].filter(Boolean).join("\n");
764
+ const v = await embedder.embedSingle(text);
765
+ if (v?.length) vectorIndex.saveEmbedding(id, v);
766
+ } catch { /* best-effort */ }
767
+ }
768
+ }
769
+ }
770
+ for (const [id, text] of rebuild) {
771
+ try {
772
+ const v = await embedder.embedSingle(text);
773
+ if (v?.length) vectorIndex.saveEmbedding(id, v);
774
+ } catch { /* best-effort */ }
775
+ }
776
+ if (embedder.modelHash) vectorIndex.markModel?.(embedder.modelHash, embedder.dimension);
777
+ }
778
+
779
+ // Issue #292:连续失败退避的间隔封顶(30 分钟)。封顶只拦指数「增长」,不把
780
+ // 用户配得比这更大的 dreamMinIntervalMinutes 基数压小(见 effectiveMinIntervalMs)。
781
+ const FAILURE_BACKOFF_CAP_MS = 30 * 60 * 1000;
782
+
783
+ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, minIntervalMs = 0, failureBackoff = false, logger, semantic = null, lastRunAtSeed = 0, baselineSeed = null, peakHours = "", peakMaxDeferMinutes = 120, auditPeakSkip = null, now = () => Date.now(), setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout }) {
784
+ let pendingTimer = null;
785
+ // Issue #239(第 4 项)镜像到巩固:高峰顺延定时器。与 pendingTimer 分开——两者
786
+ // 语义不同(一个是「马上要跑」,一个是「等出高峰再跑」),合成一个变量会让
787
+ // maybeSchedule 的守卫在顺延期间把新的写入触发误当成「已有待跑」而吞掉。
788
+ let deferTimer = null;
789
+ let running = false;
790
+ let disposed = false;
791
+ // Issue #89(基线半边):阈值基线跨重启持久化。baselineSeed 由调用方从
792
+ // dream_runs 读上次成功轮结束时的库规模(store.lastDreamBaseline)——它只活在
793
+ // 闭包内存里时进程重启即归零,而库里记忆远多于阈值,重启后第一条写入就满足
794
+ // overBase、绕过阈值开跑整轮(#291 只补了 lastRunAt 那半边)。缺种子(新库、
795
+ // 升级后还没跑过成功轮)或种子非法时退回 {0,0}:不假装知道基线,行为与升级前
796
+ // 逐字节一致——修的是「知道却不认」,不是凭空造一个基线。
797
+ let baseline = toBaseline(baselineSeed) ?? { count: 0, chars: 0 };
798
+ let inFlight = null;
799
+ // Issue #89(请求 2):上一次实际开跑时刻。失败/degraded 的 run 也占用
800
+ // 最小间隔——节流的目的正是防止失败调用连发;间隔内的触发静默跳过。
801
+ // lastRunAtSeed:调用方从 dream_runs 审计表读出的上次开跑时刻——
802
+ // 内存变量进程重启即归零,闸门对新实例放行 → 重启后立刻连发(#89 根因)。
803
+ let lastRunAt = lastRunAtSeed;
804
+ // Issue #292(#135 派生):同会话内连续失败计数。失败(onRun 抛错或返回
805
+ // ok:false)+1,成功清零;无返回结果的 run(no-op 桩)视为完成且无失败,
806
+ // 不动计数。纯内存变量、宿主重启归零——跨重启的冷却由 lastRunAtSeed(#291)
807
+ // 持久化负责,两者不重叠。
808
+ let consecutiveFailures = 0;
809
+
810
+ // Issue #292:有效最小间隔 = 基数 × 2^连续失败数,封顶 30 分钟。退避关闭或
811
+ // 尚无失败时逐字节返回基数(默认关 = 行为与现状一致)。基数 0 无闸可翻倍
812
+ // (本键不自己产生间隔);封顶取 max(基数, cap),指数再大也不会把用户配的
813
+ // 大基数压小。2^N 溢出成 Infinity 由 Math.min 兜到 cap,无需另设上限位数。
814
+ function effectiveMinIntervalMs() {
815
+ if (!failureBackoff || consecutiveFailures <= 0) return minIntervalMs;
816
+ const cap = Math.max(minIntervalMs, FAILURE_BACKOFF_CAP_MS);
817
+ return Math.min(minIntervalMs * 2 ** consecutiveFailures, cap);
818
+ }
819
+
820
+ function shouldTrigger(service) {
821
+ const { count, chars } = activeStoreSize(service);
822
+ const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
823
+ const overAbs = count >= thresholdCount || chars >= thresholdChars;
824
+ return { trigger: overAbs && overBase, count, chars };
825
+ }
826
+
827
+ function maybeSchedule(service) {
828
+ if (disposed || running || pendingTimer || deferTimer) return false;
829
+ // Issue #89(请求 2):最小触发间隔闸门。#292 退避开启时改用指数放大的
830
+ // 有效间隔:连续失败越多,下次放行越晚(恒定失败的模型不再按固定节奏连发,
831
+ // 只会越打越稀)。失败 run 本就占用间隔(lastRunAt 在开跑时刷新,见 #89),
832
+ // 这里放大的是同一道闸,不新增任何状态面。间隔内的触发静默跳过:没有调用
833
+ // 发生,也就没有可审计的对象(与 #89 口径一致,不写审计行)。
834
+ if (minIntervalMs > 0 && now() - lastRunAt < effectiveMinIntervalMs()) return false;
835
+ const { trigger, count, chars } = shouldTrigger(service);
836
+ if (!trigger) return false;
837
+ // Issue #239(第 4 项,错峰队列)镜像到巩固:命中高峰就不调模型。与蒸馏的差别
838
+ // 在于巩固是**全局单实例**(蒸馏按会话各挂一个定时器),所以这里只需要一个
839
+ // deferTimer,且不需要 deferredRuns 那套按会话去重。
840
+ // baseline 刻意不刷新:阈值继续累积,留到非高峰一次性巩固(一次大 run 比多次
841
+ // 小 run 省)。审计只登记一行 skip——「为什么不再做梦了」必须对用户可观测。
842
+ if (isInPeakWindow(new Date(now()), peakHours)) {
843
+ try {
844
+ auditPeakSkip?.({ count, chars });
845
+ } catch (error) {
846
+ // 记账是 best-effort:写审计行失败只 warn,绝不反噬调度本身。
847
+ logger?.warn?.(`dsh-mneme dream: peak-hours audit failed: ${String(error)}`);
848
+ }
849
+ scheduleDeferredRun(service);
850
+ return false;
851
+ }
852
+ pendingTimer = setTimeoutFn(() => {
853
+ pendingTimer = null;
854
+ startRun(service);
855
+ }, delayMs);
856
+ return true;
857
+ }
858
+
859
+ /**
860
+ * Issue #239:高峰内择时补跑——挂到「距当前最近的一个高峰结束时刻」,被
861
+ * peakMaxDeferMinutes 截断时到点照跑(bypassPeak),长高峰不会把巩固饿死。
862
+ * 定时器 unref:不阻止宿主退出。重复触发不叠加(deferTimer 已在 maybeSchedule
863
+ * 的守卫里,这里再判一次以防从其它路径进来)。
864
+ */
865
+ function scheduleDeferredRun(service) {
866
+ if (disposed || deferTimer) return;
867
+ const at = nextOffPeakAt(new Date(now()), peakHours);
868
+ if (!at) return;
869
+ const maxDeferMs = (peakMaxDeferMinutes ?? 0) * 60000;
870
+ let delay = Math.max(0, at.getTime() - now());
871
+ const capped = maxDeferMs > 0 && delay > maxDeferMs;
872
+ if (capped) delay = maxDeferMs;
873
+ deferTimer = setTimeoutFn(() => {
874
+ deferTimer = null;
875
+ if (disposed) return;
876
+ // 截断放行时仍在高峰:不再重新顺延(否则长高峰里会无限顺延,等于把巩固
877
+ // 关掉)。直接开跑,与蒸馏的 bypassPeak 同口径。
878
+ if (!capped && isInPeakWindow(new Date(now()), peakHours)) {
879
+ // 理论上到点已出高峰;时钟跳变/时段串被改小可能落回高峰内,此时再顺延一次。
880
+ scheduleDeferredRun(service);
881
+ return;
882
+ }
883
+ logger?.info?.(`dsh-mneme dream: peak-hours deferred run firing (capped=${capped}, delayMs=${delay})`);
884
+ startRun(service);
885
+ }, delay);
886
+ deferTimer.unref?.();
887
+ }
888
+
889
+ /**
890
+ * 真正开跑。抽出来是因为两条路径都要用:写入触发的正常路径,与高峰顺延后的
891
+ * 补跑路径。onRun 的调用刻意放在 Promise 里——同步抛出的异常若逃出 timer 回调
892
+ * 会直接崩掉进程并跳过收尾。inFlight 让 dispose() 能等完这一轮再关库。
893
+ */
894
+ function startRun(service) {
895
+ running = true;
896
+ lastRunAt = now();
897
+ inFlight = Promise.resolve()
898
+ .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
899
+ .then((result) => {
900
+ // Refresh the baseline only for a successful run (design §5.3: an
901
+ // LLM failure must not move the baseline, so the next write can
902
+ // immediately re-trigger a retry). A `{ok:false}` result or a throw
903
+ // keeps the old baseline. A run that reports nothing is treated as
904
+ // completed without failure (no-op hooks / minimal test doubles).
905
+ if (result && result.ok) {
906
+ consecutiveFailures = 0; // Issue #292:成功清零,下次触发回到基数间隔
907
+ try {
908
+ // Issue #89(基线半边):run 自报的基线(与审计行同一份数字)优先——重启
909
+ // 播种读的就是它,两条路径共用唯一口径;no-op 桩不回这个字段时退回现场
910
+ // 计算,最小测试替身的行为逐字节不变。
911
+ baseline = toBaseline(result.baseline) ?? shouldTrigger(service);
912
+ } catch (error) {
913
+ // Store closed mid-flight: keep the last known baseline.
914
+ logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
915
+ }
916
+ } else if (result) {
917
+ // Issue #292:ok:false(LLM 失败 / 空体 / 整单拒绝)计入连败;degraded
918
+ // 的 run 走 ok:true(LLM 本身成功了,只是决策被部分应用)→ 算成功、清零。
919
+ // 退避关闭时该计数没有消费者,行为与此前逐字节一致。
920
+ consecutiveFailures += 1;
921
+ }
922
+ // result 为空(no-op 桩 / 最小测试替身)=完成且无失败:基线与连败计数都不动。
923
+ })
924
+ .catch((error) => {
925
+ logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
926
+ // Failed runs do not refresh the baseline.
927
+ consecutiveFailures += 1; // Issue #292:抛错同样计入连败
928
+ })
929
+ .finally(() => {
930
+ running = false;
931
+ inFlight = null;
932
+ });
933
+ }
934
+
935
+ async function dispose() {
936
+ disposed = true;
937
+ if (pendingTimer) { clearTimeoutFn(pendingTimer); pendingTimer = null; }
938
+ // Issue #239:高峰顺延定时器同样要清,否则进程关闭后仍会触发一次巩固。
939
+ if (deferTimer) { clearTimeoutFn(deferTimer); deferTimer = null; }
940
+ // An in-flight run is left to complete naturally (its LLM calls are
941
+ // already paid for and aborting would discard the work). Await it so the
942
+ // caller can close the store only after every write has landed.
943
+ if (inFlight) await inFlight.catch(() => {});
944
+ }
945
+
946
+ async function runDream(ctx, service, config) {
947
+ const language = langOf(config);
948
+ const logger = ctx.logger;
949
+ let memories = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
950
+ if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
951
+ // Issue #89:开跑时刻既喂给审计行(created_at),也是调度器闸门的时间基准。
952
+ const dreamStartedAt = Date.now();
953
+ // v0.4.4 滑动窗口:只 consolidation 最近 dreamMaxSnapshotSize 条记忆,
954
+ // 窗口外的旧记忆不进 snapshot(大记忆量下全量快照会撑爆 LLM 输入,配合
955
+ // 隐式 keep 让 run 始终可收敛)。按 updated_at 倒序取前 maxSize 条。
956
+ const maxSize = Number.isInteger(config.dreamMaxSnapshotSize) ? config.dreamMaxSnapshotSize : 200;
957
+ const windowMemories = [...memories]
958
+ .sort((a, b) => {
959
+ const ta = String(a.updated_at ?? "");
960
+ const tb = String(b.updated_at ?? "");
961
+ if (ta < tb) return 1;
962
+ if (ta > tb) return -1;
963
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
964
+ })
965
+ .slice(0, Math.max(1, maxSize));
966
+ // Issue #125:hybrid 档在窗口之外并入向量翻出的高相似组。候选**总量**仍由
967
+ // maxSize(或显式 dreamCandidateMax)封顶、与库总量解耦——用"按相似度取候选"
968
+ // 替代"调大窗口",输入成本才不随库增长。封顶截断时向量组优先于窗口尾部,
969
+ // 否则"该合并的一对"仍会被时间窗挤掉。
970
+ let selected = windowMemories;
971
+ if ((config.dreamCandidateMode ?? "window") === "hybrid" && semantic?.embedder && semantic?.vectorIndex) {
972
+ const extra = await hybridCandidateMembers(memories, config, semantic, logger);
973
+ if (extra.length > 0) {
974
+ const cap = Math.max(
975
+ Math.max(1, maxSize),
976
+ Number.isInteger(config.dreamCandidateMax) && config.dreamCandidateMax > 0 ? config.dreamCandidateMax : 0
977
+ );
978
+ const merged = [];
979
+ const seen = new Set();
980
+ for (const m of [...extra, ...windowMemories]) {
981
+ if (seen.has(m.id)) continue;
982
+ seen.add(m.id);
983
+ merged.push(m);
984
+ if (merged.length >= cap) break;
985
+ }
986
+ selected = merged;
987
+ logger?.info?.(`[dsh-mneme] dream hybrid candidates: ${merged.length} (window ${windowMemories.length}, vector ${extra.length}, cap ${cap})`);
988
+ }
989
+ }
990
+ memories = selected;
991
+ const snapshot = new Map(memories.map((m) => [m.id, m]));
992
+ const route = resolveRoute(ctx, config, logger);
993
+ const runId = randomUUID();
994
+ const snapshotHash = hashSnapshot([...snapshot.values()]);
995
+ // Conflict freeze (opt-in): when enabled, conflict decisions are parked for
996
+ // manual review instead of auto-adjudicated. Read once up front so the
997
+ // prompt hint and the apply-split agree on the same gate.
998
+ const freezeEnabled = config.conflictFreezeEnabled === true;
999
+ // Every exit (success or failure) funnels through `finish`, which writes
1000
+ // the audit row + receipt. A record failure is logged, never thrown —
1001
+ // auditing must not break the consolidation path. Failed runs still
1002
+ // capture their decisions/outcome when the LLM produced a validated list
1003
+ // (e.g. summary step failed after consolidation), so the partial write is
1004
+ // replayable too.
1005
+ const finish = (result) => {
1006
+ // status is derived from what actually committed: ok only when the full
1007
+ // decision list landed (or a summary was refreshed); noop when nothing
1008
+ // changed; degraded when real changes landed without a summary;
1009
+ // reconcile when decisions were validated but some did not commit (CAS
1010
+ // conflict / rollback); failed on any LLM/validation error. No fake "ok"
1011
+ // for an empty or partial run.
1012
+ const status = result.status ?? (result.ok ? "ok" : "failed");
1013
+ const applied = result.applied ?? 0;
1014
+ const summaryStored = result.summary ?? false;
1015
+ const receipt = buildReceipt({ runId, status, snapshotHash, inputCount: snapshot.size, applied, summaryStored });
1016
+ // Issue #89(基线半边):成功轮把「本轮结束后的库规模」落进审计行 = 阈值基线的
1017
+ // 持久化副本,重启后由 store.lastDreamBaseline 播种。判定条件必须与调度器刷新
1018
+ // 基线的条件严格一致(result.ok)——非 ok 轮不推进基线是既有语义,若这里也落值,
1019
+ // 重启后播种就会拿到一个「其实没推进过」的假基线,阈值反而被抬高。
1020
+ // 取不到(库已关闭等)就落 NULL:宁可不持久化,也不写一个错的基线。
1021
+ let baselineSnapshot = null;
1022
+ if (result.ok) {
1023
+ try {
1024
+ baselineSnapshot = activeStoreSize(service);
1025
+ } catch {
1026
+ baselineSnapshot = null;
1027
+ }
1028
+ }
1029
+ try {
1030
+ service.saveDreamRun({
1031
+ id: runId,
1032
+ // Issue #89:审计行记开跑时刻而非完成时刻——lastDreamRunAt 以它做
1033
+ // 重启后的间隔种子,落完成时刻会让 run 耗时白白计入下一轮最小间隔。
1034
+ created_at: new Date(dreamStartedAt).toISOString(),
1035
+ status,
1036
+ error: result.error,
1037
+ provider: route?.provider,
1038
+ model: route?.model,
1039
+ snapshot_hash: snapshotHash,
1040
+ input_count: snapshot.size,
1041
+ // 裁决规则版本号:config.policyEpoch(默认 0)。规则升级后该行保留
1042
+ // 当时的 epoch,旧裁决据此降级为历史证据(store 层 getLatestPolicyEpoch
1043
+ // 只负责读取当前生效版本,写入由这里完成)。
1044
+ policy_epoch: config.policyEpoch ?? 0,
1045
+ // Full input snapshot (canonical fields) so the exact arbitration
1046
+ // input can be rebuilt offline from the audit row alone — the
1047
+ // digest + decisions + outcome triple makes silent errors locatable
1048
+ // even after the store has moved on.
1049
+ input: [...snapshot.values()].map((m) => ({
1050
+ id: m.id,
1051
+ type: m.type,
1052
+ title: m.title,
1053
+ content: m.content,
1054
+ importance: m.importance,
1055
+ updated_at: m.updated_at
1056
+ })),
1057
+ decisions: result.decisions,
1058
+ outcome: result.outcome,
1059
+ applied,
1060
+ summary_stored: summaryStored,
1061
+ receipt,
1062
+ // Issue #104:degraded(合法子集已应用)轮被跳过的决策明细。写成独立字段
1063
+ // 而非内联进 decisions——degraded 的 decisions 是合法子集,下游按「决策
1064
+ // 数组」消费,内联标记会污染其它读者(失败轮的 _validationFailed 是整单
1065
+ // 拒绝哨兵,语义与「部分应用」不同,也不复用)。
1066
+ skipped: result.skipped,
1067
+ // Issue #89(基线半边):成功的 run 才带这两个值(见上方 baselineSnapshot
1068
+ // 的注释)。两列要么同时有值、要么同时为 NULL,读侧以「同时有值」认账。
1069
+ store_count: baselineSnapshot?.count,
1070
+ store_chars: baselineSnapshot?.chars
1071
+ });
1072
+ } catch (error) {
1073
+ logger?.warn?.(`dsh-mneme dream: failed to record audit run: ${String(error)}`);
1074
+ }
1075
+ // Issue #89(基线半边):把「与审计行同一份数字」的基线回给调度器,两条路径
1076
+ // (进程内刷新 / 跨重启播种)因此共享唯一口径;调度器拿不到时会退出现场计算。
1077
+ return { ...result, runId, receipt, snapshotHash, baseline: baselineSnapshot ?? undefined };
1078
+ };
1079
+ if (!route) {
1080
+ logger?.warn?.("dsh-mneme dream: no llm route available");
1081
+ return finish({ ok: false, error: "no llm route", summary: false });
1082
+ }
1083
+
1084
+ let listText;
1085
+ if (semantic?.embedder && semantic?.vectorIndex) {
1086
+ try {
1087
+ const vectors = await collectVectors(memories, semantic);
1088
+ if (vectors) {
1089
+ const k = Math.min(10, Math.max(1, Math.floor(Math.sqrt(memories.length / 2))));
1090
+ const clusters = clusterMemories(memories, vectors, k);
1091
+ const conflicts = findPotentialConflicts(memories, vectors, 0.85);
1092
+ const conflictIds = new Set(conflicts.flatMap((c) => [c.a.id, c.b.id]));
1093
+ const parts = [];
1094
+ clusters.forEach((cluster, ci) => {
1095
+ parts.push(STR.clusterHeader[language](ci + 1));
1096
+ for (const m of cluster) {
1097
+ parts.push(
1098
+ `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}` +
1099
+ (conflictIds.has(m.id) ? STR.conflictMark[language] : "")
1100
+ );
1101
+ }
1102
+ });
1103
+ listText = parts.join("\n");
1104
+ logger?.info?.(`[dsh-mneme] dream semantic pre-group: ${clusters.length} clusters, ${conflicts.length} conflict pairs`);
1105
+ }
1106
+ } catch (error) {
1107
+ logger?.warn?.(`[dsh-mneme] dream semantic pre-group failed: ${String(error)}`);
1108
+ }
1109
+ }
1110
+ if (!listText) {
1111
+ listText = [...snapshot.values()].map((m) =>
1112
+ `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
1113
+ ).join("\n");
1114
+ }
1115
+
1116
+ // Freeze-aware prompt: in freeze mode the conflict branch still outputs
1117
+ // winner/loser (validation requires them) but they are treated as tentative
1118
+ // candidates — the human makes the final call, not the model.
1119
+ const consolidationPrompt = freezeEnabled
1120
+ ? STR.prompts.consolidation[language] + STR.prompts.freezeSuffix[language]
1121
+ : STR.prompts.consolidation[language];
1122
+ let decisionText;
1123
+ // 加固(v0.8.1):配置的 reasoningEffort 被 provider 拒收时回退重试一次
1124
+ // (不带该字段),避免 thinking 模型配置 low/medium 直接整单失败。解析放
1125
+ // 在 auditError 检查器里、闭包交回主流程,避免二次解析;解析失败同时如实
1126
+ // 记 audit error 并在日志带原始输出前 300 字节,便于定位"推理吞预算返回空体"。
1127
+ const effort = await resolveDreamEffort(ctx, route, config.dreamReasoningEffort, logger);
1128
+ let decisions = null;
1129
+ let streamFailure = "";
1130
+ const runConsolidation = (withEffort) => {
1131
+ streamFailure = "";
1132
+ return runAuditedLlm(ctx, service, config, {
1133
+ triggerSource: "autoDream",
1134
+ operationType: "dream_consolidate",
1135
+ modelId: `${route.provider}:${route.model}`,
1136
+ relatedMemoryIds: [...snapshot.keys()],
1137
+ streamError: () => streamFailure,
1138
+ auditError: (text) => {
1139
+ decisions = extractJsonArray(text);
1140
+ return Array.isArray(decisions) ? null : "no json array in llm output";
1141
+ }
1142
+ }, (reportUsage) => streamText(ctx, {
1143
+ provider: route.provider,
1144
+ model: route.model,
1145
+ purpose: "compaction",
1146
+ maxTokens: config.dreamMaxTokens ?? 4096,
1147
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
1148
+ messages: [
1149
+ { role: "system", content: [{ type: "text", text: consolidationPrompt }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
1150
+ { role: "user", content: [{ type: "text", text: listText }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
1151
+ ]
1152
+ }, reportUsage, (reason) => { streamFailure = describeStreamFailure(reason); }));
1153
+ };
1154
+ try {
1155
+ // Bug8: the consolidation call is audited (tokens/time/status). A throw
1156
+ // re-propagates to the catch below; an aborted stream returns undefined
1157
+ // and is treated as a failed run after the check below.
1158
+ decisionText = await withEffortFallback(ctx, effort, () => runConsolidation(true), () => runConsolidation(false), () => streamFailure);
1159
+ } catch (error) {
1160
+ logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
1161
+ return finish({ ok: false, error: "llm failed", summary: false });
1162
+ }
1163
+ if (decisionText === undefined) {
1164
+ logger?.warn?.(`dsh-mneme dream: consolidation llm stream aborted or errored${streamFailure ? ` (${streamFailure})` : ""}`);
1165
+ return finish({ ok: false, error: "llm failed", summary: false });
1166
+ }
1167
+ if (!Array.isArray(decisions)) {
1168
+ const head = (decisionText ?? "").slice(0, 300).replace(/\s+/g, " ").trim();
1169
+ logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0}; head: ${head})`);
1170
+ return finish({ ok: false, error: "no json array in llm output", summary: false });
1171
+ }
1172
+ const { ok, errors, skipped, resolvedShortIds, coverageShortfall } = validateDecisions(decisions, snapshot, {
1173
+ maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
1174
+ // Issue #104 方向 2:archive 批量上限(全局闸门,超限整单拒绝)。
1175
+ maxArchivePerRun: config.dreamMaxArchivePerRun,
1176
+ // #135 成本审计派生:merge 批量上限(merge 是唯一回吐正文的动作,同款全局闸门)。
1177
+ maxMergePerRun: config.dreamMaxMergePerRun,
1178
+ minAgeHours: config.reflectionUpdateMinAgeHours,
1179
+ // v0.4.4 fix:显式透传,用户配 dreamImplicitKeep:false 时严格模式必须
1180
+ // 真正生效,dreamMinExplicitCoverage 决定隐式 keep 下的覆盖率下限。
1181
+ dreamImplicitKeep: config.dreamImplicitKeep,
1182
+ dreamMinExplicitCoverage: config.dreamMinExplicitCoverage,
1183
+ // Issue #89:v0.6.9(Issue #26)的宽容路径在 v0.7.11 重写中丢失——单条
1184
+ // 非法决策重新只跳过该条、合法子集照常应用(run 记为 degraded)。
1185
+ skipInvalid: config.dreamSkipInvalid !== false,
1186
+ allowCrossTypeMerge: config.allowCrossTypeMerge === true,
1187
+ // issue #339 / E8:guarded 类型 merge 护栏(默认开,dreamMergeGuard)。
1188
+ mergeGuard: config.dreamMergeGuard === true
1189
+ });
1190
+ // Issue #135:模型把 UUID 缩写成前缀时,唯一前缀已在校验前被解析回完整 id。
1191
+ // 解析量是模型输出质量的一个直接信号(>0 意味着模型在缩写 id),记一条 info
1192
+ // 便于事后从日志侧观察该行为的分布。
1193
+ if (resolvedShortIds > 0) {
1194
+ logger?.info?.(`[dsh-mneme] dream: resolved ${resolvedShortIds} short id prefix(es) to full ids`);
1195
+ }
1196
+ if (!ok) {
1197
+ // Issue #135(观测缺口):失败轮的逐条校验明细此前既不落库也基本不可见——
1198
+ // skipped 的 warn 写在 return 之后(失败路径到不了),dream_runs.decisions
1199
+ // 落 NULL,上百轮失败零现场。这里把明细前置到日志,并把
1200
+ // { _validationFailed, errors, skipped } 随失败行持久化,事后可从审计行
1201
+ // 直接定位「模型输出了什么、为何逐条非法」。
1202
+ logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
1203
+ if (skipped.length > 0) {
1204
+ logger?.warn?.(`dsh-mneme dream: ${skipped.length} invalid decision(s) skipped: ${skipped.map((s) => `decision[${s.index}]: ${s.error}`).join("; ")}`);
1205
+ }
1206
+ return finish({
1207
+ ok: false,
1208
+ error: `invalid decisions: ${errors.length} errors`,
1209
+ summary: false,
1210
+ decisions: [{ _validationFailed: true, errors, skipped }]
1211
+ });
1212
+ }
1213
+ const skippedInvalid = skipped.length > 0;
1214
+ if (skippedInvalid) {
1215
+ logger?.warn?.(`dsh-mneme dream: ${skipped.length} invalid decision(s) skipped (run degrades): ${skipped.map((s) => s.error).join("; ")}`);
1216
+ }
1217
+ // Issue #104 方向 1:覆盖率不足降级为 degraded(不再整单拒绝)——合法子集
1218
+ // 照常应用、未提及条目隐式 keep,理由随 outcome.degradations 落库供离线定位。
1219
+ const coverageDegraded = typeof coverageShortfall === "string" && coverageShortfall.length > 0;
1220
+ if (coverageDegraded) {
1221
+ logger?.warn?.(`dsh-mneme dream: ${coverageShortfall} (run degrades: valid subset applied, unclaimed ids kept implicitly)`);
1222
+ }
1223
+
1224
+ // Capture pre-update snapshots so the audit records what each update changed.
1225
+ const updateSnapshots = {};
1226
+ for (const d of decisions) {
1227
+ if (d.action === "update") {
1228
+ const mem = snapshot.get(d.ids[0]);
1229
+ if (mem) updateSnapshots[d.ids[0]] = { title: mem.title, content: mem.content, importance: mem.importance };
1230
+ }
1231
+ }
1232
+
1233
+ // Conflict freeze (opt-in): when enabled, conflict decisions are not
1234
+ // auto-adjudicated — no winner kept, no loser archived. The pair is parked
1235
+ // in conflict_pending for human review instead. Best-effort: a store
1236
+ // failure here must never block the run (fail-safe — the memories are left
1237
+ // untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
1238
+ // bounds the review queue; overflow is skipped with a warning.
1239
+ let frozenCount = 0;
1240
+ const frozenIds = [];
1241
+ // v0.8.1(issue #170 复核项 3):跨 scope 的 conflict 决策两种模式都一律
1242
+ // 停车人工裁决、绝不自动归档——否则普通 dream 的 LLM 能归档别的 scope 的
1243
+ // 唯一副本,sleep 路径(scope-candidate-queue)的保护在这里缺位。同 scope
1244
+ // 的 conflict 决策照旧:freeze 停车 / 非 freeze 自动裁决。
1245
+ const isCrossScopeDecision = (d) => {
1246
+ const a = snapshot.get(d.winner);
1247
+ const b = snapshot.get(d.loser);
1248
+ return !!a && !!b && (
1249
+ scopeKeyOf(a.agent_scope) !== scopeKeyOf(b.agent_scope)
1250
+ || scopeKeyOf(a.workspace_scope) !== scopeKeyOf(b.workspace_scope)
1251
+ );
1252
+ };
1253
+ const applyList = freezeEnabled
1254
+ ? decisions.filter((d) => d.action !== "conflict")
1255
+ : decisions.filter((d) => d.action !== "conflict" || !isCrossScopeDecision(d));
1256
+ if (freezeEnabled) {
1257
+ const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
1258
+ if (conflictsToFreeze.length > 0) {
1259
+ try {
1260
+ const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
1261
+ const pendingNow = service.countConflictPending();
1262
+ const budget = Math.max(0, maxPending - pendingNow);
1263
+ const toFreeze = conflictsToFreeze.slice(0, budget);
1264
+ if (conflictsToFreeze.length > budget) {
1265
+ logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
1266
+ }
1267
+ for (const d of toFreeze) {
1268
+ try {
1269
+ // 返回 undefined = 该对已被人工裁决且两侧内容未变(issue #170 复核
1270
+ // 项 4:内容变了才重新入队)——不算停车、不进 frozenIds。
1271
+ const parked = service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
1272
+ if (parked == null) continue;
1273
+ frozenCount++;
1274
+ frozenIds.push(d.winner, d.loser);
1275
+ } catch (error) {
1276
+ logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
1277
+ }
1278
+ }
1279
+ } catch (error) {
1280
+ logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
1281
+ }
1282
+ }
1283
+ } else {
1284
+ // 非 freeze:跨 scope conflict 停车(绝不进 applyDecisions)。带专属
1285
+ // reason + 模型给出的裁决理由,队列里读起来是「归属裁决」而非重复项。
1286
+ const crossScope = decisions.filter((d) => d.action === "conflict" && isCrossScopeDecision(d));
1287
+ for (const d of crossScope) {
1288
+ try {
1289
+ const parked = service.saveConflictPending({
1290
+ run_id: runId,
1291
+ memory_a: d.winner,
1292
+ memory_b: d.loser,
1293
+ reason: STR.scopeConflictParkReason[language](d.reason)
1294
+ });
1295
+ if (parked != null) {
1296
+ frozenCount++;
1297
+ frozenIds.push(d.winner, d.loser);
1298
+ }
1299
+ } catch (error) {
1300
+ logger?.warn?.(`dsh-mneme dream: failed to park cross-scope conflict ${d.winner}/${d.loser}: ${String(error)}`);
1301
+ }
1302
+ }
1303
+ if (crossScope.length > 0) {
1304
+ logger?.info?.(`[dsh-mneme] dream: parked ${crossScope.length} cross-scope conflict(s) for human ownership review`);
1305
+ }
1306
+ }
1307
+
1308
+ // CAS-guarded, per-decision-transactional apply against the run snapshot:
1309
+ // a target changed during the LLM call is skipped and reported as a
1310
+ // conflict instead of being overwritten (item ①). Frozen conflicts are
1311
+ // excluded from this list (they are parked, not applied).
1312
+ const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot, config);
1313
+ // Per-record receipt chain: one row per actually-committed merge/conflict/
1314
+ // update verdict, stamped with the decision-basis digest + idempotency
1315
+ // counters (count_before → count_after). Written here, before the run audit
1316
+ // row, so the verdict trail always precedes the run trail it belongs to.
1317
+ // Bookkeeping: a write failure is logged and swallowed — it must never
1318
+ // block the consolidation flow.
1319
+ try {
1320
+ for (const r of buildRecordReceipts({ runId, committed, snapshot, policyEpoch: config.policyEpoch ?? 0 })) {
1321
+ service.saveReceipt(r);
1322
+ }
1323
+ } catch (error) {
1324
+ logger?.warn?.(`dsh-mneme dream: failed to write per-record receipt: ${String(error)}`);
1325
+ }
1326
+ // Attach the pre-update snapshot to the audit copy of each update decision
1327
+ // so the recorded row shows the before/after delta, not just the target.
1328
+ const auditDecisions = decisions.map((d) =>
1329
+ d.action === "update" && updateSnapshots[d.ids[0]]
1330
+ ? { ...d, _before: updateSnapshots[d.ids[0]] }
1331
+ : d
1332
+ );
1333
+ // Outcome is derived from the ACTUALLY committed sub-steps, never from the
1334
+ // raw LLM decision list — a merge whose archive step rolled back must not
1335
+ // claim "merge-archived" (item ②). Conflicts/failures ride along so the
1336
+ // audit row records why the run diverged.
1337
+ const outcome = { ...buildOutcome(committed), conflicts, failures };
1338
+ if (coverageDegraded) outcome.degradations = [coverageShortfall];
1339
+ // Frozen conflicts were not adjudicated: mark both sides pending in the
1340
+ // per-id outcome so the audit row shows they were parked, not skipped.
1341
+ if (frozenIds.length) {
1342
+ for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
1343
+ }
1344
+ // Decisions validated but not fully committed → reconcile (not ok).
1345
+ const partial = conflicts.length > 0 || failures.length > 0;
1346
+ // No decision landed (all-keep, or every decision skipped as an idempotent
1347
+ // replay) → nothing substantive changed. Distinct from a success: such a
1348
+ // run must never be reported as ok, or the audit claims work that never
1349
+ // happened and the scheduler refreshes the baseline on a false positive.
1350
+ // Frozen conflicts are substantive output (parked for review), so a run
1351
+ // that only froze conflicts is not a noop.
1352
+ const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
1353
+
1354
+ // Keep the vector index consistent with the post-dream store state.
1355
+ if (semantic?.embedder && semantic?.vectorIndex) {
1356
+ try {
1357
+ await maintainIndexAfterDream(applyList, service, semantic);
1358
+ } catch (error) {
1359
+ logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
1360
+ }
1361
+ }
1362
+
1363
+ // Summary generation (second LLM call). A throwing stream is reported as
1364
+ // a failed run; summary:false marks a run that produced no summary.
1365
+ let summaryText;
1366
+ let summaryStreamFailure = "";
1367
+ const runSummary = (withEffort) => {
1368
+ summaryStreamFailure = "";
1369
+ // Issue #258:总览阶段可用 dreamSummaryProvider/dreamSummaryModel 走独立路由
1370
+ //(默认空 = 沿用 dream 路由);输入侧有 dreamSummaryMaxInputs 硬上限,
1371
+ // 按窗口同款 updated_at 倒序保留最新的(见下方 summaryInputs)。
1372
+ const summaryRoute = (config.dreamSummaryProvider && config.dreamSummaryModel)
1373
+ ? { provider: config.dreamSummaryProvider, model: config.dreamSummaryModel }
1374
+ : route;
1375
+ return runAuditedLlm(ctx, service, config, {
1376
+ triggerSource: "autoDream",
1377
+ operationType: "dream_summarize",
1378
+ modelId: `${summaryRoute.provider}:${summaryRoute.model}`,
1379
+ relatedMemoryIds: [],
1380
+ streamError: () => summaryStreamFailure
1381
+ }, (reportUsage) => streamText(ctx, {
1382
+ provider: summaryRoute.provider,
1383
+ model: summaryRoute.model,
1384
+ purpose: "compaction",
1385
+ maxTokens: config.dreamMaxTokens ?? 2048,
1386
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
1387
+ messages: [
1388
+ { role: "system", content: [{ type: "text", text: STR.prompts.dreamSummary[language] }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } },
1389
+ { role: "user", content: [{ type: "text", text: summaryInputs.map((m) => `- ${m.title}: ${m.content}`).join("\n") }], source: { kind: "plugin:dsh-mneme", plugin: "dsh-mneme" } }
1390
+ ]
1391
+ }, reportUsage, (reason) => { summaryStreamFailure = describeStreamFailure(reason); }));
1392
+ };
1393
+ // Resident status bar (#164 alignment): the overview is THE one resident
1394
+ // narrative — summary tier 0, refreshed every run via _overwrite (supersede
1395
+ // v1, content_history traceable). Its 口径 (what snapshot produced it) is
1396
+ // stamped into the content so the standing answer is always auditable; the
1397
+ // formal evidence column lands with the narrative-bars batch.
1398
+ // Issue #258:输入硬上限(条数)——原全库无界,把 dream 路由指向小 ctx
1399
+ // 模型时 120k token 当场 CONTEXT_WINDOW_EXCEEDED(#258 实测),且随库增长
1400
+ // 渐进恶化。倒序排序与 consolidate 窗口同款(updated_at desc, id tiebreak),
1401
+ // 保留最新的;0 = 关闭上限(回归全库行为,调用方自担 ctx)。
1402
+ // #230:document 指针行不进总览(与 dream/sleep 五个候选池的同款排除)。
1403
+ const summaryAll = service.all().filter((m) => !m.archived && m.type !== "summary" && m.type !== "document");
1404
+ const summaryMaxInputs = Number.isInteger(config.dreamSummaryMaxInputs) ? config.dreamSummaryMaxInputs : 0;
1405
+ const summaryInputs = summaryMaxInputs > 0 && summaryAll.length > summaryMaxInputs
1406
+ ? [...summaryAll]
1407
+ .sort((a, b) => {
1408
+ const ta = String(a.updated_at ?? "");
1409
+ const tb = String(b.updated_at ?? "");
1410
+ if (ta < tb) return 1;
1411
+ if (ta > tb) return -1;
1412
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
1413
+ })
1414
+ .slice(0, summaryMaxInputs)
1415
+ : summaryAll;
1416
+
1417
+ const summaryScope = STR.summaryScope[language](
1418
+ summaryInputs.length,
1419
+ runId.slice(0, 8),
1420
+ new Date().toISOString().slice(0, 10)
1421
+ );
1422
+ try {
1423
+ // Bug8: the summary call is audited too (operation dream_summarize).
1424
+ summaryText = await withEffortFallback(ctx, effort, () => runSummary(true), () => runSummary(false), () => summaryStreamFailure);
1425
+ } catch (error) {
1426
+ logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
1427
+ return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
1428
+ }
1429
+ let summaryStored = false;
1430
+ if (summaryText !== undefined && summaryText.trim()) {
1431
+ // Bug5 carve-out: the library overview is regenerated every run, so it
1432
+ // must REPLACE the previous overview (not append — that would grow the
1433
+ // summary unboundedly). `_overwrite` still archives the old overview into
1434
+ // content_history before replacing it. Content carries the snapshot-scope
1435
+ // footer computed above — the resident bar states its own 口径.
1436
+ service.saveWithDedupe({ type: "summary", title: STR.summaryTitle[language], content: `${summaryText.trim()}${summaryScope}`, importance: 5, source: "dream", _overwrite: true });
1437
+ summaryStored = true;
1438
+ // Re-embed the fresh summary so the index stays in sync with the store.
1439
+ if (semantic?.embedder && semantic?.vectorIndex) {
1440
+ try {
1441
+ // source="dream" 限定:叙述条(source=narrative)同为 summary 类型,
1442
+ // 不加限定时 find 可能截胡,把总览的 re-embed 花在叙述条上。
1443
+ const summary = service.all().find((m) => m.type === "summary" && m.source === "dream");
1444
+ if (summary) await reEmbedMemory(semantic, summary, logger);
1445
+ } catch { /* best-effort */ }
1446
+ }
1447
+ }
1448
+ // Narrative bars (#164 alignment, opt-in dreamNarrativeEnabled): per-topic
1449
+ // on-demand narratives after consolidation + summary. Additive phase —
1450
+ // failures degrade to zero narratives, never break the run.
1451
+ let narrativesStored = 0;
1452
+ if (config.dreamNarrativeEnabled === true) {
1453
+ try {
1454
+ narrativesStored = await generateNarratives({ ctx, service, config, route, language, effort, semantic, logger });
1455
+ } catch (error) {
1456
+ logger?.warn?.(`dsh-mneme dream: narrative phase failed: ${String(error)}`);
1457
+ }
1458
+ }
1459
+
1460
+ // Honest status assignment (never a fake ok):
1461
+ // reconcile — some decisions validated but did not commit (CAS/rollback).
1462
+ // noop — nothing changed and no summary persisted: truly an empty
1463
+ // run. ok:false keeps the scheduler from moving the baseline.
1464
+ // ok — either real changes landed, or a fresh summary was stored
1465
+ // (all-keep + summary is a substantive summary refresh).
1466
+ // degraded — real consolidation landed but the run did not produce its
1467
+ // full output: the summary came back empty/missing, or
1468
+ // skipInvalid dropped individually-invalid decisions
1469
+ // (Issue #89 — marked, not faked), or the explicit-decision
1470
+ // coverage fell below dreamMinExplicitCoverage (Issue #104
1471
+ // 方向 1 — degrade, don't reject). The valid subset was
1472
+ // absorbed (ok for the baseline).
1473
+ let status;
1474
+ let okResult;
1475
+ if (partial) {
1476
+ status = "reconcile";
1477
+ okResult = false;
1478
+ } else if (noChange) {
1479
+ status = summaryStored ? "ok" : "noop";
1480
+ okResult = summaryStored;
1481
+ } else {
1482
+ status = summaryStored && !skippedInvalid && !coverageDegraded ? "ok" : "degraded";
1483
+ okResult = true;
1484
+ }
1485
+ return finish({
1486
+ ok: okResult,
1487
+ status,
1488
+ applied,
1489
+ decisions: auditDecisions,
1490
+ outcome,
1491
+ conflicts,
1492
+ failures,
1493
+ frozen: frozenCount,
1494
+ summary: summaryStored,
1495
+ narratives: narrativesStored,
1496
+ // Issue #104:只有真发生跳过时才落库(degraded 也可能仅因 summary 为空),
1497
+ // ok 轮留 NULL,避免「空数组」与「无此字段」两种假明细占据审计行。
1498
+ skipped: skippedInvalid ? skipped : undefined
1499
+ });
1500
+ }
1501
+
1502
+ return { maybeSchedule, runDream, dispose };
1503
+ }