@modusensus/dsh-mneme 0.6.7 → 0.6.9

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 (139) hide show
  1. package/.github/workflows/test.yml +32 -0
  2. package/.release-notes-v0.6.9.md +13 -0
  3. package/CHANGELOG.md +89 -0
  4. package/LICENSE +21 -21
  5. package/README.md +219 -463
  6. package/SECURITY.md +544 -0
  7. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +247 -0
  8. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +145 -0
  9. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +56 -0
  10. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +77 -0
  11. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +64 -0
  12. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +90 -0
  13. package/dsh-mneme/CHANGELOG.md +248 -0
  14. package/dsh-mneme/LICENSE +21 -0
  15. package/dsh-mneme/README.md +465 -0
  16. package/{cordis.patch.yml → dsh-mneme/cordis.patch.yml} +15 -15
  17. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +183 -0
  18. package/dsh-mneme/docs/ENTITIES.md +245 -0
  19. package/dsh-mneme/docs/LOCAL_MODEL.md +141 -0
  20. package/dsh-mneme/docs/MIGRATION.md +127 -0
  21. package/dsh-mneme/docs/SEMANTIC.md +256 -0
  22. package/dsh-mneme/docs/SLEEP.md +163 -0
  23. package/{lib → dsh-mneme/lib}/api.js +783 -783
  24. package/{lib → dsh-mneme/lib}/client.js +1757 -1757
  25. package/{src → dsh-mneme/lib}/commands.js +64 -64
  26. package/{lib → dsh-mneme/lib}/config.js +298 -288
  27. package/{lib → dsh-mneme/lib}/dream/clustering.js +118 -118
  28. package/{src → dsh-mneme/lib}/dream/decisions.js +488 -439
  29. package/{lib → dsh-mneme/lib}/dream/sleep.js +561 -554
  30. package/{src → dsh-mneme/lib}/dream/tag-extractor.js +156 -156
  31. package/{lib → dsh-mneme/lib}/dream.js +958 -929
  32. package/{src → dsh-mneme/lib}/embedding.js +154 -154
  33. package/{src → dsh-mneme/lib}/entities/extractor.js +242 -242
  34. package/{src → dsh-mneme/lib}/hot-memory.js +53 -53
  35. package/{lib → dsh-mneme/lib}/index.js +361 -361
  36. package/{src → dsh-mneme/lib}/inject.js +208 -208
  37. package/{lib → dsh-mneme/lib}/local-embedder.js +282 -282
  38. package/{lib → dsh-mneme/lib}/mirror.js +170 -170
  39. package/{lib → dsh-mneme/lib}/parser/tag.js +59 -59
  40. package/{lib → dsh-mneme/lib}/parser/wiki-link.js +38 -38
  41. package/{src → dsh-mneme/lib}/quality-filter.js +123 -123
  42. package/{lib → dsh-mneme/lib}/reranker.js +218 -218
  43. package/{lib → dsh-mneme/lib}/search/adaptive.js +22 -22
  44. package/{lib → dsh-mneme/lib}/search/bm25.js +96 -96
  45. package/{src → dsh-mneme/lib}/search/tag-boost.js +61 -61
  46. package/{src → dsh-mneme/lib}/service.js +1726 -1726
  47. package/{lib → dsh-mneme/lib}/settings.js +172 -172
  48. package/{lib → dsh-mneme/lib}/store.js +2238 -2238
  49. package/{lib → dsh-mneme/lib}/summarize.js +236 -236
  50. package/{lib → dsh-mneme/lib}/tools.js +290 -290
  51. package/{lib → dsh-mneme/lib}/vector-index.js +116 -116
  52. package/dsh-mneme/package-lock.json +1936 -0
  53. package/dsh-mneme/package.json +80 -0
  54. package/{scripts → dsh-mneme/scripts}/benchmark-embed.js +201 -201
  55. package/{scripts → dsh-mneme/scripts}/benchmark-recall.js +133 -133
  56. package/{scripts → dsh-mneme/scripts}/benchmark-rerank.js +166 -166
  57. package/{scripts → dsh-mneme/scripts}/e2e-dsh.js +218 -218
  58. package/{scripts → dsh-mneme/scripts}/stress-dsh.js +255 -255
  59. package/{scripts → dsh-mneme/scripts}/sync-lib.js +52 -52
  60. package/{src → dsh-mneme/src}/api.js +783 -783
  61. package/{lib → dsh-mneme/src}/commands.js +64 -64
  62. package/{src → dsh-mneme/src}/config.js +298 -288
  63. package/{src → dsh-mneme/src}/dream/clustering.js +118 -118
  64. package/{lib → dsh-mneme/src}/dream/decisions.js +488 -439
  65. package/{src → dsh-mneme/src}/dream/sleep.js +561 -554
  66. package/{lib → dsh-mneme/src}/dream/tag-extractor.js +156 -156
  67. package/{src → dsh-mneme/src}/dream.js +958 -929
  68. package/{lib → dsh-mneme/src}/embedding.js +154 -154
  69. package/{lib → dsh-mneme/src}/entities/extractor.js +242 -242
  70. package/{lib → dsh-mneme/src}/hot-memory.js +53 -53
  71. package/{src → dsh-mneme/src}/index.js +361 -361
  72. package/{lib → dsh-mneme/src}/inject.js +208 -208
  73. package/{src → dsh-mneme/src}/local-embedder.js +282 -282
  74. package/{src → dsh-mneme/src}/mirror.js +170 -170
  75. package/{src → dsh-mneme/src}/parser/tag.js +59 -59
  76. package/{src → dsh-mneme/src}/parser/wiki-link.js +38 -38
  77. package/{lib → dsh-mneme/src}/quality-filter.js +123 -123
  78. package/{src → dsh-mneme/src}/reranker.js +218 -218
  79. package/{src → dsh-mneme/src}/search/adaptive.js +22 -22
  80. package/{src → dsh-mneme/src}/search/bm25.js +96 -96
  81. package/{lib → dsh-mneme/src}/search/tag-boost.js +61 -61
  82. package/{lib → dsh-mneme/src}/service.js +1726 -1726
  83. package/{src → dsh-mneme/src}/settings.js +172 -172
  84. package/{src → dsh-mneme/src}/store.js +2238 -2238
  85. package/{src → dsh-mneme/src}/summarize.js +236 -236
  86. package/{src → dsh-mneme/src}/tools.js +290 -290
  87. package/{src → dsh-mneme/src}/vector-index.js +116 -116
  88. package/{test → dsh-mneme/test}/api.test.js +594 -594
  89. package/{test → dsh-mneme/test}/audit.test.js +448 -448
  90. package/{test → dsh-mneme/test}/benchmark.test.js +35 -35
  91. package/{test → dsh-mneme/test}/boundary-v0625.test.js +82 -82
  92. package/{test → dsh-mneme/test}/client.test.js +368 -368
  93. package/{test → dsh-mneme/test}/clustering.test.js +100 -100
  94. package/{test → dsh-mneme/test}/commands.test.js +69 -69
  95. package/{test → dsh-mneme/test}/config.test.js +50 -50
  96. package/{test → dsh-mneme/test}/conflict-freeze.test.js +290 -290
  97. package/{test → dsh-mneme/test}/directory.test.js +134 -134
  98. package/{test → dsh-mneme/test}/dream.test.js +1060 -901
  99. package/{test → dsh-mneme/test}/entities.test.js +522 -522
  100. package/{test → dsh-mneme/test}/epistemic.test.js +298 -298
  101. package/{test → dsh-mneme/test}/fnew-0112.test.js +311 -311
  102. package/{test → dsh-mneme/test}/fnew-03.test.js +422 -422
  103. package/{test → dsh-mneme/test}/graph-api.test.js +175 -175
  104. package/{test → dsh-mneme/test}/helpers/dream-mock.js +82 -82
  105. package/{test → dsh-mneme/test}/hot-memory.test.js +174 -174
  106. package/{test → dsh-mneme/test}/inject.test.js +103 -103
  107. package/{test → dsh-mneme/test}/llm-audit.test.js +279 -279
  108. package/{test → dsh-mneme/test}/local-embedder.test.js +227 -227
  109. package/{test → dsh-mneme/test}/mirror-dirty.test.js +424 -424
  110. package/{test → dsh-mneme/test}/mirror-edit-digest.test.js +187 -187
  111. package/{test → dsh-mneme/test}/mirror-generation.test.js +499 -499
  112. package/{test → dsh-mneme/test}/mirror.test.js +249 -249
  113. package/{test → dsh-mneme/test}/normalize-decisions.test.js +120 -120
  114. package/{test → dsh-mneme/test}/peer-blockers.test.js +190 -190
  115. package/{test → dsh-mneme/test}/policy-epoch.test.js +259 -259
  116. package/{test → dsh-mneme/test}/provenance.test.js +103 -103
  117. package/{test → dsh-mneme/test}/quality-filter.test.js +118 -118
  118. package/{test → dsh-mneme/test}/reasoning-effort.test.js +199 -199
  119. package/{test → dsh-mneme/test}/recall-evals.test.js +235 -235
  120. package/{test → dsh-mneme/test}/recall-layer.test.js +315 -315
  121. package/{test → dsh-mneme/test}/receipt-chain.test.js +451 -451
  122. package/{test → dsh-mneme/test}/reflection.test.js +226 -226
  123. package/{test → dsh-mneme/test}/reranker.test.js +240 -240
  124. package/{test → dsh-mneme/test}/search-fusion.test.js +90 -90
  125. package/{test → dsh-mneme/test}/semantic.test.js +124 -124
  126. package/{test → dsh-mneme/test}/service-search.test.js +199 -199
  127. package/{test → dsh-mneme/test}/service.test.js +435 -435
  128. package/{test → dsh-mneme/test}/settings.test.js +118 -118
  129. package/{test → dsh-mneme/test}/sleep.test.js +365 -365
  130. package/{test → dsh-mneme/test}/store.test.js +436 -436
  131. package/{test → dsh-mneme/test}/stress.test.js +209 -209
  132. package/{test → dsh-mneme/test}/summarize.test.js +191 -191
  133. package/{test → dsh-mneme/test}/tag-boost.test.js +125 -125
  134. package/{test → dsh-mneme/test}/tag.test.js +312 -312
  135. package/{test → dsh-mneme/test}/tools.test.js +285 -285
  136. package/{test → dsh-mneme/test}/vector-index.test.js +221 -221
  137. package/{test → dsh-mneme/test}/wiki-link.test.js +332 -332
  138. package/package.json +18 -40
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,929 +1,958 @@
1
- import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
- import { clusterMemories, findPotentialConflicts } from "./dream/clustering.js";
3
- import { runAutoTag } from "./dream/tag-extractor.js";
4
- import { createHash, randomUUID } from "node:crypto";
5
- export { validateDecisions, applyDecisions, normalizeDecisions };
6
-
7
-
8
- // Extract the first JSON array from LLM output, tolerating markdown fences,
9
- // leading/trailing prose, and common wrapper noise. Returns an array or null.
10
- function extractJsonArray(text) {
11
- if (typeof text !== "string" || text.trim().length === 0) return null;
12
-
13
- // 1. Strip markdown code fences (```json ... ``` or ``` ... ```).
14
- let cleaned = text.replace(/```(?:json)?\s*([\s\S]*?)```/gi, "$1");
15
- cleaned = cleaned.trim();
16
-
17
- // 2. Find the first '[' and the matching last ']' that yields valid JSON.
18
- const start = cleaned.indexOf("[");
19
- if (start === -1) return null;
20
- for (let end = cleaned.lastIndexOf("]"); end > start; end = cleaned.lastIndexOf("]", end - 1)) {
21
- const candidate = cleaned.slice(start, end + 1);
22
- try {
23
- return JSON.parse(candidate);
24
- } catch {
25
- // Light repair: remove trailing commas before ] or }.
26
- try {
27
- const repaired = candidate.replace(/,(\s*[}\]])/g, "$1");
28
- return JSON.parse(repaired);
29
- } catch {
30
- // keep searching backwards
31
- }
32
- }
33
- }
34
-
35
- // 3. Fallback: a broader regex extraction.
36
- try {
37
- const match = cleaned.match(/\[[\s\S]*\]/);
38
- if (match) return JSON.parse(match[0]);
39
- } catch {
40
- // fall through
41
- }
42
- return null;
43
- }
44
-
45
- /**
46
- * Field-name drift guard (v0.5.3): thinking-type models (deepseek-v4-flash
47
- * etc.) occasionally ignore the prompt's exact decision schema and emit alias
48
- * keys —实测方案 A 输出 "consolidation"/"target_ids"、方案 B 输出
49
- * "action"/"targetIds",都不是插件要求的 "action"/"ids"。normalizeDecisions
50
- * 在 validateDecisions 之前把常见变体重写回规范字段名,让"字段名不听话但
51
- * 语义正确"的输出仍可被应用,而不是整单被拒。覆盖三类漂移:
52
- * 1. 整个 body 是包在对象里的数组({consolidation:[...]} /
53
- * {decisions:[...]} / {actions:[...]});
54
- * 2. 决策对象用了别名键(target_ids→ids、keep_source→keepSource、
55
- * winner_id→winner、targetIds→ids 等);
56
- * 3. action 值用了同义词(archived→archive、consolidation→merge 等)。
57
- * 无归一化必要时原样返回(null→null,调用方"no json array"分支不受影响)。
58
- */
59
- const FIELD_ALIASES = {
60
- // "consolidation" 也可作 action 键(实测 deepseek-v4-flash 这么写过);
61
- // 但 normalizeOne 对 action 键做字符串过滤,{consolidation:[...]} 这种
62
- // wrapper 数组不会被误当成 action(顶层 WRAPPER_KEYS 负责解包)。
63
- action: ["action", "decision", "operation", "op", "action_type", "actionType", "mode", "consolidation"],
64
- // 注意:action 别名不含 "type"——create 决策的 type 是合法的记忆类型字段,
65
- // 不能误当 action。
66
- ids: ["ids", "target_ids", "targetIds", "targets", "memory_ids", "memoryIds", "id_list", "idList", "memories"],
67
- reason: ["reason", "rationale", "why", "comment", "note", "explanation"],
68
- importance: ["importance", "priority", "weight", "level", "score"],
69
- keepSource: ["keepSource", "keep_source", "source_id", "sourceId", "keeper", "keep_id", "keepId"],
70
- winner: ["winner", "winner_id", "winnerId", "win_id", "winId", "preferred", "primary"],
71
- loser: ["loser", "loser_id", "loserId", "lose_id", "loseId", "drop_id", "dropId", "archive_id", "archiveId"],
72
- title: ["title", "new_title", "newTitle", "merged_title", "mergedTitle", "merge_title", "mergeTitle"],
73
- content: ["content", "new_content", "newContent", "merged_content", "mergedContent", "merge_content", "mergeContent"],
74
- evidence: ["evidence", "evidence_ids", "evidenceIds"]
75
- };
76
-
77
- // 保守的 action 值同义词:只收语义无歧义、不可能被误认为记忆类型/其他 action 的映射。
78
- const ACTION_SYNONYMS = {
79
- archived: "archive",
80
- remove: "archive",
81
- delete: "archive",
82
- combine: "merge",
83
- consolidation: "merge",
84
- consolidate: "merge",
85
- modify: "update",
86
- edit: "update"
87
- };
88
-
89
- const WRAPPER_KEYS = ["consolidation", "decisions", "actions", "results", "updates", "list", "data"];
90
-
91
- /** 把单个决策对象重写到规范字段名;非对象原样返回。 */
92
- function normalizeOne(raw) {
93
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;
94
- const d = {};
95
- const consumed = new Set();
96
- for (const [canon, aliases] of Object.entries(FIELD_ALIASES)) {
97
- for (const key of aliases) {
98
- if (key in raw && raw[key] !== undefined && raw[key] !== null) {
99
- // action 必须是字符串——{consolidation:[...]} 的 wrapper 数组跳过。
100
- if (canon === "action" && Array.isArray(raw[key])) continue;
101
- d[canon] = raw[key];
102
- consumed.add(key);
103
- break;
104
- }
105
- }
106
- }
107
- // 保留未被别名消费的原始键(create 的 type、未来字段)原样透传。
108
- for (const key of Object.keys(raw)) {
109
- if (!consumed.has(key)) d[key] = raw[key];
110
- }
111
- if (typeof d.action === "string") {
112
- const low = d.action.toLowerCase();
113
- if (ACTION_SYNONYMS[low] !== undefined) d.action = ACTION_SYNONYMS[low];
114
- }
115
- // ids 若被写成单个字符串则包成数组(validateDecisions 要求数组)。
116
- if (d.ids !== undefined && typeof d.ids === "string") d.ids = [d.ids];
117
- return d;
118
- }
119
-
120
- /** 归一化 LLM 决策 body(数组 / 包裹对象 / 单个决策对象),null 原样返回。 */
121
- function normalizeDecisions(raw) {
122
- if (!raw) return raw;
123
- if (Array.isArray(raw)) return raw.map(normalizeOne).filter((d) => d && typeof d === "object");
124
- if (typeof raw === "object") {
125
- for (const key of WRAPPER_KEYS) {
126
- if (Array.isArray(raw[key])) return normalizeDecisions(raw[key]);
127
- }
128
- // 单个决策对象 → 包成单元素数组(validateDecisions 要求数组)。
129
- return [normalizeOne(raw)];
130
- }
131
- return raw;
132
- }
133
- const SUMMARY_PROMPT = `你是记忆库摘要助手。根据整理后的记忆,生成一段 150-200 字的记忆库总览,覆盖:用户偏好、活跃项目、关键决策。之后作为会话上下文注入。只输出摘要文本,不要其他内容。`;
134
-
135
- const CONSOLIDATION_PROMPT = `你是记忆库整理助手。下面是全部记忆条目(id、类型、标题、内容、重要性、更新时间)。
136
- 请执行记忆巩固(consolidation),输出一个决策 JSON 数组。
137
-
138
- 【决策格式(必须严格遵守)】
139
- 每个决策必须是对象,字段固定:
140
- - "action":必填。取值只能是 "keep" / "merge" / "archive" / "update" / "conflict" 之一(字段名必须是 action,严禁写成 type)
141
- - "ids":必填,数组,本决策涉及的记忆 id 列表
142
- - "reason":可选,字符串,决策理由
143
- - "importance":可选,整数 1-5
144
- - merge 额外字段:"keepSource"(单个 id 字符串,必须是 ids 之一)+ 合并后的 "title"、"content"
145
- - conflict 额外字段:"winner" 与 "loser",都是【单个 id 字符串,不是数组】
146
- - update 额外字段:修正后的 "title" 和/或 "content";"ids" 只能包含一个 id
147
-
148
- 【决策 JSON 示例】
149
- [
150
- { "action": "merge", "ids": ["m1", "m2"], "keepSource": "m1", "title": "合并标题", "content": "合并后的摘要内容", "importance": 4, "reason": "主题相近" },
151
- { "action": "conflict", "winner": "m3", "loser": "m4", "reason": "内容矛盾,保留更新的信息" },
152
- { "action": "update", "ids": ["m5"], "content": "修正后的内容", "reason": "信息过时" },
153
- { "action": "archive", "ids": ["m6"], "reason": "重复或过时" }
154
- ]
155
-
156
- 【任务】
157
- 1. 识别主题相近的条目 → merge(合并为更精炼的摘要,保留信息最完整的 id 作为 keepSource)
158
- 2. 识别重复/过时信息 → archive
159
- 3. 识别内容矛盾的条目 → conflict(按时间新旧、来源完整性、信息具体程度判断 winner/loser)
160
- 4. 发现单条记忆中的信息过时、错误或遗漏 → update(直接修正内容)
161
- - update 的 ids 只能包含一个 id
162
- - 必须提供修正后的 title 和/或 content
163
- - 仅当内容确实需要修正时才使用,不要滥用
164
- - 每次整理最多输出 2 个 update
165
- - 24 小时内新建的记忆不可 update
166
- 5. 无问题的条目无需输出(未提及的条目将自动保留 keep)
167
-
168
- 【硬性规则】
169
- - 字段名必须精确为 "action",严禁写成 "type";字段名统一用双引号
170
- - conflict 的 winner/loser、merge 的 keepSource 都是【单个 id 字符串,绝不是数组】
171
- - 每条记忆最多被 claim 一次:同一个 id 不能出现在多个决策中(同一 id 不能被 merge 和 conflict/archive 等重复占用)
172
- - 未在决策中提及的记忆将自动保留(keep),无需为每条记忆输出 keep
173
- - merge 的 keepSource 必须是 ids 之一
174
- - 仅合并同类型条目(type 相同)
175
- - 不要编造 ids;只使用提供的 id
176
- - 重要性 1-5,合并后取最高
177
- - 只输出 JSON 数组,不要其他文字`;
178
-
179
- function totalChars(memories) {
180
- return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
181
- }
182
-
183
- // ---------------------------------------------------------------- audit
184
-
185
- /**
186
- * Canonical digest of the consolidation input snapshot. Built from stable
187
- * fields sorted by id, so identical inputs always yield the same hash — the
188
- * basis for replaying/verifying a recorded decision (receipt check).
189
- */
190
- export function hashSnapshot(memories) {
191
- const canon = memories
192
- .map((m) => [m.id, m.type, m.title, m.content, m.importance, m.updated_at])
193
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
194
- .map((parts) => parts.map((p) => String(p ?? "")).join("\u0001"))
195
- .join("\u0002");
196
- return createHash("sha256").update(canon).digest("hex");
197
- }
198
-
199
- /**
200
- * Compact machine-verifiable receipt for one autoDream run. Format:
201
- * dsh-mneme:run:<runId>:<status>:<snapshotHash(12)>:<inputCount>:<applied>:<summaryFlag>
202
- * Enough to correlate a run with its persisted audit row and to spot silent
203
- * drift (same snapshot hash + same decisions must reproduce the same outcome).
204
- */
205
- export function buildReceipt({ runId, status, snapshotHash, inputCount, applied, summaryStored }) {
206
- return `dsh-mneme:run:${runId}:${status}:${snapshotHash.slice(0, 12)}:${inputCount}:${applied}:${summaryStored ? 1 : 0}`;
207
- }
208
-
209
- /**
210
- * Parse a receipt back into fields; returns undefined for malformed input.
211
- */
212
- export function parseReceipt(receipt) {
213
- if (typeof receipt !== "string") return undefined;
214
- const parts = receipt.split(":");
215
- if (parts.length !== 8 || parts[0] !== "dsh-mneme" || parts[1] !== "run") return undefined;
216
- const [, , runId, status, snapshotHash, inputCount, applied, summaryStored] = parts;
217
- // reconcile = decisions validated but one or more did not commit (CAS
218
- // conflict / transaction rollback) — the store diverges from the decision
219
- // list and the run must be reconciled, never reported as a fake ok.
220
- if (!runId || !/^(ok|noop|degraded|reconcile|failed)$/.test(status)) return undefined;
221
- const count = Number(inputCount);
222
- const appliedN = Number(applied);
223
- if (!Number.isInteger(count) || !Number.isInteger(appliedN)) return undefined;
224
- return { runId, status, snapshotHash, inputCount: count, applied: appliedN, summaryStored: summaryStored === "1" };
225
- }
226
-
227
- /**
228
- * Derive the per-id disposition (keep / merge-keep / merge-archived /
229
- * archived / conflict-winner / conflict-archived) from a validated decision
230
- * list. Stored in the audit row so a run can be replayed without re-running
231
- * the LLM.
232
- */
233
- export function buildOutcome(decisions) {
234
- const byId = {};
235
- for (const d of decisions ?? []) {
236
- if (d.action === "keep") {
237
- for (const id of d.ids) byId[id] = "keep";
238
- } else if (d.action === "archive") {
239
- for (const id of d.ids) byId[id] = "archived";
240
- } else if (d.action === "merge") {
241
- for (const id of d.ids) byId[id] = id === d.keepSource ? "merge-keep" : "merge-archived";
242
- } else if (d.action === "conflict") {
243
- byId[d.winner] = "conflict-winner";
244
- byId[d.loser] = "conflict-archived";
245
- } else if (d.action === "update") {
246
- for (const id of d.ids) byId[id] = "updated";
247
- }
248
- }
249
- return { byId };
250
- }
251
-
252
- /**
253
- * Content-addressed digest of the memories a verdict was decided against
254
- * (id + title + content + importance), sorted by id so identical inputs always
255
- * hash the same. This is the per-record "判定依据" fingerprint: a receipt whose
256
- * digest cannot be reproduced from the involved memories is a bare claim, and a
257
- * digest match with a divergent outcome pinpoints drift to the exact record.
258
- */
259
- export function hashDecisionInput(memories) {
260
- const canon = (memories ?? [])
261
- .map((m) => [m.id, m.title, m.content, m.importance])
262
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
263
- .map((p) => p.map((x) => String(x ?? "")).join(""))
264
- .join("");
265
- return createHash("sha256").update(canon).digest("hex");
266
- }
267
-
268
- /**
269
- * Build the per-record receipts for a run's actually-committed mutable verdicts
270
- * (merge/conflict/update) — one row per verdict in the receipt_chain. Inputs
271
- * are drawn from the run snapshot (what the LLM actually arbitrated against),
272
- * and the idempotency counters count_before → count_after come from the
273
- * committed sub-step, so replaying the same decision must reproduce the same
274
- * numbers. verdict starts "live"; a later policy_epoch upgrade will batch-mark
275
- * older verdicts "historical" (a receipt_chain rewrite driven by the store's
276
- * getLatestPolicyEpoch — out of scope for this pass), while "revoked" is
277
- * reserved for verdicts later overturned by an explicit human decision.
278
- */
279
- function buildRecordReceipts({ runId, committed, snapshot, policyEpoch }) {
280
- const at = (id) => snapshot?.get?.(id);
281
- const receipts = [];
282
- for (const c of committed ?? []) {
283
- const base = {
284
- run_id: runId,
285
- verdict: "live",
286
- count_before: c.count_before,
287
- count_after: c.count_after,
288
- policy_epoch: policyEpoch,
289
- created_at: new Date().toISOString()
290
- };
291
- if (c.action === "merge") {
292
- receipts.push({
293
- ...base,
294
- receipt_id: randomUUID(),
295
- record_id: c.keepSource,
296
- kind: "merge",
297
- input_digest: hashDecisionInput((c.ids ?? []).map(at).filter(Boolean)),
298
- keep_source: c.keepSource,
299
- sources: c.ids
300
- });
301
- } else if (c.action === "conflict") {
302
- receipts.push({
303
- ...base,
304
- receipt_id: randomUUID(),
305
- record_id: c.winner,
306
- kind: "conflict",
307
- input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
308
- winner_id: c.winner,
309
- loser_id: c.loser
310
- });
311
- } else if (c.action === "update") {
312
- receipts.push({
313
- ...base,
314
- receipt_id: randomUUID(),
315
- record_id: c.ids[0],
316
- kind: "update",
317
- input_digest: hashDecisionInput([at(c.ids[0])].filter(Boolean))
318
- });
319
- }
320
- }
321
- return receipts;
322
- }
323
-
324
- /**
325
- * Consume an LLM stream and return the accumulated text. Direct text-delta
326
- * accumulation covers both the real protocol ({type:"text-delta", index, text})
327
- * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
328
- * surfaces as undefined. The caller decides how to treat an empty result.
329
- * `onUsage` (optional, Bug8) receives any usage chunk for token accounting.
330
- */
331
- async function streamText(ctx, options, onUsage) {
332
- let text = "";
333
- for await (const chunk of ctx.llm.stream(options)) {
334
- if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
335
- if (chunk.type === "usage" && typeof onUsage === "function") onUsage(chunk);
336
- if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
337
- return undefined;
338
- }
339
- }
340
- return text;
341
- }
342
-
343
- /**
344
- * Bug8: wrap a background LLM call so its token/time/status are recorded in the
345
- * llm_audit_logs table. Best-effort bookkeeping: a failure to WRITE the audit
346
- * row is swallowed (never blocks the LLM call), while a failure of the call
347
- * itself is captured as status='error' and re-thrown so the caller keeps its
348
- * existing error path. `spec` carries the static metadata (trigger_source,
349
- * operation_type, model_id, related_memory_ids); `body(reportUsage)` performs
350
- * the actual stream consumption and is handed a usage reporter for the chunks.
351
- */
352
- async function runAuditedLlm(ctx, service, config, spec, body) {
353
- const audit = config?.llmAudit;
354
- if (audit?.enabled === false || typeof service?.saveLlmAudit !== "function") return body(() => {});
355
- const startedAt = Date.now();
356
- const timestamp = new Date(startedAt).toISOString();
357
- let inputTokens = 0;
358
- let outputTokens = 0;
359
- let status = "success";
360
- let errorMessage = null;
361
- let result;
362
- try {
363
- result = await body((usage) => {
364
- if (!usage) return;
365
- const i = usage.input_tokens ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens;
366
- const o = usage.output_tokens ?? usage.outputTokens ?? usage.completion_tokens ?? usage.completionTokens;
367
- if (Number.isFinite(i)) inputTokens = i;
368
- if (Number.isFinite(o)) outputTokens = o;
369
- });
370
- if (result === undefined) {
371
- // stream aborted/errored: the caller treats undefined as a failed run;
372
- // record it as error here so the audit shows the truth.
373
- status = "error";
374
- errorMessage = errorMessage ?? "llm stream aborted or errored";
375
- }
376
- return result;
377
- } catch (error) {
378
- status = "error";
379
- errorMessage = String(error?.message ?? error);
380
- throw error;
381
- } finally {
382
- try {
383
- service.saveLlmAudit({
384
- timestamp,
385
- trigger_source: spec.triggerSource,
386
- operation_type: spec.operationType,
387
- model_id: spec.modelId,
388
- input_tokens: inputTokens,
389
- output_tokens: outputTokens,
390
- total_tokens: inputTokens + outputTokens,
391
- cost_usd: 0,
392
- duration_ms: Date.now() - startedAt,
393
- status,
394
- error_message: errorMessage,
395
- related_memory_ids: spec.relatedMemoryIds ?? []
396
- });
397
- } catch (auditError) {
398
- ctx.logger?.warn?.(`dsh-mneme: llm audit write failed: ${String(auditError)}`);
399
- }
400
- }
401
- }
402
-
403
- /**
404
- * Resolve the LLM route: agent default model (deployment) first, plugin config
405
- * (dreamProvider/dreamModel) as fallback. Falls through to undefined when no
406
- * route exists runDream then fails safe. Fallback is logged so a silent
407
- * route switch is observable.
408
- */
409
- function resolveRoute(ctx, config, logger) {
410
- try {
411
- const sel = ctx.agentDefaultModel?.currentSelection?.();
412
- if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
413
- logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, falling back to config route");
414
- } catch (error) {
415
- logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed, falling back to config route: ${String(error)}`);
416
- }
417
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
418
- return undefined;
419
- }
420
-
421
- // ------------------------------------------------------- semantic enhancement
422
- // Best-effort: any failure here degrades to plain consolidation. The dream
423
- // path must never be broken by an unavailable embedder/index.
424
-
425
- /** Backfill + return vectors for every memory; null when impossible. */
426
- async function collectVectors(memories, semantic) {
427
- const { embedder, vectorIndex } = semantic;
428
- if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return null;
429
- const vectors = new Array(memories.length);
430
- const missing = [];
431
- for (let i = 0; i < memories.length; i++) {
432
- const cached = vectorIndex.getEmbedding?.(memories[i].id);
433
- if (cached) vectors[i] = cached;
434
- else missing.push(i);
435
- }
436
- if (missing.length) {
437
- const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
438
- const rows = await embedder.embed(texts);
439
- missing.forEach((mi, j) => {
440
- if (rows[j]?.length) {
441
- vectors[mi] = rows[j];
442
- vectorIndex.saveEmbedding(memories[mi].id, rows[j]);
443
- }
444
- });
445
- }
446
- return vectors.some((v) => !v) ? null : vectors;
447
- }
448
-
449
- /**
450
- * Rebuild the vector index after dream decisions so the store and the index
451
- * stay in sync: merged-away/archived/conflict-loser rows lose their vectors,
452
- * the merge keeper gets a fresh one.
453
- */
454
- async function maintainIndexAfterDream(decisions, service, semantic) {
455
- const { embedder, vectorIndex } = semantic;
456
- if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return;
457
- const rebuild = new Map();
458
- for (const d of decisions ?? []) {
459
- if (d.action === "merge") {
460
- for (const id of d.ids ?? []) {
461
- if (id !== d.keepSource) vectorIndex.deleteEmbedding(id);
462
- }
463
- if (d.keepSource) {
464
- const keeper = service.getById(d.keepSource);
465
- if (keeper) rebuild.set(keeper.id, [keeper.title, keeper.content].filter(Boolean).join("\n"));
466
- }
467
- } else if (d.action === "archive" || d.action === "conflict") {
468
- for (const id of d.ids ?? [d.loser]) vectorIndex.deleteEmbedding(id);
469
- } else if (d.action === "update") {
470
- const id = d.ids[0];
471
- const mem = service.getById(id);
472
- if (mem) {
473
- vectorIndex.deleteEmbedding(id);
474
- try {
475
- const text = [mem.title, mem.content].filter(Boolean).join("\n");
476
- const v = await embedder.embedSingle(text);
477
- if (v?.length) vectorIndex.saveEmbedding(id, v);
478
- } catch { /* best-effort */ }
479
- }
480
- }
481
- }
482
- for (const [id, text] of rebuild) {
483
- try {
484
- const v = await embedder.embedSingle(text);
485
- if (v?.length) vectorIndex.saveEmbedding(id, v);
486
- } catch { /* best-effort */ }
487
- }
488
- if (embedder.modelHash) vectorIndex.markModel?.(embedder.modelHash, embedder.dimension);
489
- }
490
-
491
- export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, logger, semantic = null }) {
492
- let pendingTimer = null;
493
- let running = false;
494
- let disposed = false;
495
- let baseline = { count: 0, chars: 0 };
496
- let inFlight = null;
497
-
498
- function shouldTrigger(service) {
499
- const memories = service.all().filter((m) => !m.archived && !m.session_disposed_at && m.type !== "summary");
500
- const count = memories.length;
501
- const chars = totalChars(memories);
502
- const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
503
- const overAbs = count >= thresholdCount || chars >= thresholdChars;
504
- return { trigger: overAbs && overBase, count, chars };
505
- }
506
-
507
- function maybeSchedule(service) {
508
- if (disposed || running || pendingTimer) return false;
509
- const { trigger, count, chars } = shouldTrigger(service);
510
- if (!trigger) return false;
511
- pendingTimer = setTimeout(() => {
512
- pendingTimer = null;
513
- running = true;
514
- // Defer the onRun invocation so a synchronous throw cannot escape the
515
- // timer callback (which would crash the process) and skip the teardown.
516
- // Errors are logged, never swallowed silently. inFlight lets dispose()
517
- // await the running consolidation before the caller closes the store.
518
- inFlight = Promise.resolve()
519
- .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
520
- .then((result) => {
521
- // Refresh the baseline only for a successful run (design §5.3: an
522
- // LLM failure must not move the baseline, so the next write can
523
- // immediately re-trigger a retry). A `{ok:false}` result or a throw
524
- // keeps the old baseline. A run that reports nothing is treated as
525
- // completed without failure (no-op hooks / minimal test doubles).
526
- if (result && result.ok) {
527
- try {
528
- baseline = shouldTrigger(service);
529
- } catch (error) {
530
- // Store closed mid-flight: keep the last known baseline.
531
- logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
532
- }
533
- }
534
- })
535
- .catch((error) => {
536
- logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
537
- // Failed runs do not refresh the baseline.
538
- })
539
- .finally(() => {
540
- running = false;
541
- inFlight = null;
542
- });
543
- }, delayMs);
544
- return true;
545
- }
546
-
547
- async function dispose() {
548
- disposed = true;
549
- if (pendingTimer) { clearTimeout(pendingTimer); pendingTimer = null; }
550
- // An in-flight run is left to complete naturally (its LLM calls are
551
- // already paid for and aborting would discard the work). Await it so the
552
- // caller can close the store only after every write has landed.
553
- if (inFlight) await inFlight.catch(() => {});
554
- }
555
-
556
- async function runDream(ctx, service, config) {
557
- const logger = ctx.logger;
558
- let memories = service.all().filter((m) => !m.archived && m.type !== "summary");
559
- if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
560
- // v0.4.4 滑动窗口:只 consolidation 最近 dreamMaxSnapshotSize 条记忆,
561
- // 窗口外的旧记忆不进 snapshot(大记忆量下全量快照会撑爆 LLM 输入,配合
562
- // 隐式 keep run 始终可收敛)。按 updated_at 倒序取前 maxSize 条。
563
- const maxSize = Number.isInteger(config.dreamMaxSnapshotSize) ? config.dreamMaxSnapshotSize : 200;
564
- memories = [...memories]
565
- .sort((a, b) => {
566
- const ta = String(a.updated_at ?? "");
567
- const tb = String(b.updated_at ?? "");
568
- if (ta < tb) return 1;
569
- if (ta > tb) return -1;
570
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
571
- })
572
- .slice(0, Math.max(1, maxSize));
573
- const snapshot = new Map(memories.map((m) => [m.id, m]));
574
- const route = resolveRoute(ctx, config, logger);
575
- const runId = randomUUID();
576
- const snapshotHash = hashSnapshot([...snapshot.values()]);
577
- // Conflict freeze (opt-in): when enabled, conflict decisions are parked for
578
- // manual review instead of auto-adjudicated. Read once up front so the
579
- // prompt hint and the apply-split agree on the same gate.
580
- const freezeEnabled = config.conflictFreezeEnabled === true;
581
- // Every exit (success or failure) funnels through `finish`, which writes
582
- // the audit row + receipt. A record failure is logged, never thrown —
583
- // auditing must not break the consolidation path. Failed runs still
584
- // capture their decisions/outcome when the LLM produced a validated list
585
- // (e.g. summary step failed after consolidation), so the partial write is
586
- // replayable too.
587
- const finish = (result) => {
588
- // status is derived from what actually committed: ok only when the full
589
- // decision list landed (or a summary was refreshed); noop when nothing
590
- // changed; degraded when real changes landed without a summary;
591
- // reconcile when decisions were validated but some did not commit (CAS
592
- // conflict / rollback); failed on any LLM/validation error. No fake "ok"
593
- // for an empty or partial run.
594
- const status = result.status ?? (result.ok ? "ok" : "failed");
595
- const applied = result.applied ?? 0;
596
- const summaryStored = result.summary ?? false;
597
- const receipt = buildReceipt({ runId, status, snapshotHash, inputCount: snapshot.size, applied, summaryStored });
598
- try {
599
- service.saveDreamRun({
600
- id: runId,
601
- status,
602
- error: result.error,
603
- provider: route?.provider,
604
- model: route?.model,
605
- snapshot_hash: snapshotHash,
606
- input_count: snapshot.size,
607
- // 裁决规则版本号:config.policyEpoch(默认 0)。规则升级后该行保留
608
- // 当时的 epoch,旧裁决据此降级为历史证据(store 层 getLatestPolicyEpoch
609
- // 只负责读取当前生效版本,写入由这里完成)。
610
- policy_epoch: config.policyEpoch ?? 0,
611
- // Full input snapshot (canonical fields) so the exact arbitration
612
- // input can be rebuilt offline from the audit row alone — the
613
- // digest + decisions + outcome triple makes silent errors locatable
614
- // even after the store has moved on.
615
- input: [...snapshot.values()].map((m) => ({
616
- id: m.id,
617
- type: m.type,
618
- title: m.title,
619
- content: m.content,
620
- importance: m.importance,
621
- updated_at: m.updated_at
622
- })),
623
- decisions: result.decisions,
624
- outcome: result.outcome,
625
- applied,
626
- summary_stored: summaryStored,
627
- receipt
628
- });
629
- } catch (error) {
630
- logger?.warn?.(`dsh-mneme dream: failed to record audit run: ${String(error)}`);
631
- }
632
- return { ...result, runId, receipt, snapshotHash };
633
- };
634
- if (!route) {
635
- logger?.warn?.("dsh-mneme dream: no llm route available");
636
- return finish({ ok: false, error: "no llm route", summary: false });
637
- }
638
-
639
- let listText;
640
- if (semantic?.embedder && semantic?.vectorIndex) {
641
- try {
642
- const vectors = await collectVectors(memories, semantic);
643
- if (vectors) {
644
- const k = Math.min(10, Math.max(1, Math.floor(Math.sqrt(memories.length / 2))));
645
- const clusters = clusterMemories(memories, vectors, k);
646
- const conflicts = findPotentialConflicts(memories, vectors, 0.85);
647
- const conflictIds = new Set(conflicts.flatMap((c) => [c.a.id, c.b.id]));
648
- const parts = [];
649
- clusters.forEach((cluster, ci) => {
650
- parts.push(`# 聚类 ${ci + 1}`);
651
- for (const m of cluster) {
652
- parts.push(
653
- `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}` +
654
- (conflictIds.has(m.id) ? " | [潜在冲突]" : "")
655
- );
656
- }
657
- });
658
- listText = parts.join("\n");
659
- logger?.info?.(`[dsh-mneme] dream semantic pre-group: ${clusters.length} clusters, ${conflicts.length} conflict pairs`);
660
- }
661
- } catch (error) {
662
- logger?.warn?.(`[dsh-mneme] dream semantic pre-group failed: ${String(error)}`);
663
- }
664
- }
665
- if (!listText) {
666
- listText = [...snapshot.values()].map((m) =>
667
- `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
668
- ).join("\n");
669
- }
670
-
671
- // Freeze-aware prompt: in freeze mode the conflict branch still outputs
672
- // winner/loser (validation requires them) but they are treated as tentative
673
- // candidates the human makes the final call, not the model.
674
- const consolidationPrompt = freezeEnabled
675
- ? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
676
- : CONSOLIDATION_PROMPT;
677
- let decisionText;
678
- try {
679
- // Bug8: the consolidation call is audited (tokens/time/status). A throw
680
- // re-propagates to the catch below; an aborted stream returns undefined
681
- // and is treated as a failed run after the check below.
682
- decisionText = await runAuditedLlm(ctx, service, config, {
683
- triggerSource: "autoDream",
684
- operationType: "dream_consolidate",
685
- modelId: `${route.provider}:${route.model}`,
686
- relatedMemoryIds: [...snapshot.keys()]
687
- }, (reportUsage) => streamText(ctx, {
688
- provider: route.provider,
689
- model: route.model,
690
- purpose: "compaction",
691
- maxTokens: config.dreamMaxTokens ?? 4096,
692
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
693
- ? { reasoningEffort: config.dreamReasoningEffort }
694
- : {}),
695
- messages: [
696
- { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
697
- { role: "user", content: [{ type: "text", text: listText }] }
698
- ]
699
- }, reportUsage));
700
- } catch (error) {
701
- logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
702
- return finish({ ok: false, error: "llm failed", summary: false });
703
- }
704
- if (decisionText === undefined) {
705
- logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
706
- return finish({ ok: false, error: "llm failed", summary: false });
707
- }
708
-
709
- // v0.5.3 字段名归一化兜底:thinking 模型可能输出别名键/wrapper 对象,
710
- // validateDecisions 之前重写到规范字段名,语义正确但 schema 不听话的
711
- // 输出不再整单被拒。
712
- const decisions = normalizeDecisions(extractJsonArray(decisionText));
713
- if (!Array.isArray(decisions)) {
714
- logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0})`);
715
- return finish({ ok: false, error: "no json array in llm output", summary: false });
716
- }
717
- const { ok, errors } = validateDecisions(decisions, snapshot, {
718
- maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
719
- minAgeHours: config.reflectionUpdateMinAgeHours,
720
- // v0.4.4 fix:显式透传,用户配 dreamImplicitKeep:false 时严格模式必须
721
- // 真正生效,dreamMinExplicitCoverage 决定隐式 keep 下的覆盖率下限。
722
- dreamImplicitKeep: config.dreamImplicitKeep,
723
- dreamMinExplicitCoverage: config.dreamMinExplicitCoverage
724
- });
725
- if (!ok) {
726
- logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
727
- return finish({ ok: false, error: `invalid decisions: ${errors.length} errors`, summary: false });
728
- }
729
-
730
- // Capture pre-update snapshots so the audit records what each update changed.
731
- const updateSnapshots = {};
732
- for (const d of decisions) {
733
- if (d.action === "update") {
734
- const mem = snapshot.get(d.ids[0]);
735
- if (mem) updateSnapshots[d.ids[0]] = { title: mem.title, content: mem.content, importance: mem.importance };
736
- }
737
- }
738
-
739
- // Conflict freeze (opt-in): when enabled, conflict decisions are not
740
- // auto-adjudicated — no winner kept, no loser archived. The pair is parked
741
- // in conflict_pending for human review instead. Best-effort: a store
742
- // failure here must never block the run (fail-safe — the memories are left
743
- // untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
744
- // bounds the review queue; overflow is skipped with a warning.
745
- let frozenCount = 0;
746
- const frozenIds = [];
747
- const applyList = freezeEnabled ? decisions.filter((d) => d.action !== "conflict") : decisions;
748
- if (freezeEnabled) {
749
- const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
750
- if (conflictsToFreeze.length > 0) {
751
- try {
752
- const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
753
- const pendingNow = service.countConflictPending();
754
- const budget = Math.max(0, maxPending - pendingNow);
755
- const toFreeze = conflictsToFreeze.slice(0, budget);
756
- if (conflictsToFreeze.length > budget) {
757
- logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
758
- }
759
- for (const d of toFreeze) {
760
- try {
761
- service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
762
- frozenCount++;
763
- frozenIds.push(d.winner, d.loser);
764
- } catch (error) {
765
- logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
766
- }
767
- }
768
- } catch (error) {
769
- logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
770
- }
771
- }
772
- }
773
-
774
- // CAS-guarded, per-decision-transactional apply against the run snapshot:
775
- // a target changed during the LLM call is skipped and reported as a
776
- // conflict instead of being overwritten (item ①). Frozen conflicts are
777
- // excluded from this list (they are parked, not applied).
778
- const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot, config);
779
- // Per-record receipt chain: one row per actually-committed merge/conflict/
780
- // update verdict, stamped with the decision-basis digest + idempotency
781
- // counters (count_before → count_after). Written here, before the run audit
782
- // row, so the verdict trail always precedes the run trail it belongs to.
783
- // Bookkeeping: a write failure is logged and swallowed — it must never
784
- // block the consolidation flow.
785
- try {
786
- for (const r of buildRecordReceipts({ runId, committed, snapshot, policyEpoch: config.policyEpoch ?? 0 })) {
787
- service.saveReceipt(r);
788
- }
789
- } catch (error) {
790
- logger?.warn?.(`dsh-mneme dream: failed to write per-record receipt: ${String(error)}`);
791
- }
792
- // Attach the pre-update snapshot to the audit copy of each update decision
793
- // so the recorded row shows the before/after delta, not just the target.
794
- const auditDecisions = decisions.map((d) =>
795
- d.action === "update" && updateSnapshots[d.ids[0]]
796
- ? { ...d, _before: updateSnapshots[d.ids[0]] }
797
- : d
798
- );
799
- // Outcome is derived from the ACTUALLY committed sub-steps, never from the
800
- // raw LLM decision list — a merge whose archive step rolled back must not
801
- // claim "merge-archived" (item ②). Conflicts/failures ride along so the
802
- // audit row records why the run diverged.
803
- const outcome = { ...buildOutcome(committed), conflicts, failures };
804
- // Frozen conflicts were not adjudicated: mark both sides pending in the
805
- // per-id outcome so the audit row shows they were parked, not skipped.
806
- if (frozenIds.length) {
807
- for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
808
- }
809
- // Decisions validated but not fully committed → reconcile (not ok).
810
- const partial = conflicts.length > 0 || failures.length > 0;
811
- // No decision landed (all-keep, or every decision skipped as an idempotent
812
- // replay) → nothing substantive changed. Distinct from a success: such a
813
- // run must never be reported as ok, or the audit claims work that never
814
- // happened and the scheduler refreshes the baseline on a false positive.
815
- // Frozen conflicts are substantive output (parked for review), so a run
816
- // that only froze conflicts is not a noop.
817
- const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
818
-
819
- // v0.6.2 auto-tag: a light LLM pass over the retained (post-consolidation)
820
- // memories. Opt-in via config.autoTagEnabled, bounded by autoTagMaxPerRun,
821
- // and always fail-safe a tag failure must never change the consolidation
822
- // outcome reported below (it is logged and counted, nothing more).
823
- let autoTagged = 0;
824
- if (config.autoTagEnabled === true) {
825
- try {
826
- const tagResult = await runAutoTag({ ctx, service, config, route });
827
- autoTagged = tagResult?.tagged ?? 0;
828
- if (tagResult?.ok === false && tagResult?.skippedBy && tagResult.skippedBy !== "empty") {
829
- logger?.warn?.(`dsh-mneme dream: auto-tag skipped (${tagResult.skippedBy})`);
830
- } else if (autoTagged > 0) {
831
- logger?.info?.(`[dsh-mneme] auto-tag: ${autoTagged} memory(ies) tagged`);
832
- }
833
- } catch (error) {
834
- logger?.warn?.(`dsh-mneme dream: auto-tag failed: ${String(error)}`);
835
- }
836
- }
837
-
838
- // Keep the vector index consistent with the post-dream store state.
839
- if (semantic?.embedder && semantic?.vectorIndex) {
840
- try {
841
- await maintainIndexAfterDream(applyList, service, semantic);
842
- } catch (error) {
843
- logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
844
- }
845
- }
846
-
847
- // Summary generation (second LLM call). A throwing stream is reported as
848
- // a failed run; summary:false marks a run that produced no summary.
849
- let summaryText;
850
- try {
851
- // Bug8: the summary call is audited too (operation dream_summarize).
852
- summaryText = await runAuditedLlm(ctx, service, config, {
853
- triggerSource: "autoDream",
854
- operationType: "dream_summarize",
855
- modelId: `${route.provider}:${route.model}`,
856
- relatedMemoryIds: []
857
- }, (reportUsage) => streamText(ctx, {
858
- provider: route.provider,
859
- model: route.model,
860
- purpose: "compaction",
861
- maxTokens: config.dreamMaxTokens ?? 2048,
862
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
863
- ? { reasoningEffort: config.dreamReasoningEffort }
864
- : {}),
865
- messages: [
866
- { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
867
- { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && !m.session_disposed_at && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
868
- ]
869
- }, reportUsage));
870
- } catch (error) {
871
- logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
872
- return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
873
- }
874
- let summaryStored = false;
875
- if (summaryText !== undefined && summaryText.trim()) {
876
- // Bug5 carve-out: the library overview is regenerated every run, so it
877
- // must REPLACE the previous overview (not append — that would grow the
878
- // summary unboundedly). `_overwrite` still archives the old overview into
879
- // content_history before replacing it.
880
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: summaryText.trim(), importance: 5, source: "dream", _overwrite: true });
881
- summaryStored = true;
882
- // Re-embed the fresh summary so the index stays in sync with the store.
883
- if (semantic?.embedder && semantic?.vectorIndex) {
884
- try {
885
- const summary = service.all().find((m) => m.type === "summary");
886
- if (summary) {
887
- const v = await semantic.embedder.embedSingle([summary.title, summary.content].filter(Boolean).join("\n"));
888
- if (v?.length) semantic.vectorIndex.saveEmbedding(summary.id, v);
889
- if (semantic.embedder.modelHash) semantic.vectorIndex.markModel?.(semantic.embedder.modelHash, semantic.embedder.dimension);
890
- }
891
- } catch { /* best-effort */ }
892
- }
893
- }
894
- // Honest status assignment (never a fake ok):
895
- // reconcile some decisions validated but did not commit (CAS/rollback).
896
- // noop — nothing changed and no summary persisted: truly an empty
897
- // run. ok:false keeps the scheduler from moving the baseline.
898
- // ok — either real changes landed, or a fresh summary was stored
899
- // (all-keep + summary is a substantive summary refresh).
900
- // degraded — real consolidation landed but the summary came back empty/
901
- // missing: the store was absorbed (ok for the baseline) but
902
- // the run did not produce its full output (marked, not faked).
903
- let status;
904
- let okResult;
905
- if (partial) {
906
- status = "reconcile";
907
- okResult = false;
908
- } else if (noChange) {
909
- status = summaryStored ? "ok" : "noop";
910
- okResult = summaryStored;
911
- } else {
912
- status = summaryStored ? "ok" : "degraded";
913
- okResult = true;
914
- }
915
- return finish({
916
- ok: okResult,
917
- status,
918
- applied,
919
- decisions: auditDecisions,
920
- outcome,
921
- conflicts,
922
- failures,
923
- frozen: frozenCount,
924
- summary: summaryStored
925
- });
926
- }
927
-
928
- return { maybeSchedule, runDream, dispose };
929
- }
1
+ import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
+ import { clusterMemories, findPotentialConflicts } from "./dream/clustering.js";
3
+ import { runAutoTag } from "./dream/tag-extractor.js";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ export { validateDecisions, applyDecisions, normalizeDecisions };
6
+
7
+
8
+ // Extract the first JSON array from LLM output, tolerating markdown fences,
9
+ // leading/trailing prose, and common wrapper noise. Returns an array or null.
10
+ function extractJsonArray(text) {
11
+ if (typeof text !== "string" || text.trim().length === 0) return null;
12
+
13
+ // 1. Strip markdown code fences (```json ... ``` or ``` ... ```).
14
+ let cleaned = text.replace(/```(?:json)?\s*([\s\S]*?)```/gi, "$1");
15
+ cleaned = cleaned.trim();
16
+
17
+ // 2. Find the first '[' and the matching last ']' that yields valid JSON.
18
+ const start = cleaned.indexOf("[");
19
+ if (start === -1) return null;
20
+ for (let end = cleaned.lastIndexOf("]"); end > start; end = cleaned.lastIndexOf("]", end - 1)) {
21
+ const candidate = cleaned.slice(start, end + 1);
22
+ try {
23
+ return JSON.parse(candidate);
24
+ } catch {
25
+ // Light repair: remove trailing commas before ] or }.
26
+ try {
27
+ const repaired = candidate.replace(/,(\s*[}\]])/g, "$1");
28
+ return JSON.parse(repaired);
29
+ } catch {
30
+ // keep searching backwards
31
+ }
32
+ }
33
+ }
34
+
35
+ // 3. Fallback: a broader regex extraction.
36
+ try {
37
+ const match = cleaned.match(/\[[\s\S]*\]/);
38
+ if (match) return JSON.parse(match[0]);
39
+ } catch {
40
+ // fall through
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Field-name drift guard (v0.5.3): thinking-type models (deepseek-v4-flash
47
+ * etc.) occasionally ignore the prompt's exact decision schema and emit alias
48
+ * keys —实测方案 A 输出 "consolidation"/"target_ids"、方案 B 输出
49
+ * "action"/"targetIds",都不是插件要求的 "action"/"ids"。normalizeDecisions
50
+ * 在 validateDecisions 之前把常见变体重写回规范字段名,让"字段名不听话但
51
+ * 语义正确"的输出仍可被应用,而不是整单被拒。覆盖三类漂移:
52
+ * 1. 整个 body 是包在对象里的数组({consolidation:[...]} /
53
+ * {decisions:[...]} / {actions:[...]});
54
+ * 2. 决策对象用了别名键(target_ids→ids、keep_source→keepSource、
55
+ * winner_id→winner、targetIds→ids 等);
56
+ * 3. action 值用了同义词(archived→archive、consolidation→merge 等)。
57
+ * 无归一化必要时原样返回(null→null,调用方"no json array"分支不受影响)。
58
+ */
59
+ const FIELD_ALIASES = {
60
+ // "consolidation" 也可作 action 键(实测 deepseek-v4-flash 这么写过);
61
+ // 但 normalizeOne 对 action 键做字符串过滤,{consolidation:[...]} 这种
62
+ // wrapper 数组不会被误当成 action(顶层 WRAPPER_KEYS 负责解包)。
63
+ action: ["action", "decision", "operation", "op", "action_type", "actionType", "mode", "consolidation"],
64
+ // 注意:action 别名不含 "type"——create 决策的 type 是合法的记忆类型字段,
65
+ // 不能误当 action。
66
+ ids: ["ids", "target_ids", "targetIds", "targets", "memory_ids", "memoryIds", "id_list", "idList", "memories"],
67
+ reason: ["reason", "rationale", "why", "comment", "note", "explanation"],
68
+ importance: ["importance", "priority", "weight", "level", "score"],
69
+ keepSource: ["keepSource", "keep_source", "source_id", "sourceId", "keeper", "keep_id", "keepId"],
70
+ winner: ["winner", "winner_id", "winnerId", "win_id", "winId", "preferred", "primary"],
71
+ loser: ["loser", "loser_id", "loserId", "lose_id", "loseId", "drop_id", "dropId", "archive_id", "archiveId"],
72
+ title: ["title", "new_title", "newTitle", "merged_title", "mergedTitle", "merge_title", "mergeTitle"],
73
+ content: ["content", "new_content", "newContent", "merged_content", "mergedContent", "merge_content", "mergeContent"],
74
+ evidence: ["evidence", "evidence_ids", "evidenceIds"]
75
+ };
76
+
77
+ // 保守的 action 值同义词:只收语义无歧义、不可能被误认为记忆类型/其他 action 的映射。
78
+ const ACTION_SYNONYMS = {
79
+ archived: "archive",
80
+ remove: "archive",
81
+ delete: "archive",
82
+ combine: "merge",
83
+ consolidation: "merge",
84
+ consolidate: "merge",
85
+ modify: "update",
86
+ edit: "update"
87
+ };
88
+
89
+ const WRAPPER_KEYS = ["consolidation", "decisions", "actions", "results", "updates", "list", "data"];
90
+
91
+ /** 把单个决策对象重写到规范字段名;非对象原样返回。 */
92
+ function normalizeOne(raw) {
93
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;
94
+ const d = {};
95
+ const consumed = new Set();
96
+ for (const [canon, aliases] of Object.entries(FIELD_ALIASES)) {
97
+ for (const key of aliases) {
98
+ if (key in raw && raw[key] !== undefined && raw[key] !== null) {
99
+ // action 必须是字符串——{consolidation:[...]} 的 wrapper 数组跳过。
100
+ if (canon === "action" && Array.isArray(raw[key])) continue;
101
+ d[canon] = raw[key];
102
+ consumed.add(key);
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ // 保留未被别名消费的原始键(create 的 type、未来字段)原样透传。
108
+ for (const key of Object.keys(raw)) {
109
+ if (!consumed.has(key)) d[key] = raw[key];
110
+ }
111
+ if (typeof d.action === "string") {
112
+ const low = d.action.toLowerCase();
113
+ if (ACTION_SYNONYMS[low] !== undefined) d.action = ACTION_SYNONYMS[low];
114
+ }
115
+ // ids 若被写成单个字符串则包成数组(validateDecisions 要求数组)。
116
+ if (d.ids !== undefined && typeof d.ids === "string") d.ids = [d.ids];
117
+ return d;
118
+ }
119
+
120
+ /** 归一化 LLM 决策 body(数组 / 包裹对象 / 单个决策对象),null 原样返回。 */
121
+ function normalizeDecisions(raw) {
122
+ if (!raw) return raw;
123
+ if (Array.isArray(raw)) return raw.map(normalizeOne).filter((d) => d && typeof d === "object");
124
+ if (typeof raw === "object") {
125
+ for (const key of WRAPPER_KEYS) {
126
+ if (Array.isArray(raw[key])) return normalizeDecisions(raw[key]);
127
+ }
128
+ // 单个决策对象 → 包成单元素数组(validateDecisions 要求数组)。
129
+ return [normalizeOne(raw)];
130
+ }
131
+ return raw;
132
+ }
133
+ const SUMMARY_PROMPT = `你是记忆库摘要助手。根据整理后的记忆,生成一段 150-200 字的记忆库总览,覆盖:用户偏好、活跃项目、关键决策。之后作为会话上下文注入。只输出摘要文本,不要其他内容。`;
134
+
135
+ const CONSOLIDATION_PROMPT = `你是记忆库整理助手。下面是全部记忆条目(id、类型、标题、内容、重要性、更新时间)。
136
+ 请执行记忆巩固(consolidation),输出一个决策 JSON 数组。
137
+
138
+ 【决策格式(必须严格遵守)】
139
+ 每个决策必须是对象,字段固定:
140
+ - "action":必填。取值只能是 "keep" / "merge" / "archive" / "update" / "conflict" 之一(字段名必须是 action,严禁写成 type)
141
+ - "ids":必填,数组,本决策涉及的记忆 id 列表
142
+ - "reason":可选,字符串,决策理由
143
+ - "importance":可选,整数 1-5
144
+ - merge 额外字段:"keepSource"(单个 id 字符串,必须是 ids 之一)+ 合并后的 "title"、"content"
145
+ - conflict 额外字段:"winner" 与 "loser",都是【单个 id 字符串,不是数组】
146
+ - update 额外字段:修正后的 "title" 和/或 "content";"ids" 只能包含一个 id
147
+
148
+ 【决策 JSON 示例】
149
+ [
150
+ { "action": "merge", "ids": ["m1", "m2"], "keepSource": "m1", "title": "合并标题", "content": "合并后的摘要内容", "importance": 4, "reason": "主题相近" },
151
+ { "action": "conflict", "winner": "m3", "loser": "m4", "reason": "内容矛盾,保留更新的信息" },
152
+ { "action": "update", "ids": ["m5"], "content": "修正后的内容", "reason": "信息过时" },
153
+ { "action": "archive", "ids": ["m6"], "reason": "重复或过时" }
154
+ ]
155
+
156
+ 【任务】
157
+ 1. 识别主题相近的条目 → merge(合并为更精炼的摘要,保留信息最完整的 id 作为 keepSource)
158
+ 2. 识别重复/过时信息 → archive
159
+ 3. 识别内容矛盾的条目 → conflict(按时间新旧、来源完整性、信息具体程度判断 winner/loser)
160
+ 4. 发现单条记忆中的信息过时、错误或遗漏 → update(直接修正内容)
161
+ - update 的 ids 只能包含一个 id
162
+ - 必须提供修正后的 title 和/或 content
163
+ - 仅当内容确实需要修正时才使用,不要滥用
164
+ - 每次整理最多输出 2 个 update
165
+ - 24 小时内新建的记忆不可 update
166
+ 5. 无问题的条目无需输出(未提及的条目将自动保留 keep)
167
+
168
+ 【硬性规则】
169
+ - 字段名必须精确为 "action",严禁写成 "type";字段名统一用双引号
170
+ - conflict 的 winner/loser、merge 的 keepSource 都是【单个 id 字符串,绝不是数组】
171
+ - 每条记忆最多被 claim 一次:同一个 id 不能出现在多个决策中(同一 id 不能被 merge 和 conflict/archive 等重复占用)
172
+ - 未在决策中提及的记忆将自动保留(keep),无需为每条记忆输出 keep
173
+ - merge 的 keepSource 必须是 ids 之一
174
+ - 仅合并同类型条目(type 相同)
175
+ - 不要编造 ids;只使用提供的 id
176
+ - 重要性 1-5,合并后取最高
177
+ - 只输出 JSON 数组,不要其他文字`;
178
+
179
+ function totalChars(memories) {
180
+ return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
181
+ }
182
+
183
+ // ---------------------------------------------------------------- audit
184
+
185
+ /**
186
+ * Canonical digest of the consolidation input snapshot. Built from stable
187
+ * fields sorted by id, so identical inputs always yield the same hash — the
188
+ * basis for replaying/verifying a recorded decision (receipt check).
189
+ */
190
+ export function hashSnapshot(memories) {
191
+ const canon = memories
192
+ .map((m) => [m.id, m.type, m.title, m.content, m.importance, m.updated_at])
193
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
194
+ .map((parts) => parts.map((p) => String(p ?? "")).join("\u0001"))
195
+ .join("\u0002");
196
+ return createHash("sha256").update(canon).digest("hex");
197
+ }
198
+
199
+ /**
200
+ * Compact machine-verifiable receipt for one autoDream run. Format:
201
+ * dsh-mneme:run:<runId>:<status>:<snapshotHash(12)>:<inputCount>:<applied>:<summaryFlag>
202
+ * Enough to correlate a run with its persisted audit row and to spot silent
203
+ * drift (same snapshot hash + same decisions must reproduce the same outcome).
204
+ */
205
+ export function buildReceipt({ runId, status, snapshotHash, inputCount, applied, summaryStored }) {
206
+ return `dsh-mneme:run:${runId}:${status}:${snapshotHash.slice(0, 12)}:${inputCount}:${applied}:${summaryStored ? 1 : 0}`;
207
+ }
208
+
209
+ /**
210
+ * Parse a receipt back into fields; returns undefined for malformed input.
211
+ */
212
+ export function parseReceipt(receipt) {
213
+ if (typeof receipt !== "string") return undefined;
214
+ const parts = receipt.split(":");
215
+ if (parts.length !== 8 || parts[0] !== "dsh-mneme" || parts[1] !== "run") return undefined;
216
+ const [, , runId, status, snapshotHash, inputCount, applied, summaryStored] = parts;
217
+ // reconcile = decisions validated but one or more did not commit (CAS
218
+ // conflict / transaction rollback) — the store diverges from the decision
219
+ // list and the run must be reconciled, never reported as a fake ok.
220
+ if (!runId || !/^(ok|noop|degraded|reconcile|failed)$/.test(status)) return undefined;
221
+ const count = Number(inputCount);
222
+ const appliedN = Number(applied);
223
+ if (!Number.isInteger(count) || !Number.isInteger(appliedN)) return undefined;
224
+ return { runId, status, snapshotHash, inputCount: count, applied: appliedN, summaryStored: summaryStored === "1" };
225
+ }
226
+
227
+ /**
228
+ * Derive the per-id disposition (keep / merge-keep / merge-archived /
229
+ * archived / conflict-winner / conflict-archived) from a validated decision
230
+ * list. Stored in the audit row so a run can be replayed without re-running
231
+ * the LLM.
232
+ */
233
+ export function buildOutcome(decisions) {
234
+ const byId = {};
235
+ for (const d of decisions ?? []) {
236
+ if (d.action === "keep") {
237
+ for (const id of d.ids) byId[id] = "keep";
238
+ } else if (d.action === "archive") {
239
+ for (const id of d.ids) byId[id] = "archived";
240
+ } else if (d.action === "merge") {
241
+ for (const id of d.ids) byId[id] = id === d.keepSource ? "merge-keep" : "merge-archived";
242
+ } else if (d.action === "conflict") {
243
+ byId[d.winner] = "conflict-winner";
244
+ byId[d.loser] = "conflict-archived";
245
+ } else if (d.action === "update") {
246
+ for (const id of d.ids) byId[id] = "updated";
247
+ }
248
+ }
249
+ return { byId };
250
+ }
251
+
252
+ /**
253
+ * Content-addressed digest of the memories a verdict was decided against
254
+ * (id + title + content + importance), sorted by id so identical inputs always
255
+ * hash the same. This is the per-record "判定依据" fingerprint: a receipt whose
256
+ * digest cannot be reproduced from the involved memories is a bare claim, and a
257
+ * digest match with a divergent outcome pinpoints drift to the exact record.
258
+ */
259
+ export function hashDecisionInput(memories) {
260
+ const canon = (memories ?? [])
261
+ .map((m) => [m.id, m.title, m.content, m.importance])
262
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
263
+ .map((p) => p.map((x) => String(x ?? "")).join(""))
264
+ .join("");
265
+ return createHash("sha256").update(canon).digest("hex");
266
+ }
267
+
268
+ /**
269
+ * Build the per-record receipts for a run's actually-committed mutable verdicts
270
+ * (merge/conflict/update) — one row per verdict in the receipt_chain. Inputs
271
+ * are drawn from the run snapshot (what the LLM actually arbitrated against),
272
+ * and the idempotency counters count_before → count_after come from the
273
+ * committed sub-step, so replaying the same decision must reproduce the same
274
+ * numbers. verdict starts "live"; a later policy_epoch upgrade will batch-mark
275
+ * older verdicts "historical" (a receipt_chain rewrite driven by the store's
276
+ * getLatestPolicyEpoch — out of scope for this pass), while "revoked" is
277
+ * reserved for verdicts later overturned by an explicit human decision.
278
+ */
279
+ function buildRecordReceipts({ runId, committed, snapshot, policyEpoch }) {
280
+ const at = (id) => snapshot?.get?.(id);
281
+ const receipts = [];
282
+ for (const c of committed ?? []) {
283
+ const base = {
284
+ run_id: runId,
285
+ verdict: "live",
286
+ count_before: c.count_before,
287
+ count_after: c.count_after,
288
+ policy_epoch: policyEpoch,
289
+ created_at: new Date().toISOString()
290
+ };
291
+ if (c.action === "merge") {
292
+ receipts.push({
293
+ ...base,
294
+ receipt_id: randomUUID(),
295
+ record_id: c.keepSource,
296
+ kind: "merge",
297
+ input_digest: hashDecisionInput((c.ids ?? []).map(at).filter(Boolean)),
298
+ keep_source: c.keepSource,
299
+ sources: c.ids
300
+ });
301
+ } else if (c.action === "conflict") {
302
+ receipts.push({
303
+ ...base,
304
+ receipt_id: randomUUID(),
305
+ record_id: c.winner,
306
+ kind: "conflict",
307
+ input_digest: hashDecisionInput([at(c.winner), at(c.loser)].filter(Boolean)),
308
+ winner_id: c.winner,
309
+ loser_id: c.loser
310
+ });
311
+ } else if (c.action === "update") {
312
+ receipts.push({
313
+ ...base,
314
+ receipt_id: randomUUID(),
315
+ record_id: c.ids[0],
316
+ kind: "update",
317
+ input_digest: hashDecisionInput([at(c.ids[0])].filter(Boolean))
318
+ });
319
+ }
320
+ }
321
+ return receipts;
322
+ }
323
+
324
+ /**
325
+ * Consume an LLM stream and return the accumulated text. Direct text-delta
326
+ * accumulation covers both the real protocol ({type:"text-delta", index, text})
327
+ * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
328
+ * surfaces as undefined. The caller decides how to treat an empty result.
329
+ * `onUsage` (optional, Bug8) receives any usage chunk for token accounting.
330
+ */
331
+ async function streamText(ctx, options, onUsage) {
332
+ let text = "";
333
+ for await (const chunk of ctx.llm.stream(options)) {
334
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
335
+ if (chunk.type === "usage" && typeof onUsage === "function") onUsage(chunk);
336
+ if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
337
+ return undefined;
338
+ }
339
+ }
340
+ return text;
341
+ }
342
+
343
+ /**
344
+ * Bug8: wrap a background LLM call so its token/time/status are recorded in the
345
+ * llm_audit_logs table. Best-effort bookkeeping: a failure to WRITE the audit
346
+ * row is swallowed (never blocks the LLM call), while a failure of the call
347
+ * itself is captured as status='error' and re-thrown so the caller keeps its
348
+ * existing error path. `spec` carries the static metadata (trigger_source,
349
+ * operation_type, model_id, related_memory_ids); `body(reportUsage)` performs
350
+ * the actual stream consumption and is handed a usage reporter for the chunks.
351
+ */
352
+ async function runAuditedLlm(ctx, service, config, spec, body) {
353
+ const audit = config?.llmAudit;
354
+ if (audit?.enabled === false || typeof service?.saveLlmAudit !== "function") return body(() => {});
355
+ const startedAt = Date.now();
356
+ const timestamp = new Date(startedAt).toISOString();
357
+ let inputTokens = 0;
358
+ let outputTokens = 0;
359
+ let status = "success";
360
+ let errorMessage = null;
361
+ let result;
362
+ try {
363
+ result = await body((usage) => {
364
+ if (!usage) return;
365
+ const i = usage.input_tokens ?? usage.inputTokens ?? usage.prompt_tokens ?? usage.promptTokens;
366
+ const o = usage.output_tokens ?? usage.outputTokens ?? usage.completion_tokens ?? usage.completionTokens;
367
+ if (Number.isFinite(i)) inputTokens = i;
368
+ if (Number.isFinite(o)) outputTokens = o;
369
+ });
370
+ if (result === undefined) {
371
+ // stream aborted/errored: the caller treats undefined as a failed run;
372
+ // record it as error here so the audit shows the truth.
373
+ status = "error";
374
+ errorMessage = errorMessage ?? "llm stream aborted or errored";
375
+ }
376
+ return result;
377
+ } catch (error) {
378
+ status = "error";
379
+ errorMessage = String(error?.message ?? error);
380
+ throw error;
381
+ } finally {
382
+ try {
383
+ service.saveLlmAudit({
384
+ timestamp,
385
+ trigger_source: spec.triggerSource,
386
+ operation_type: spec.operationType,
387
+ model_id: spec.modelId,
388
+ input_tokens: inputTokens,
389
+ output_tokens: outputTokens,
390
+ total_tokens: inputTokens + outputTokens,
391
+ cost_usd: 0,
392
+ duration_ms: Date.now() - startedAt,
393
+ status,
394
+ error_message: errorMessage,
395
+ related_memory_ids: spec.relatedMemoryIds ?? []
396
+ });
397
+ } catch (auditError) {
398
+ ctx.logger?.warn?.(`dsh-mneme: llm audit write failed: ${String(auditError)}`);
399
+ }
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Resolve the LLM route (Issue #25): an explicit plugin config
405
+ * (dreamProvider/dreamModel) is the user's declared override and wins; the
406
+ * agent default model (deployment) is only a fallback when no config route is
407
+ * set. In a standard DSH install agentDefaultModel always resolves, so without
408
+ * this ordering the config route would be dead code and dreamProvider/dreamModel
409
+ * could never take effect. Falls through to undefined when no route exists —
410
+ * runDream then fails safe. A config→default switch is logged so it is observable.
411
+ */
412
+ function resolveRoute(ctx, config, logger) {
413
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
414
+ try {
415
+ const sel = ctx.agentDefaultModel?.currentSelection?.();
416
+ if (sel?.provider && sel?.model) {
417
+ logger?.info?.("dsh-mneme dream: no dreamProvider/dreamModel config, falling back to agent default");
418
+ return { provider: sel.provider, model: sel.model };
419
+ }
420
+ logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, no config route either");
421
+ } catch (error) {
422
+ logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed: ${String(error)}`);
423
+ }
424
+ return undefined;
425
+ }
426
+
427
+ // ------------------------------------------------------- semantic enhancement
428
+ // Best-effort: any failure here degrades to plain consolidation. The dream
429
+ // path must never be broken by an unavailable embedder/index.
430
+
431
+ /** Backfill + return vectors for every memory; null when impossible. */
432
+ async function collectVectors(memories, semantic) {
433
+ const { embedder, vectorIndex } = semantic;
434
+ if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return null;
435
+ const vectors = new Array(memories.length);
436
+ const missing = [];
437
+ for (let i = 0; i < memories.length; i++) {
438
+ const cached = vectorIndex.getEmbedding?.(memories[i].id);
439
+ if (cached) vectors[i] = cached;
440
+ else missing.push(i);
441
+ }
442
+ if (missing.length) {
443
+ const texts = missing.map((i) => [memories[i].title, memories[i].content].filter(Boolean).join("\n"));
444
+ const rows = await embedder.embed(texts);
445
+ missing.forEach((mi, j) => {
446
+ if (rows[j]?.length) {
447
+ vectors[mi] = rows[j];
448
+ vectorIndex.saveEmbedding(memories[mi].id, rows[j]);
449
+ }
450
+ });
451
+ }
452
+ return vectors.some((v) => !v) ? null : vectors;
453
+ }
454
+
455
+ /**
456
+ * Rebuild the vector index after dream decisions so the store and the index
457
+ * stay in sync: merged-away/archived/conflict-loser rows lose their vectors,
458
+ * the merge keeper gets a fresh one.
459
+ */
460
+ async function maintainIndexAfterDream(decisions, service, semantic) {
461
+ const { embedder, vectorIndex } = semantic;
462
+ if (!embedder || !vectorIndex || typeof embedder.embedSingle !== "function") return;
463
+ const rebuild = new Map();
464
+ for (const d of decisions ?? []) {
465
+ if (d.action === "merge") {
466
+ for (const id of d.ids ?? []) {
467
+ if (id !== d.keepSource) vectorIndex.deleteEmbedding(id);
468
+ }
469
+ if (d.keepSource) {
470
+ const keeper = service.getById(d.keepSource);
471
+ if (keeper) rebuild.set(keeper.id, [keeper.title, keeper.content].filter(Boolean).join("\n"));
472
+ }
473
+ } else if (d.action === "archive" || d.action === "conflict") {
474
+ for (const id of d.ids ?? [d.loser]) vectorIndex.deleteEmbedding(id);
475
+ } else if (d.action === "update") {
476
+ const id = d.ids[0];
477
+ const mem = service.getById(id);
478
+ if (mem) {
479
+ vectorIndex.deleteEmbedding(id);
480
+ try {
481
+ const text = [mem.title, mem.content].filter(Boolean).join("\n");
482
+ const v = await embedder.embedSingle(text);
483
+ if (v?.length) vectorIndex.saveEmbedding(id, v);
484
+ } catch { /* best-effort */ }
485
+ }
486
+ }
487
+ }
488
+ for (const [id, text] of rebuild) {
489
+ try {
490
+ const v = await embedder.embedSingle(text);
491
+ if (v?.length) vectorIndex.saveEmbedding(id, v);
492
+ } catch { /* best-effort */ }
493
+ }
494
+ if (embedder.modelHash) vectorIndex.markModel?.(embedder.modelHash, embedder.dimension);
495
+ }
496
+
497
+ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, logger, semantic = null }) {
498
+ let pendingTimer = null;
499
+ let running = false;
500
+ let disposed = false;
501
+ let baseline = { count: 0, chars: 0 };
502
+ let inFlight = null;
503
+
504
+ function shouldTrigger(service) {
505
+ const memories = service.all().filter((m) => !m.archived && !m.session_disposed_at && m.type !== "summary");
506
+ const count = memories.length;
507
+ const chars = totalChars(memories);
508
+ const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
509
+ const overAbs = count >= thresholdCount || chars >= thresholdChars;
510
+ return { trigger: overAbs && overBase, count, chars };
511
+ }
512
+
513
+ function maybeSchedule(service) {
514
+ if (disposed || running || pendingTimer) return false;
515
+ const { trigger, count, chars } = shouldTrigger(service);
516
+ if (!trigger) return false;
517
+ pendingTimer = setTimeout(() => {
518
+ pendingTimer = null;
519
+ running = true;
520
+ // Defer the onRun invocation so a synchronous throw cannot escape the
521
+ // timer callback (which would crash the process) and skip the teardown.
522
+ // Errors are logged, never swallowed silently. inFlight lets dispose()
523
+ // await the running consolidation before the caller closes the store.
524
+ inFlight = Promise.resolve()
525
+ .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
526
+ .then((result) => {
527
+ // Refresh the baseline only for a successful run (design §5.3: an
528
+ // LLM failure must not move the baseline, so the next write can
529
+ // immediately re-trigger a retry). A `{ok:false}` result or a throw
530
+ // keeps the old baseline. A run that reports nothing is treated as
531
+ // completed without failure (no-op hooks / minimal test doubles).
532
+ if (result && result.ok) {
533
+ try {
534
+ baseline = shouldTrigger(service);
535
+ } catch (error) {
536
+ // Store closed mid-flight: keep the last known baseline.
537
+ logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
538
+ }
539
+ }
540
+ })
541
+ .catch((error) => {
542
+ logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
543
+ // Failed runs do not refresh the baseline.
544
+ })
545
+ .finally(() => {
546
+ running = false;
547
+ inFlight = null;
548
+ });
549
+ }, delayMs);
550
+ return true;
551
+ }
552
+
553
+ async function dispose() {
554
+ disposed = true;
555
+ if (pendingTimer) { clearTimeout(pendingTimer); pendingTimer = null; }
556
+ // An in-flight run is left to complete naturally (its LLM calls are
557
+ // already paid for and aborting would discard the work). Await it so the
558
+ // caller can close the store only after every write has landed.
559
+ if (inFlight) await inFlight.catch(() => {});
560
+ }
561
+
562
+ async function runDream(ctx, service, config) {
563
+ const logger = ctx.logger;
564
+ let memories = service.all().filter((m) => !m.archived && m.type !== "summary");
565
+ if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
566
+ // v0.4.4 滑动窗口:只 consolidation 最近 dreamMaxSnapshotSize 条记忆,
567
+ // 窗口外的旧记忆不进 snapshot(大记忆量下全量快照会撑爆 LLM 输入,配合
568
+ // 隐式 keep run 始终可收敛)。按 updated_at 倒序取前 maxSize 条。
569
+ const maxSize = Number.isInteger(config.dreamMaxSnapshotSize) ? config.dreamMaxSnapshotSize : 200;
570
+ memories = [...memories]
571
+ .sort((a, b) => {
572
+ const ta = String(a.updated_at ?? "");
573
+ const tb = String(b.updated_at ?? "");
574
+ if (ta < tb) return 1;
575
+ if (ta > tb) return -1;
576
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
577
+ })
578
+ .slice(0, Math.max(1, maxSize));
579
+ const snapshot = new Map(memories.map((m) => [m.id, m]));
580
+ const route = resolveRoute(ctx, config, logger);
581
+ const runId = randomUUID();
582
+ const snapshotHash = hashSnapshot([...snapshot.values()]);
583
+ // Conflict freeze (opt-in): when enabled, conflict decisions are parked for
584
+ // manual review instead of auto-adjudicated. Read once up front so the
585
+ // prompt hint and the apply-split agree on the same gate.
586
+ const freezeEnabled = config.conflictFreezeEnabled === true;
587
+ // Every exit (success or failure) funnels through `finish`, which writes
588
+ // the audit row + receipt. A record failure is logged, never thrown —
589
+ // auditing must not break the consolidation path. Failed runs still
590
+ // capture their decisions/outcome when the LLM produced a validated list
591
+ // (e.g. summary step failed after consolidation), so the partial write is
592
+ // replayable too.
593
+ const finish = (result) => {
594
+ // status is derived from what actually committed: ok only when the full
595
+ // decision list landed (or a summary was refreshed); noop when nothing
596
+ // changed; degraded when real changes landed without a summary;
597
+ // reconcile when decisions were validated but some did not commit (CAS
598
+ // conflict / rollback); failed on any LLM/validation error. No fake "ok"
599
+ // for an empty or partial run.
600
+ const status = result.status ?? (result.ok ? "ok" : "failed");
601
+ const applied = result.applied ?? 0;
602
+ const summaryStored = result.summary ?? false;
603
+ const receipt = buildReceipt({ runId, status, snapshotHash, inputCount: snapshot.size, applied, summaryStored });
604
+ try {
605
+ service.saveDreamRun({
606
+ id: runId,
607
+ status,
608
+ error: result.error,
609
+ provider: route?.provider,
610
+ model: route?.model,
611
+ snapshot_hash: snapshotHash,
612
+ input_count: snapshot.size,
613
+ // 裁决规则版本号:config.policyEpoch(默认 0)。规则升级后该行保留
614
+ // 当时的 epoch,旧裁决据此降级为历史证据(store getLatestPolicyEpoch
615
+ // 只负责读取当前生效版本,写入由这里完成)。
616
+ policy_epoch: config.policyEpoch ?? 0,
617
+ // Full input snapshot (canonical fields) so the exact arbitration
618
+ // input can be rebuilt offline from the audit row alone — the
619
+ // digest + decisions + outcome triple makes silent errors locatable
620
+ // even after the store has moved on.
621
+ input: [...snapshot.values()].map((m) => ({
622
+ id: m.id,
623
+ type: m.type,
624
+ title: m.title,
625
+ content: m.content,
626
+ importance: m.importance,
627
+ updated_at: m.updated_at
628
+ })),
629
+ decisions: result.decisions,
630
+ outcome: result.outcome,
631
+ applied,
632
+ summary_stored: summaryStored,
633
+ receipt
634
+ });
635
+ } catch (error) {
636
+ logger?.warn?.(`dsh-mneme dream: failed to record audit run: ${String(error)}`);
637
+ }
638
+ return { ...result, runId, receipt, snapshotHash };
639
+ };
640
+ if (!route) {
641
+ logger?.warn?.("dsh-mneme dream: no llm route available");
642
+ return finish({ ok: false, error: "no llm route", summary: false });
643
+ }
644
+
645
+ let listText;
646
+ if (semantic?.embedder && semantic?.vectorIndex) {
647
+ try {
648
+ const vectors = await collectVectors(memories, semantic);
649
+ if (vectors) {
650
+ const k = Math.min(10, Math.max(1, Math.floor(Math.sqrt(memories.length / 2))));
651
+ const clusters = clusterMemories(memories, vectors, k);
652
+ const conflicts = findPotentialConflicts(memories, vectors, 0.85);
653
+ const conflictIds = new Set(conflicts.flatMap((c) => [c.a.id, c.b.id]));
654
+ const parts = [];
655
+ clusters.forEach((cluster, ci) => {
656
+ parts.push(`# 聚类 ${ci + 1}`);
657
+ for (const m of cluster) {
658
+ parts.push(
659
+ `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}` +
660
+ (conflictIds.has(m.id) ? " | [潜在冲突]" : "")
661
+ );
662
+ }
663
+ });
664
+ listText = parts.join("\n");
665
+ logger?.info?.(`[dsh-mneme] dream semantic pre-group: ${clusters.length} clusters, ${conflicts.length} conflict pairs`);
666
+ }
667
+ } catch (error) {
668
+ logger?.warn?.(`[dsh-mneme] dream semantic pre-group failed: ${String(error)}`);
669
+ }
670
+ }
671
+ if (!listText) {
672
+ listText = [...snapshot.values()].map((m) =>
673
+ `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
674
+ ).join("\n");
675
+ }
676
+
677
+ // Freeze-aware prompt: in freeze mode the conflict branch still outputs
678
+ // winner/loser (validation requires them) but they are treated as tentative
679
+ // candidates the human makes the final call, not the model.
680
+ const consolidationPrompt = freezeEnabled
681
+ ? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
682
+ : CONSOLIDATION_PROMPT;
683
+ let decisionText;
684
+ try {
685
+ // Bug8: the consolidation call is audited (tokens/time/status). A throw
686
+ // re-propagates to the catch below; an aborted stream returns undefined
687
+ // and is treated as a failed run after the check below.
688
+ decisionText = await runAuditedLlm(ctx, service, config, {
689
+ triggerSource: "autoDream",
690
+ operationType: "dream_consolidate",
691
+ modelId: `${route.provider}:${route.model}`,
692
+ relatedMemoryIds: [...snapshot.keys()]
693
+ }, (reportUsage) => streamText(ctx, {
694
+ provider: route.provider,
695
+ model: route.model,
696
+ purpose: "compaction",
697
+ maxTokens: config.dreamMaxTokens ?? 4096,
698
+ ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
699
+ ? { reasoningEffort: config.dreamReasoningEffort }
700
+ : {}),
701
+ messages: [
702
+ { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
703
+ { role: "user", content: [{ type: "text", text: listText }] }
704
+ ]
705
+ }, reportUsage));
706
+ } catch (error) {
707
+ logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
708
+ return finish({ ok: false, error: "llm failed", summary: false });
709
+ }
710
+ if (decisionText === undefined) {
711
+ logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
712
+ return finish({ ok: false, error: "llm failed", summary: false });
713
+ }
714
+
715
+ // v0.5.3 字段名归一化兜底:thinking 模型可能输出别名键/wrapper 对象,
716
+ // 在 validateDecisions 之前重写到规范字段名,语义正确但 schema 不听话的
717
+ // 输出不再整单被拒。
718
+ const decisions = normalizeDecisions(extractJsonArray(decisionText));
719
+ if (!Array.isArray(decisions)) {
720
+ logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0})`);
721
+ return finish({ ok: false, error: "no json array in llm output", summary: false });
722
+ }
723
+ const { ok, errors, skipped = [] } = validateDecisions(decisions, snapshot, {
724
+ maxUpdatePerRun: config.reflectionUpdateMaxPerRun,
725
+ minAgeHours: config.reflectionUpdateMinAgeHours,
726
+ // v0.4.4 fix:显式透传,用户配 dreamImplicitKeep:false 时严格模式必须
727
+ // 真正生效,dreamMinExplicitCoverage 决定隐式 keep 下的覆盖率下限。
728
+ dreamImplicitKeep: config.dreamImplicitKeep,
729
+ dreamMinExplicitCoverage: config.dreamMinExplicitCoverage,
730
+ // Issue #26 (P0):跨类型 merge 等"单条非法"决策不再拖垮整批——默认开启
731
+ // skipInvalid,非法决策跳过、合法子集照常应用(run 记为 degraded)。
732
+ // dreamSkipInvalid:false 可恢复旧的"任意非法即整单拒绝"。
733
+ skipInvalid: config.dreamSkipInvalid !== false,
734
+ // Issue #26 (P1):显式开启 allowCrossTypeMerge 后放宽跨类型合并检查。
735
+ allowCrossTypeMerge: config.allowCrossTypeMerge === true
736
+ });
737
+ if (!ok) {
738
+ logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
739
+ return finish({ ok: false, error: `invalid decisions: ${errors.length} errors`, summary: false });
740
+ }
741
+ for (const s of skipped) {
742
+ logger?.warn?.(`dsh-mneme dream: skipping invalid decision[${s.index}] (${s.action}): ${s.error}`);
743
+ }
744
+
745
+ // Capture pre-update snapshots so the audit records what each update changed.
746
+ const updateSnapshots = {};
747
+ for (const d of decisions) {
748
+ if (d.action === "update") {
749
+ const mem = snapshot.get(d.ids[0]);
750
+ if (mem) updateSnapshots[d.ids[0]] = { title: mem.title, content: mem.content, importance: mem.importance };
751
+ }
752
+ }
753
+
754
+ // Conflict freeze (opt-in): when enabled, conflict decisions are not
755
+ // auto-adjudicated no winner kept, no loser archived. The pair is parked
756
+ // in conflict_pending for human review instead. Best-effort: a store
757
+ // failure here must never block the run (fail-safe the memories are left
758
+ // untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
759
+ // bounds the review queue; overflow is skipped with a warning.
760
+ let frozenCount = 0;
761
+ const frozenIds = [];
762
+ const applyList = freezeEnabled ? decisions.filter((d) => d.action !== "conflict") : decisions;
763
+ if (freezeEnabled) {
764
+ const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
765
+ if (conflictsToFreeze.length > 0) {
766
+ try {
767
+ const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
768
+ const pendingNow = service.countConflictPending();
769
+ const budget = Math.max(0, maxPending - pendingNow);
770
+ const toFreeze = conflictsToFreeze.slice(0, budget);
771
+ if (conflictsToFreeze.length > budget) {
772
+ logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
773
+ }
774
+ for (const d of toFreeze) {
775
+ try {
776
+ service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
777
+ frozenCount++;
778
+ frozenIds.push(d.winner, d.loser);
779
+ } catch (error) {
780
+ logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
781
+ }
782
+ }
783
+ } catch (error) {
784
+ logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
785
+ }
786
+ }
787
+ }
788
+
789
+ // CAS-guarded, per-decision-transactional apply against the run snapshot:
790
+ // a target changed during the LLM call is skipped and reported as a
791
+ // conflict instead of being overwritten (item ①). Frozen conflicts are
792
+ // excluded from this list (they are parked, not applied).
793
+ const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot, config);
794
+ // Per-record receipt chain: one row per actually-committed merge/conflict/
795
+ // update verdict, stamped with the decision-basis digest + idempotency
796
+ // counters (count_before count_after). Written here, before the run audit
797
+ // row, so the verdict trail always precedes the run trail it belongs to.
798
+ // Bookkeeping: a write failure is logged and swallowed — it must never
799
+ // block the consolidation flow.
800
+ try {
801
+ for (const r of buildRecordReceipts({ runId, committed, snapshot, policyEpoch: config.policyEpoch ?? 0 })) {
802
+ service.saveReceipt(r);
803
+ }
804
+ } catch (error) {
805
+ logger?.warn?.(`dsh-mneme dream: failed to write per-record receipt: ${String(error)}`);
806
+ }
807
+ // Attach the pre-update snapshot to the audit copy of each update decision
808
+ // so the recorded row shows the before/after delta, not just the target.
809
+ const auditDecisions = decisions.map((d) =>
810
+ d.action === "update" && updateSnapshots[d.ids[0]]
811
+ ? { ...d, _before: updateSnapshots[d.ids[0]] }
812
+ : d
813
+ );
814
+ // Outcome is derived from the ACTUALLY committed sub-steps, never from the
815
+ // raw LLM decision list a merge whose archive step rolled back must not
816
+ // claim "merge-archived" (item ②). Conflicts/failures/skipped ride along
817
+ // so the audit row records why the run diverged (Issue #26: skipped =
818
+ // decisions dropped by skipInvalid because they were individually invalid,
819
+ // e.g. cross-type merge).
820
+ const outcome = { ...buildOutcome(committed), conflicts, failures, skipped };
821
+ // Frozen conflicts were not adjudicated: mark both sides pending in the
822
+ // per-id outcome so the audit row shows they were parked, not skipped.
823
+ if (frozenIds.length) {
824
+ for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
825
+ }
826
+ // Decisions validated but not fully committed reconcile (not ok).
827
+ const partial = conflicts.length > 0 || failures.length > 0;
828
+ // No decision landed (all-keep, or every decision skipped as an idempotent
829
+ // replay) nothing substantive changed. Distinct from a success: such a
830
+ // run must never be reported as ok, or the audit claims work that never
831
+ // happened and the scheduler refreshes the baseline on a false positive.
832
+ // Frozen conflicts are substantive output (parked for review), so a run
833
+ // that only froze conflicts is not a noop.
834
+ const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
835
+
836
+ // v0.6.2 auto-tag: a light LLM pass over the retained (post-consolidation)
837
+ // memories. Opt-in via config.autoTagEnabled, bounded by autoTagMaxPerRun,
838
+ // and always fail-safe a tag failure must never change the consolidation
839
+ // outcome reported below (it is logged and counted, nothing more).
840
+ let autoTagged = 0;
841
+ if (config.autoTagEnabled === true) {
842
+ try {
843
+ const tagResult = await runAutoTag({ ctx, service, config, route });
844
+ autoTagged = tagResult?.tagged ?? 0;
845
+ if (tagResult?.ok === false && tagResult?.skippedBy && tagResult.skippedBy !== "empty") {
846
+ logger?.warn?.(`dsh-mneme dream: auto-tag skipped (${tagResult.skippedBy})`);
847
+ } else if (autoTagged > 0) {
848
+ logger?.info?.(`[dsh-mneme] auto-tag: ${autoTagged} memory(ies) tagged`);
849
+ }
850
+ } catch (error) {
851
+ logger?.warn?.(`dsh-mneme dream: auto-tag failed: ${String(error)}`);
852
+ }
853
+ }
854
+
855
+ // Keep the vector index consistent with the post-dream store state.
856
+ if (semantic?.embedder && semantic?.vectorIndex) {
857
+ try {
858
+ await maintainIndexAfterDream(applyList, service, semantic);
859
+ } catch (error) {
860
+ logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
861
+ }
862
+ }
863
+
864
+ // Summary generation (second LLM call). A throwing stream is reported as
865
+ // a failed run; summary:false marks a run that produced no summary.
866
+ let summaryText;
867
+ try {
868
+ // Bug8: the summary call is audited too (operation dream_summarize).
869
+ summaryText = await runAuditedLlm(ctx, service, config, {
870
+ triggerSource: "autoDream",
871
+ operationType: "dream_summarize",
872
+ modelId: `${route.provider}:${route.model}`,
873
+ relatedMemoryIds: []
874
+ }, (reportUsage) => streamText(ctx, {
875
+ provider: route.provider,
876
+ model: route.model,
877
+ purpose: "compaction",
878
+ maxTokens: config.dreamMaxTokens ?? 2048,
879
+ ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
880
+ ? { reasoningEffort: config.dreamReasoningEffort }
881
+ : {}),
882
+ messages: [
883
+ { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
884
+ { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && !m.session_disposed_at && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
885
+ ]
886
+ }, reportUsage));
887
+ } catch (error) {
888
+ logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
889
+ return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
890
+ }
891
+ let summaryStored = false;
892
+ if (summaryText !== undefined && summaryText.trim()) {
893
+ // Bug5 carve-out: the library overview is regenerated every run, so it
894
+ // must REPLACE the previous overview (not append that would grow the
895
+ // summary unboundedly). `_overwrite` still archives the old overview into
896
+ // content_history before replacing it.
897
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: summaryText.trim(), importance: 5, source: "dream", _overwrite: true });
898
+ summaryStored = true;
899
+ // Re-embed the fresh summary so the index stays in sync with the store.
900
+ if (semantic?.embedder && semantic?.vectorIndex) {
901
+ try {
902
+ const summary = service.all().find((m) => m.type === "summary");
903
+ if (summary) {
904
+ const v = await semantic.embedder.embedSingle([summary.title, summary.content].filter(Boolean).join("\n"));
905
+ if (v?.length) semantic.vectorIndex.saveEmbedding(summary.id, v);
906
+ if (semantic.embedder.modelHash) semantic.vectorIndex.markModel?.(semantic.embedder.modelHash, semantic.embedder.dimension);
907
+ }
908
+ } catch { /* best-effort */ }
909
+ }
910
+ }
911
+ // Honest status assignment (never a fake ok):
912
+ // reconcile some decisions validated but did not commit (CAS/rollback).
913
+ // noop nothing changed and no summary persisted: truly an empty
914
+ // run. ok:false keeps the scheduler from moving the baseline.
915
+ // ok — either real changes landed, or a fresh summary was stored
916
+ // (all-keep + summary is a substantive summary refresh).
917
+ // degraded — real consolidation landed but the run did not produce its
918
+ // full output: the summary came back empty/missing, or
919
+ // (Issue #26) some individually-invalid decisions were
920
+ // skipped by skipInvalid. The valid subset was absorbed (ok
921
+ // for the baseline — a future run won't re-fail on the same
922
+ // permanently-invalid pairs), but the run is marked, not faked.
923
+ let status;
924
+ let okResult;
925
+ if (partial) {
926
+ status = "reconcile";
927
+ okResult = false;
928
+ } else if (noChange) {
929
+ status = summaryStored ? "ok" : "noop";
930
+ okResult = summaryStored;
931
+ } else if (skipped.length > 0) {
932
+ // Issue #26: valid subset landed but at least one decision was dropped as
933
+ // invalid (e.g. cross-type merge). degraded (not ok) — never a fake ok.
934
+ // autoTag still runs on degraded runs, so it is not blocked behind a
935
+ // "success" that a skipped-invalid run can never reach.
936
+ status = "degraded";
937
+ okResult = true;
938
+ } else {
939
+ status = summaryStored ? "ok" : "degraded";
940
+ okResult = true;
941
+ }
942
+ return finish({
943
+ ok: okResult,
944
+ status,
945
+ applied,
946
+ decisions: auditDecisions,
947
+ outcome,
948
+ conflicts,
949
+ failures,
950
+ skipped,
951
+ frozen: frozenCount,
952
+ summary: summaryStored,
953
+ error: skipped.length > 0 ? `skipped ${skipped.length} invalid decision(s)` : undefined
954
+ });
955
+ }
956
+
957
+ return { maybeSchedule, runDream, dispose };
958
+ }