@modusensus/dsh-mneme 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -269
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -361
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2087
  42. package/lib/settings.js +430 -420
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -510
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -269
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -361
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2087
  95. package/src/settings.js +430 -420
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1482
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -161
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -249
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -348
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
@@ -1,658 +1,658 @@
1
- import { STR, langOf } from "../lang.js";
2
-
3
- // Issue #126:sleepActionSet="full" 时新增两个动作——supersede(演进:新版取代
4
- // 旧版)与 differentiate(互补:两条都留、各追加差异注记)。两者的校验与执行都
5
- // 复用既有 merge/conflict 的机制(winner/loser、casGuard、transaction、receipt)。
6
- // 调用方(sleep)按档位派生「本档允许的动作集合」时需要读它,故导出。
7
- export const ACTIONS = new Set(["keep", "merge", "archive", "conflict", "update", "create", "supersede", "differentiate"]);
8
-
9
- // Epistemic trust (v0.4.5): when config.trustEpistemicWeighting is on, merge
10
- // keepSource and conflict winners prefer the higher-trust memory. Higher value
11
- // = preferred. observation (measured) > inferred (derived) > subjective (guess).
12
- const EPISTEMIC_PRIORITY = { observation: 3, inferred: 2, subjective: 1 };
13
-
14
- // Issue #104 方向 2:archive 类型护栏的长保留类型集合——这些类型的存在意义
15
- // 就是长期保存(踩坑记录、约束、用户偏好、挖掘出的模式),LLM 以「价值判断」
16
- // 类理由批量归档它们时误伤损失最大。conflict 裁决的败者归档不经过 archive
17
- // action(走 applyDecisions 的 conflict 分支),不受此护栏影响。
18
- const ARCHIVE_GUARDED_TYPES = new Set(["preference", "pattern", "rejected_solution", "constraint", "pitfall"]);
19
- // 「重复 / 过时」类理由的关键词(中英双语)。命中才允许归档长保留类型;
20
- // 词表宁可放宽也不误拦——护栏只跳过单条并落明细,不整单拒绝。
21
- const ARCHIVE_RATIONALE_RE = /重复|过时|陈旧|过期|已被取代|被取代|冗余|不再使用|旧版|废弃|stale|outdated|obsolete|dup(?:licate|licat)?|superseded|redundant|deprecated|expired|replaced/i;
22
-
23
- /**
24
- * Validate a dream decision list against a snapshot of eligible memories.
25
- * @param decisions - LLM-produced decision list. In skipInvalid mode, invalid
26
- * entries are spliced out of this array in place (the caller reuses the same
27
- * reference downstream for apply/audit); implicit keeps are appended here too.
28
- * @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
29
- * @returns {{ok: boolean, errors: string[], skipped?: Array<{index, action, ids, error}>,
30
- * resolvedShortIds?: number}}
31
- */
32
- export function validateDecisions(decisions, snapshot, options = {}) {
33
- const errors = [];
34
- // Issue #89 回归修复(v0.6.9 / Issue #26 的 skipInvalid 路径原样移植,该路径
35
- // 在 v0.7.11 重写中丢失):skipInvalid 开启时,单条非法决策只跳过该条(记录
36
- // 到 skipped、不 claim 任何 id),合法子集照常应用,调用方据此把 run 记为
37
- // degraded。全局信号(update/create 上限、显式覆盖率下限)依旧整单拒绝——
38
- // 刷爆上限或覆盖率不达标的输出是模型坏了,不是轻微 schema 漂移。
39
- const skipped = [];
40
- const survivors = [];
41
- const skipInvalid = options.skipInvalid === true;
42
- const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
43
- const minAgeHours = options.minAgeHours ?? 24;
44
- // Issue #126 review(Copilot):档位白名单。sleepActionSet 默认档只换 prompt 是
45
- // 不够的——ACTIONS 是两个模块共用的,模型自发出 supersede / differentiate 时校验器
46
- // 照样放行,"opt-in 零行为变化"就成了空话。省略 / null = 不限制(沿用全局 ACTIONS)。
47
- const allowedActions = Array.isArray(options.allowedActions) ? new Set(options.allowedActions) : null;
48
- if (!Array.isArray(decisions)) {
49
- return { ok: false, errors: ["decision list must be an array"], resolvedShortIds: 0 };
50
- }
51
- // 空决策 = 模型完整评估后确认无需操作(CONSOLIDATION_PROMPT 明确允许"无问题的
52
- // 条目无需输出")。合法 JSON [] 不是空体(那是无输出/截断),也不是"残缺输出"
53
- // ——显式短路直接 ok,避免隐式 keep 的覆盖率检查把 0% 误判为模型坏了。与
54
- // sleep 的空模式(skipped no-op)语义对齐:下游 applied=0、audit 记 ok。
55
- if (decisions.length === 0) {
56
- return { ok: true, errors: [], skipped: [], resolvedShortIds: 0 };
57
- }
58
- // Issue #135:模型常把 36 位 UUID 回填成前缀(实测 78/78 个 8 位前缀都能唯一
59
- // 对应窗口内真实记忆,且 few-shot 示例的 "m1"/"m2" 占位符在诱导这种缩写),而
60
- // 下方校验用 snapshot.get(id) 整串精确匹配 → 全部 unknown id → claimed=0 →
61
- // 覆盖率闸整单拒绝,一整轮语义成果被丢。校验前先把「唯一前缀」解析回完整 id
62
- // (git 短哈希式):仅在 snapshot 内解析,有歧义或匹配不到就原样保留,仍由下
63
- // 方 unknown id 校验如实报错。就地改写 ids / keepSource / winner / loser,下
64
- // 游 applyDecisions 与审计拿到的同样是完整 id。
65
- let resolvedShortIds = 0;
66
- const resolveShortId = (value) => {
67
- if (typeof value !== "string" || snapshot.has(value)) return value;
68
- // 太短不猜(歧义概率高);长度 ≥36 说明不是前缀缩写,交给校验如实报错。
69
- if (value.length < 8 || value.length >= 36) return value;
70
- let hit = null;
71
- let matches = 0;
72
- for (const id of snapshot.keys()) {
73
- if (id.startsWith(value)) {
74
- hit = id;
75
- if (++matches > 1) return value; // 有歧义,不解析
76
- }
77
- }
78
- if (matches === 1) {
79
- resolvedShortIds++;
80
- return hit;
81
- }
82
- return value;
83
- };
84
- for (const d of decisions) {
85
- if (!d || typeof d !== "object") continue;
86
- if (Array.isArray(d.ids)) d.ids = d.ids.map(resolveShortId);
87
- if (typeof d.keepSource === "string") d.keepSource = resolveShortId(d.keepSource);
88
- if (typeof d.winner === "string") d.winner = resolveShortId(d.winner);
89
- if (typeof d.loser === "string") d.loser = resolveShortId(d.loser);
90
- }
91
- const claimed = new Set();
92
- for (const [index, d] of decisions.entries()) {
93
- const at = `decision[${index}]`;
94
- // 单条校验错误先进 local:skipInvalid 模式下整条跳过,严格模式下才并入
95
- // 全局 errors(沿用 v0.6.9 的双轨结构)。
96
- const local = [];
97
- // Issue #126:supersede 与 conflict 一样用 winner/loser 定位双方(沿用同一套
98
- // 字段,校验与 receipt 逻辑因此可以直接复用)。
99
- const ids = d && (d.action === "conflict" || d.action === "supersede") ? [d.winner, d.loser] : (d?.ids ?? []);
100
- if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
101
- local.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
102
- } else if (allowedActions && !allowedActions.has(d.action)) {
103
- // 动作本身合法,但不在当前档位允许的集合里(例如默认档收到 supersede)。
104
- local.push(`${at}: action ${JSON.stringify(d.action)} not allowed in this mode`);
105
- } else if (d.action === "conflict" || d.action === "supersede") {
106
- if (!d.winner || !d.loser || d.winner === d.loser) {
107
- local.push(`${at}: ${d.action} needs distinct winner and loser`);
108
- }
109
- } else if (d.action === "differentiate") {
110
- // Issue #126:互补型——两条都留下、各追加差异注记。ids 必须 ≥2(随后走下方
111
- // 通用 id 校验:unknown / archived / summary / 重复 claim),distinctions 必须
112
- // 非空,否则会写出空注记(写了等于没写,还会污染正文)。
113
- if (!Array.isArray(d.ids) || d.ids.length < 2) {
114
- local.push(`${at}: differentiate needs at least two ids`);
115
- } else if (!Array.isArray(d.distinctions) || !d.distinctions.some((s) => typeof s === "string" && s.trim())) {
116
- local.push(`${at}: differentiate needs a non-empty distinctions array`);
117
- }
118
- } else if (d.action === "create") {
119
- // Mint a fresh memory (sleep pattern discovery). Claims no existing id,
120
- // so it skips the claiming loop below; evidence is optional provenance
121
- // (already filtered to real ids by the caller) and is stored in content.
122
- if (typeof d.title !== "string" || !d.title.trim()) {
123
- local.push(`${at}: create needs non-empty title`);
124
- }
125
- if (typeof d.content !== "string" || !d.content.trim()) {
126
- local.push(`${at}: create needs non-empty content`);
127
- }
128
- if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
129
- local.push(`${at}: create importance must be an integer 1-5 when provided`);
130
- }
131
- if (typeof d.type !== "string" || !d.type.trim()) {
132
- local.push(`${at}: create needs non-empty type`);
133
- }
134
- } else if (!Array.isArray(d.ids) || d.ids.length === 0) {
135
- local.push(`${at}: ${d.action} needs non-empty ids`);
136
- }
137
- // update-specific field validation runs BEFORE claiming ids, so a failing
138
- // update never pollutes the claimed set (which drives the "every id must
139
- // appear in a decision" check below).
140
- // Issue #104 方向 2:archive 类型护栏。长保留类型的 archive 决策必须携带
141
- // 「重复 / 过时」类理由(提示词对 archive 的定义本就如此),「价值判断」类
142
- // 理由(保持整洁、参考价值低……)不放行——单条跳过记 skipped(run 记
143
- // degraded,明细进 dream_runs.skipped),绝不整单拒绝。未知 id 在下方通用
144
- // 校验里另行报错,这里 snapshot.get 为 undefined 时跳过护栏判断。
145
- if (local.length === 0 && d?.action === "archive") {
146
- const guardedTypes = new Set();
147
- for (const id of d.ids) {
148
- const mem = snapshot.get(id);
149
- if (mem && ARCHIVE_GUARDED_TYPES.has(mem.type)) guardedTypes.add(mem.type);
150
- }
151
- if (guardedTypes.size > 0 && !ARCHIVE_RATIONALE_RE.test(String(d.reason ?? ""))) {
152
- local.push(`${at}: archive of long-retention type(s) ${[...guardedTypes].join(", ")} needs a duplicate/outdated rationale (重复/过时), got: ${JSON.stringify(String(d.reason ?? "")).slice(0, 60)}`);
153
- }
154
- }
155
- if (local.length === 0 && d?.action === "update") {
156
- // 只能更新单条
157
- if (!Array.isArray(d.ids) || d.ids.length !== 1) {
158
- local.push(`${at}: update must target exactly one id`);
159
- } else {
160
- // 必须产生实际变化
161
- const mem = snapshot.get(d.ids[0]);
162
- const hasChange = (d.title !== undefined && d.title !== mem?.title)
163
- || (d.content !== undefined && d.content !== mem?.content)
164
- || (d.importance !== undefined && d.importance !== mem?.importance);
165
- if (!hasChange) {
166
- local.push(`${at}: update must change at least one field`);
167
- } else if (mem?.type === "summary") {
168
- // 不能更新 summary
169
- local.push(`${at}: cannot update summary via update action`);
170
- } else {
171
- // 保护期:新建记忆不可立即被 update(可配置)
172
- const ageHours = (Date.now() - new Date(mem?.created_at).getTime()) / 3600000;
173
- if (ageHours < minAgeHours) {
174
- local.push(`${at}: memory too young (< ${minAgeHours}h)`);
175
- }
176
- }
177
- }
178
- }
179
- if (local.length === 0 && d && d.action !== "create") {
180
- // seen 捕获同一条决策内的重复 id;claimed 只含先前存活决策的 id
181
- // (被跳过的决策不 claim,其目标留给其它合法决策/隐式 keep)。
182
- const seen = new Set();
183
- for (const id of ids) {
184
- const mem = snapshot.get(id);
185
- if (!mem) {
186
- local.push(`${at}: unknown id ${JSON.stringify(id)}`);
187
- } else if (mem.archived || mem.type === "summary") {
188
- local.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
189
- }
190
- if (claimed.has(id) || seen.has(id)) {
191
- local.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
192
- }
193
- seen.add(id);
194
- }
195
- if (local.length === 0 && d.action === "merge") {
196
- if (!d.keepSource || !d.ids.includes(d.keepSource)) {
197
- local.push(`${at}: merge keepSource must be one of ids`);
198
- }
199
- if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
200
- local.push(`${at}: merge needs non-empty title and content`);
201
- }
202
- if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
203
- local.push(`${at}: merge importance must be an integer 1-5 when provided`);
204
- }
205
- // Merging across types would blur preference/project/decision boundaries
206
- // in the injected context; the snapshot carries each entry's type.
207
- // Issue #26 (P1):默认禁止跨类型合并。用户显式开启 allowCrossTypeMerge
208
- // 后放宽该检查,类型边界由用户自行承担。
209
- const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
210
- if (mergeTypes.size > 1 && options.allowCrossTypeMerge !== true) {
211
- local.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
212
- }
213
- }
214
- }
215
- if (local.length > 0) {
216
- if (skipInvalid) {
217
- // 单条非法 → 跳过该决策,不 claim id(其目标记忆留给其它合法决策/隐式
218
- // keep),并记录到 skipped 供调用方日志/审计。信息性跳过绝不写入全局
219
- // errors,否则会误触发下方的整单拒绝。
220
- skipped.push({ index, action: d?.action, ids, error: local.join("; ") });
221
- } else {
222
- errors.push(...local);
223
- }
224
- continue;
225
- }
226
- if (d.action !== "create") {
227
- for (const id of ids) claimed.add(id);
228
- }
229
- survivors.push(d);
230
- }
231
- // Cap update churn: too many edits in one cycle signals a runaway model.
232
- // 全局信号——skipInvalid 模式下依旧整单拒绝(见函数头注释)。
233
- const updateCount = survivors.filter((d) => d.action === "update").length;
234
- if (updateCount > maxUpdatePerRun) {
235
- errors.push(`too many update decisions: ${updateCount} > ${maxUpdatePerRun}`);
236
- }
237
- // Cap pattern minting per run (sleepMaxPatternPerRun passes through here).
238
- const createCount = survivors.filter((d) => d.action === "create").length;
239
- const maxCreatePerRun = options.maxCreatePerRun ?? 5;
240
- if (createCount > maxCreatePerRun) {
241
- errors.push(`too many create decisions: ${createCount} > ${maxCreatePerRun}`);
242
- }
243
- // Issue #104 方向 2:archive 批量上限——一次性大扫除(12 条互不相关主题被
244
- // 批量归档)是失控信号,与 update 上限同一类全局闸门:skipInvalid 也不豁免,
245
- // 超限整单拒绝;正常的大规模清理由用户调高 dreamMaxArchivePerRun。
246
- const archiveCount = survivors.filter((d) => d.action === "archive").length;
247
- const maxArchivePerRun = options.maxArchivePerRun ?? 8;
248
- if (archiveCount > maxArchivePerRun) {
249
- errors.push(`too many archive decisions: ${archiveCount} > ${maxArchivePerRun}`);
250
- }
251
- // Issue #89 防洗白核心(#104 方向 1 重审后保留):全部决策都被跳过、合法
252
- // 子集为空时仍整单拒绝——宽容的前提是「有合法子集可应用」;模型输出整体
253
- // 非法(如全部幻觉 id)是真故障,不能被隐式 keep 洗成 ok。#104 只豁免
254
- // 「有合法子集但覆盖率不足」的良性挑重点(见下方 coverageShortfall)。
255
- if (options.skipInvalid === true && skipped.length > 0 && survivors.length === 0 && errors.length === 0) {
256
- errors.push(`all ${skipped.length} decision(s) invalid — nothing valid survived validation`);
257
- return { ok: false, errors, skipped, resolvedShortIds };
258
- }
259
- // v0.4.4: 隐式 keep。默认(dreamImplicitKeep !== false)下,未 claim 的
260
- // snapshot 记忆自动补 {action:"keep"},而不是整体拒绝——大记忆量下 LLM 漏报
261
- // 一两条就全拒(636 记忆 → 677 errors)会白白浪费整轮 run。设 false 则保留
262
- // 旧的严格"全量覆盖"校验。补齐的 keep 直接 append 到 decisions,调用方
263
- // (runDream/applyDecisions/audit)复用同一数组即可覆盖全部 snapshot 记忆。
264
- //
265
- // v0.4.4 fix(残缺输出防洗白)→ Issue #104 方向 1 重审:显式覆盖率护栏的
266
- // 初衷是拦「输出截断 → 只 claim 少量 → 其余被隐式 keep 洗白」,但它无法区分
267
- // 恶性截断与良性挑重点——而提示词硬性规则本身要求「无问题的条目无需输出」,
268
- // 挑重点正是要求的行为。官方路由 + 强模型的实测(heptaspirit:81 轮 failed
269
- // 全是 coverage,LLM 调用本身成功、applied=0)证明这是常规路径而非边角。
270
- // 处置:覆盖率不足不再 ok:false 整单拒绝,改为返回 coverageShortfall 理由、
271
- // 照常补齐隐式 keep——调用方把 run 记 degraded(合法子集已应用),护栏以
272
- // 状态暴露而非一票否决,与 skipInvalid 同一宽容哲学。明确异常信号(create
273
- // 上限等硬错误)保持整单拒绝。要恢复旧行为可设 dreamImplicitKeep:false
274
- // (严格模式,缺失即 error)或 dreamMinExplicitCoverage: 0(关护栏)。
275
- // 非覆盖类硬错误(create 上限溢出、严格模式缺失 id)仍然先整单拒绝——
276
- // #104 方向 1 只豁免 coverage 这一个信号,防洗白语义对它们原样保留。
277
- if (errors.length > 0) {
278
- return { ok: false, errors, skipped, resolvedShortIds };
279
- }
280
- const minCoverage = options.dreamMinExplicitCoverage ?? 0.5;
281
- let coverageShortfall = null;
282
- if (options.dreamImplicitKeep !== false) {
283
- const coverage = snapshot.size > 0 ? claimed.size / snapshot.size : 1;
284
- if (coverage < minCoverage) {
285
- coverageShortfall = `explicit decision coverage ${Math.round(coverage * 100)}% < minimum ${Math.round(minCoverage * 100)}%`;
286
- }
287
- for (const id of snapshot.keys()) {
288
- if (!claimed.has(id)) survivors.push({ action: "keep", ids: [id] });
289
- }
290
- } else {
291
- for (const id of snapshot.keys()) {
292
- if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
293
- }
294
- if (errors.length > 0) return { ok: false, errors, skipped, resolvedShortIds };
295
- }
296
- // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
297
- // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
298
- // 不能以 survivors.length !== decisions.length 作为是否 splice 的判据:
299
- // 当"被跳过的非法决策数 == 隐式补齐的 keep 数"时长度回到相等但内容已变,
300
- // 被跳过的决策会残留进 apply/audit。一律无条件 splice 最安全。
301
- decisions.splice(0, decisions.length, ...survivors);
302
- return { ok: true, errors, skipped, resolvedShortIds, coverageShortfall };
303
- }
304
-
305
- /** Marker thrown when a decision target changed since the run snapshot. */
306
- export class CasConflictError extends Error {
307
- constructor(action, ids, reason) {
308
- super(`cas conflict: ${action} targets changed since snapshot (${reason})`);
309
- this.name = "CasConflictError";
310
- this.action = action;
311
- this.ids = ids;
312
- }
313
- }
314
-
315
- function decisionIds(d) {
316
- return d.action === "conflict" || d.action === "supersede" ? [d.winner, d.loser] : (d.ids ?? []);
317
- }
318
-
319
- /**
320
- * CAS guard (item ①): every target memory must still match what the run
321
- * snapshot captured — otherwise the decision was computed against stale state
322
- * and applying it would overwrite a concurrent edit. Snapshotless replays skip
323
- * the guard entirely (per-action idempotency checks handle those). Throws
324
- * CasConflictError on the first mismatch; the caller's transaction rolls back.
325
- */
326
- function casGuard(service, snapshot, ids) {
327
- if (!snapshot) return;
328
- for (const id of ids) {
329
- const expect = snapshot.get(id);
330
- if (!expect) continue; // not in snapshot: validated elsewhere, skip guard
331
- const current = service.getById(id);
332
- if (!current) {
333
- throw new CasConflictError("deleted", [id], `memory ${id} was removed`);
334
- }
335
- const changed = expect.updated_at !== undefined
336
- ? current.updated_at !== expect.updated_at
337
- : current.content !== expect.content || current.title !== expect.title;
338
- if (changed) {
339
- throw new CasConflictError(
340
- "changed",
341
- [id],
342
- `memory ${id} was concurrently modified (expected updated_at=${expect.updated_at}, got ${current.updated_at})`
343
- );
344
- }
345
- }
346
- }
347
-
348
- /**
349
- * Apply a validated decision list to the service. Caller must validate first.
350
- * Each decision runs inside its own SQLite transaction (item ②): the multi-step
351
- * mutation of a decision is atomic, so a merge can never leave "keeper updated
352
- * but source not archived" or vice versa — a throwing sub-step rolls the whole
353
- * decision back.
354
- *
355
- * @param decisions - validated decision list.
356
- * @param service - memory service (saveWithDedupe/getById/update/setArchived/transaction).
357
- * @param logger - optional logger ({ warn }); per-decision failures are logged.
358
- * @param snapshot - optional Map<id, memory> captured before the LLM call; when
359
- * provided, every decision target is CAS-checked against it and a decision
360
- * computed from stale state is skipped and reported as a conflict instead of
361
- * overwriting concurrent writes (item ①).
362
- * @returns {{ applied: number, conflicts: Array, failures: Array, committed: Array }}
363
- * applied - number of decisions/memories actually committed (archive counts
364
- * each archived memory as one, merge/conflict/update count one).
365
- * conflicts - decisions skipped because a target changed since the snapshot.
366
- * failures - decisions that threw mid-transaction (fully rolled back).
367
- * committed - the decisions that actually landed, for outcome/receipt based
368
- * on real committed sub-steps rather than the raw LLM list.
369
- */
370
- export function applyDecisions(decisions, service, logger = null, snapshot = null, config = {}) {
371
- let applied = 0;
372
- const conflicts = [];
373
- const failures = [];
374
- const committed = [];
375
- for (const [i, d] of decisions.entries()) {
376
- try {
377
- // keep is a confirmed no-op: it commits nothing but still records the
378
- // per-id disposition so the outcome covers every snapshot memory.
379
- if (d.action === "keep") {
380
- committed.push({ action: "keep", ids: d.ids });
381
- continue;
382
- }
383
- const outcome = applyOne(d, service, snapshot, config);
384
- if (outcome === "skipped") continue;
385
- applied += outcome.applied;
386
- committed.push(outcome.committed);
387
- } catch (error) {
388
- if (error instanceof CasConflictError) {
389
- conflicts.push({ index: i, action: d.action, ids: error.ids, reason: error.message });
390
- logger?.warn?.(`dsh-mneme dream: ${error.message}`);
391
- } else {
392
- failures.push({ index: i, action: d.action, ids: decisionIds(d), reason: error.message });
393
- logger?.warn?.(`dsh-mneme dream: failed to apply ${d.action} at index ${i}: ${error.message}`);
394
- }
395
- }
396
- }
397
- return { applied, conflicts, failures, committed };
398
- }
399
-
400
- function applyOne(d, service, snapshot, config = {}) {
401
- switch (d.action) {
402
- case "archive": return applyArchive(d, service, snapshot);
403
- case "merge": return applyMerge(d, service, snapshot, config);
404
- case "conflict": return applyConflict(d, service, snapshot, config);
405
- case "supersede": return applySupersede(d, service, snapshot, config);
406
- case "differentiate": return applyDifferentiate(d, service, snapshot, config);
407
- case "create": return applyCreate(d, service, config);
408
- default: return applyUpdate(d, service, snapshot, config);
409
- }
410
- }
411
-
412
- /**
413
- * Highest-epistemic-priority UNARCHIVED id among `ids` (ties break toward
414
- * `preferred`). Archived memories are never eligible keepers — promoting one
415
- * would demote the real keepSource to a source and then hit the archived-keeper
416
- * guard in applyMerge, silently skipping the whole merge. When `preferred`
417
- * itself is archived (or missing), fall back to any unarchived candidate.
418
- */
419
- function pickBestKeeper(ids, preferred, service) {
420
- let best = null;
421
- let bestP = -1;
422
- for (const id of ids) {
423
- const mem = service.getById(id);
424
- if (!mem || mem.archived) continue; // archived/missing: ineligible keeper
425
- const p = EPISTEMIC_PRIORITY[mem.epistemic_status] ?? 0;
426
- if (p > bestP || (p === bestP && id === preferred)) {
427
- bestP = p;
428
- best = id;
429
- }
430
- }
431
- return best ?? preferred;
432
- }
433
-
434
- /**
435
- * Mint a fresh memory (pattern discovery). No existing target, so no CAS guard.
436
- * Evidence ids ride in the content so a pattern stays traceable to its source
437
- * memories. saveWithDedupe dedupes identical mints (idempotent replay-safe).
438
- */
439
- function applyCreate(d, service, config = {}) {
440
- const language = langOf(config);
441
- const title = String(d.title ?? "").trim();
442
- const content = String(d.content ?? "").trim();
443
- const importance = Number.isInteger(d.importance) ? d.importance : 3;
444
- const type = typeof d.type === "string" ? d.type : "pattern";
445
- const evidence = Array.isArray(d.evidence)
446
- ? d.evidence.filter((id) => typeof id === "string")
447
- : [];
448
- const body = evidence.length > 0
449
- ? STR.evidenceSuffix[language](content, evidence)
450
- : content;
451
- const created = service.saveWithDedupe({ type, title, content: body, importance });
452
- const memory = created?.memory;
453
- if (!memory) return "skipped"; // deduped/subsumed: nothing minted, clean no-op
454
- return { applied: 1, committed: { action: "create", id: memory.id, type } };
455
- }
456
-
457
- function applyArchive(d, service, snapshot) {
458
- const targets = d.ids.filter((id) => {
459
- const mem = service.getById(id);
460
- return mem && !mem.archived; // existing, not-yet-archived rows only
461
- });
462
- if (targets.length === 0) return "skipped"; // all already archived: idempotent replay
463
- service.transaction(() => {
464
- casGuard(service, snapshot, d.ids);
465
- for (const id of d.ids) {
466
- const mem = service.getById(id);
467
- if (mem && !mem.archived) service.setArchived(id, true);
468
- }
469
- });
470
- return { applied: targets.length, committed: { action: "archive", ids: targets } };
471
- }
472
-
473
- function applyMerge(d, service, snapshot, config = {}) {
474
- // Epistemic trust (v0.4.5): when enabled, prefer an observation keeper over a
475
- // subjective/inferred one. Mutating the decision keeps the receipt + committed
476
- // record aligned with the actual keeper.
477
- if (config.trustEpistemicWeighting === true) {
478
- const best = pickBestKeeper(d.ids, d.keepSource, service);
479
- if (best && best !== d.keepSource) d.keepSource = best;
480
- }
481
- const sources = d.ids.filter((id) => id !== d.keepSource);
482
- // Idempotent replay: if every other source is already archived, this merge
483
- // already landed — skip so a replayed/concurrent decision never double-counts
484
- // or re-applies (guard against duplicate merges).
485
- if (sources.every((id) => service.getById(id)?.archived)) return "skipped";
486
- service.transaction(() => {
487
- casGuard(service, snapshot, d.ids);
488
- const keeper = service.getById(d.keepSource);
489
- if (!keeper || keeper.archived) return; // missing keeper: no write, still a clean commit
490
- service.update(d.keepSource, {
491
- title: d.title,
492
- content: d.content,
493
- importance: d.importance ?? Math.max(keeper.importance, ...d.ids.map((id) => service.getById(id)?.importance ?? 1))
494
- });
495
- for (const id of sources) {
496
- const mem = service.getById(id);
497
- if (mem && !mem.archived) service.setArchived(id, true);
498
- }
499
- // 4.3.2 迁移实体关联(opt-in):将 loser(source)记忆关联的 entity_attrs 的
500
- // memory_id 迁移到 keeper;keeper 已有同 entity+key 的当前属性时 loser 行被
501
- // 失效。单个 source 迁移失败只告警,绝不能导致整个 merge 事务回滚(fail-safe)。
502
- if (config.entityExtractionEnabled && typeof service.migrateAttrsToMemory === "function") {
503
- for (const id of sources) {
504
- try {
505
- service.migrateAttrsToMemory(id, d.keepSource, new Date().toISOString());
506
- } catch (error) {
507
- logger?.warn?.(`dsh-mneme dream: failed to migrate attrs from ${id} to ${d.keepSource}: ${error.message}`);
508
- }
509
- }
510
- }
511
- });
512
- return {
513
- applied: 1,
514
- committed: { action: "merge", ids: d.ids, keepSource: d.keepSource, title: d.title, content: d.content, importance: d.importance, count_before: d.ids.length, count_after: 1 }
515
- };
516
- }
517
-
518
- function applyConflict(d, service, snapshot, config = {}) {
519
- const language = langOf(config);
520
- // Epistemic trust (v0.4.5): when enabled, the observation side of a conflict
521
- // is preferred as winner over a subjective/inferred one.
522
- if (config.trustEpistemicWeighting === true) {
523
- const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
524
- const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
525
- if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
526
- }
527
- const winner = service.getById(d.winner);
528
- const loser = service.getById(d.loser);
529
- if (!winner || !loser) return "skipped";
530
- // Idempotent replay: an already-archived loser means the conflict was already
531
- // adjudicated — skip so the provenance note is never re-appended and the loser
532
- // is not re-archived.
533
- if (loser.archived) return "skipped";
534
- service.transaction(() => {
535
- casGuard(service, snapshot, [d.winner, d.loser]);
536
- const winnerNow = service.getById(d.winner);
537
- const loserNow = service.getById(d.loser);
538
- if (!winnerNow || !loserNow || loserNow.archived) return;
539
- service.update(d.winner, {
540
- content: STR.supersededSuffix[language](winnerNow.content, [...loserNow.content].slice(0, 100).join(""))
541
- });
542
- service.setArchived(d.loser, true);
543
- });
544
- return { applied: 1, committed: { action: "conflict", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
545
- }
546
-
547
- /**
548
- * supersede(Issue #126,sleepActionSet="full"):演进型重复——新版本取代旧版本。
549
- * 与 conflict 的关键差别:**注记追加到 loser(被取代方)而不是 winner**。conflict
550
- * 把"已否决旧信息"写进赢家正文,赢家因此被污染——这正是 #126 的原始抱怨;
551
- * supersede 把可追溯性留在被归档的那一侧,赢家正文一字不动。
552
- *
553
- * 幂等:loser 已归档即视为该决策已落地(重放/并发不会重复追加注记或重复归档)。
554
- */
555
- function applySupersede(d, service, snapshot, config = {}) {
556
- const language = langOf(config);
557
- // Epistemic trust(与 conflict 同款):可信度更高的一侧优先作为取代方。
558
- if (config.trustEpistemicWeighting === true) {
559
- const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
560
- const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
561
- if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
562
- }
563
- const winner = service.getById(d.winner);
564
- const loser = service.getById(d.loser);
565
- if (!winner || !loser) return "skipped";
566
- if (loser.archived) return "skipped"; // 幂等重放:已经取代过了
567
- service.transaction(() => {
568
- casGuard(service, snapshot, [d.winner, d.loser]);
569
- const winnerNow = service.getById(d.winner);
570
- const loserNow = service.getById(d.loser);
571
- if (!winnerNow || !loserNow || loserNow.archived) return;
572
- service.update(d.loser, {
573
- content: STR.supersededBySuffix[language](loserNow.content, winnerNow.title)
574
- });
575
- service.setArchived(d.loser, true);
576
- });
577
- return { applied: 1, committed: { action: "supersede", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
578
- }
579
-
580
- /**
581
- * differentiate(Issue #126,sleepActionSet="full"):互补型重复——两条各自成立、
582
- * 覆盖不同侧面,不该判输赢。双方都保留(不归档),各追加同一段差异注记;注记进
583
- * 正文 → 进注入与 embedding → 下一轮不会再被判成重复(这是本动作存在的意义)。
584
- *
585
- * 注记由插件按 distinctions 渲染,**不让模型整段重写 content**(重写有篡改/丢失
586
- * 风险)。幂等:注记已在正文里就不重复追加,否则同一决策重放会不断堆叠。
587
- */
588
- function applyDifferentiate(d, service, snapshot, config = {}) {
589
- const language = langOf(config);
590
- const ids = Array.isArray(d.ids) ? d.ids : [];
591
- const notes = (Array.isArray(d.distinctions) ? d.distinctions : [])
592
- .filter((s) => typeof s === "string" && s.trim())
593
- .map((s) => s.trim());
594
- const marker = STR.differentiatedMarker[language](notes);
595
- const alive = ids.filter((id) => {
596
- const m = service.getById(id);
597
- return m && !m.archived;
598
- });
599
- if (alive.length < 2) return "skipped"; // 缺一条即已处理/不可用(幂等)
600
- if (alive.every((id) => String(service.getById(id)?.content ?? "").includes(marker))) {
601
- return "skipped"; // 同一条决策重放:注记已存在
602
- }
603
- service.transaction(() => {
604
- casGuard(service, snapshot, ids);
605
- for (const id of ids) {
606
- const m = service.getById(id);
607
- if (!m || m.archived) continue;
608
- if (String(m.content).includes(marker)) continue; // 单条已注记过
609
- service.update(id, { content: `${m.content}${marker}` });
610
- }
611
- });
612
- return {
613
- applied: 1,
614
- committed: { action: "differentiate", ids, count_before: ids.length, count_after: ids.length }
615
- };
616
- }
617
-
618
- function applyUpdate(d, service, snapshot, config = {}) {
619
- const id = d.ids[0];
620
- const mem = service.getById(id);
621
- if (!mem || mem.archived) return "skipped";
622
- // 幂等检查:如果字段已与目标一致则跳过
623
- const same = (d.title === undefined || d.title === mem.title)
624
- && (d.content === undefined || d.content === mem.content)
625
- && (d.importance === undefined || d.importance === mem.importance);
626
- if (same) return "skipped";
627
- service.transaction(() => {
628
- casGuard(service, snapshot, [id]);
629
- const cur = service.getById(id);
630
- if (!cur || cur.archived) return;
631
- service.update(id, {
632
- title: d.title ?? cur.title,
633
- content: d.content ?? cur.content,
634
- importance: d.importance ?? cur.importance
635
- });
636
- });
637
- // 4.3.1 supersedes 关系(opt-in):事务提交成功后,为该记忆关联的每条实体属性
638
- // 建立自引用 supersedes 关系,表示"此属性版本已被替代"。仅记录、绝不阻断主流程
639
- // (fail-safe):记录失败只告警,update 本身照常生效。
640
- if (config.entityExtractionEnabled && typeof service.saveRelation === "function" && typeof service.getAttrsByMemory === "function") {
641
- try {
642
- const oldAttrs = service.getAttrsByMemory(id);
643
- for (const attr of oldAttrs) {
644
- if (!attr.entity_id) continue;
645
- service.saveRelation({
646
- from_entity: attr.entity_id,
647
- to_entity: attr.entity_id,
648
- relation_type: "supersedes",
649
- memory_id: id,
650
- metadata: JSON.stringify({ attr_key: attr.attr_key, old_value: attr.attr_value })
651
- });
652
- }
653
- } catch (error) {
654
- logger?.warn?.(`dsh-mneme dream: failed to record supersedes relations for ${id}: ${error.message}`);
655
- }
656
- }
657
- return { applied: 1, committed: { action: "update", ids: [id], title: d.title, content: d.content, importance: d.importance, count_before: 1, count_after: 1 } };
658
- }
1
+ import { STR, langOf } from "../lang.js";
2
+
3
+ // Issue #126:sleepActionSet="full" 时新增两个动作——supersede(演进:新版取代
4
+ // 旧版)与 differentiate(互补:两条都留、各追加差异注记)。两者的校验与执行都
5
+ // 复用既有 merge/conflict 的机制(winner/loser、casGuard、transaction、receipt)。
6
+ // 调用方(sleep)按档位派生「本档允许的动作集合」时需要读它,故导出。
7
+ export const ACTIONS = new Set(["keep", "merge", "archive", "conflict", "update", "create", "supersede", "differentiate"]);
8
+
9
+ // Epistemic trust (v0.4.5): when config.trustEpistemicWeighting is on, merge
10
+ // keepSource and conflict winners prefer the higher-trust memory. Higher value
11
+ // = preferred. observation (measured) > inferred (derived) > subjective (guess).
12
+ const EPISTEMIC_PRIORITY = { observation: 3, inferred: 2, subjective: 1 };
13
+
14
+ // Issue #104 方向 2:archive 类型护栏的长保留类型集合——这些类型的存在意义
15
+ // 就是长期保存(踩坑记录、约束、用户偏好、挖掘出的模式),LLM 以「价值判断」
16
+ // 类理由批量归档它们时误伤损失最大。conflict 裁决的败者归档不经过 archive
17
+ // action(走 applyDecisions 的 conflict 分支),不受此护栏影响。
18
+ const ARCHIVE_GUARDED_TYPES = new Set(["preference", "pattern", "rejected_solution", "constraint", "pitfall"]);
19
+ // 「重复 / 过时」类理由的关键词(中英双语)。命中才允许归档长保留类型;
20
+ // 词表宁可放宽也不误拦——护栏只跳过单条并落明细,不整单拒绝。
21
+ const ARCHIVE_RATIONALE_RE = /重复|过时|陈旧|过期|已被取代|被取代|冗余|不再使用|旧版|废弃|stale|outdated|obsolete|dup(?:licate|licat)?|superseded|redundant|deprecated|expired|replaced/i;
22
+
23
+ /**
24
+ * Validate a dream decision list against a snapshot of eligible memories.
25
+ * @param decisions - LLM-produced decision list. In skipInvalid mode, invalid
26
+ * entries are spliced out of this array in place (the caller reuses the same
27
+ * reference downstream for apply/audit); implicit keeps are appended here too.
28
+ * @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
29
+ * @returns {{ok: boolean, errors: string[], skipped?: Array<{index, action, ids, error}>,
30
+ * resolvedShortIds?: number}}
31
+ */
32
+ export function validateDecisions(decisions, snapshot, options = {}) {
33
+ const errors = [];
34
+ // Issue #89 回归修复(v0.6.9 / Issue #26 的 skipInvalid 路径原样移植,该路径
35
+ // 在 v0.7.11 重写中丢失):skipInvalid 开启时,单条非法决策只跳过该条(记录
36
+ // 到 skipped、不 claim 任何 id),合法子集照常应用,调用方据此把 run 记为
37
+ // degraded。全局信号(update/create 上限、显式覆盖率下限)依旧整单拒绝——
38
+ // 刷爆上限或覆盖率不达标的输出是模型坏了,不是轻微 schema 漂移。
39
+ const skipped = [];
40
+ const survivors = [];
41
+ const skipInvalid = options.skipInvalid === true;
42
+ const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
43
+ const minAgeHours = options.minAgeHours ?? 24;
44
+ // Issue #126 review(Copilot):档位白名单。sleepActionSet 默认档只换 prompt 是
45
+ // 不够的——ACTIONS 是两个模块共用的,模型自发出 supersede / differentiate 时校验器
46
+ // 照样放行,"opt-in 零行为变化"就成了空话。省略 / null = 不限制(沿用全局 ACTIONS)。
47
+ const allowedActions = Array.isArray(options.allowedActions) ? new Set(options.allowedActions) : null;
48
+ if (!Array.isArray(decisions)) {
49
+ return { ok: false, errors: ["decision list must be an array"], resolvedShortIds: 0 };
50
+ }
51
+ // 空决策 = 模型完整评估后确认无需操作(CONSOLIDATION_PROMPT 明确允许"无问题的
52
+ // 条目无需输出")。合法 JSON [] 不是空体(那是无输出/截断),也不是"残缺输出"
53
+ // ——显式短路直接 ok,避免隐式 keep 的覆盖率检查把 0% 误判为模型坏了。与
54
+ // sleep 的空模式(skipped no-op)语义对齐:下游 applied=0、audit 记 ok。
55
+ if (decisions.length === 0) {
56
+ return { ok: true, errors: [], skipped: [], resolvedShortIds: 0 };
57
+ }
58
+ // Issue #135:模型常把 36 位 UUID 回填成前缀(实测 78/78 个 8 位前缀都能唯一
59
+ // 对应窗口内真实记忆,且 few-shot 示例的 "m1"/"m2" 占位符在诱导这种缩写),而
60
+ // 下方校验用 snapshot.get(id) 整串精确匹配 → 全部 unknown id → claimed=0 →
61
+ // 覆盖率闸整单拒绝,一整轮语义成果被丢。校验前先把「唯一前缀」解析回完整 id
62
+ // (git 短哈希式):仅在 snapshot 内解析,有歧义或匹配不到就原样保留,仍由下
63
+ // 方 unknown id 校验如实报错。就地改写 ids / keepSource / winner / loser,下
64
+ // 游 applyDecisions 与审计拿到的同样是完整 id。
65
+ let resolvedShortIds = 0;
66
+ const resolveShortId = (value) => {
67
+ if (typeof value !== "string" || snapshot.has(value)) return value;
68
+ // 太短不猜(歧义概率高);长度 ≥36 说明不是前缀缩写,交给校验如实报错。
69
+ if (value.length < 8 || value.length >= 36) return value;
70
+ let hit = null;
71
+ let matches = 0;
72
+ for (const id of snapshot.keys()) {
73
+ if (id.startsWith(value)) {
74
+ hit = id;
75
+ if (++matches > 1) return value; // 有歧义,不解析
76
+ }
77
+ }
78
+ if (matches === 1) {
79
+ resolvedShortIds++;
80
+ return hit;
81
+ }
82
+ return value;
83
+ };
84
+ for (const d of decisions) {
85
+ if (!d || typeof d !== "object") continue;
86
+ if (Array.isArray(d.ids)) d.ids = d.ids.map(resolveShortId);
87
+ if (typeof d.keepSource === "string") d.keepSource = resolveShortId(d.keepSource);
88
+ if (typeof d.winner === "string") d.winner = resolveShortId(d.winner);
89
+ if (typeof d.loser === "string") d.loser = resolveShortId(d.loser);
90
+ }
91
+ const claimed = new Set();
92
+ for (const [index, d] of decisions.entries()) {
93
+ const at = `decision[${index}]`;
94
+ // 单条校验错误先进 local:skipInvalid 模式下整条跳过,严格模式下才并入
95
+ // 全局 errors(沿用 v0.6.9 的双轨结构)。
96
+ const local = [];
97
+ // Issue #126:supersede 与 conflict 一样用 winner/loser 定位双方(沿用同一套
98
+ // 字段,校验与 receipt 逻辑因此可以直接复用)。
99
+ const ids = d && (d.action === "conflict" || d.action === "supersede") ? [d.winner, d.loser] : (d?.ids ?? []);
100
+ if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
101
+ local.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
102
+ } else if (allowedActions && !allowedActions.has(d.action)) {
103
+ // 动作本身合法,但不在当前档位允许的集合里(例如默认档收到 supersede)。
104
+ local.push(`${at}: action ${JSON.stringify(d.action)} not allowed in this mode`);
105
+ } else if (d.action === "conflict" || d.action === "supersede") {
106
+ if (!d.winner || !d.loser || d.winner === d.loser) {
107
+ local.push(`${at}: ${d.action} needs distinct winner and loser`);
108
+ }
109
+ } else if (d.action === "differentiate") {
110
+ // Issue #126:互补型——两条都留下、各追加差异注记。ids 必须 ≥2(随后走下方
111
+ // 通用 id 校验:unknown / archived / summary / 重复 claim),distinctions 必须
112
+ // 非空,否则会写出空注记(写了等于没写,还会污染正文)。
113
+ if (!Array.isArray(d.ids) || d.ids.length < 2) {
114
+ local.push(`${at}: differentiate needs at least two ids`);
115
+ } else if (!Array.isArray(d.distinctions) || !d.distinctions.some((s) => typeof s === "string" && s.trim())) {
116
+ local.push(`${at}: differentiate needs a non-empty distinctions array`);
117
+ }
118
+ } else if (d.action === "create") {
119
+ // Mint a fresh memory (sleep pattern discovery). Claims no existing id,
120
+ // so it skips the claiming loop below; evidence is optional provenance
121
+ // (already filtered to real ids by the caller) and is stored in content.
122
+ if (typeof d.title !== "string" || !d.title.trim()) {
123
+ local.push(`${at}: create needs non-empty title`);
124
+ }
125
+ if (typeof d.content !== "string" || !d.content.trim()) {
126
+ local.push(`${at}: create needs non-empty content`);
127
+ }
128
+ if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
129
+ local.push(`${at}: create importance must be an integer 1-5 when provided`);
130
+ }
131
+ if (typeof d.type !== "string" || !d.type.trim()) {
132
+ local.push(`${at}: create needs non-empty type`);
133
+ }
134
+ } else if (!Array.isArray(d.ids) || d.ids.length === 0) {
135
+ local.push(`${at}: ${d.action} needs non-empty ids`);
136
+ }
137
+ // update-specific field validation runs BEFORE claiming ids, so a failing
138
+ // update never pollutes the claimed set (which drives the "every id must
139
+ // appear in a decision" check below).
140
+ // Issue #104 方向 2:archive 类型护栏。长保留类型的 archive 决策必须携带
141
+ // 「重复 / 过时」类理由(提示词对 archive 的定义本就如此),「价值判断」类
142
+ // 理由(保持整洁、参考价值低……)不放行——单条跳过记 skipped(run 记
143
+ // degraded,明细进 dream_runs.skipped),绝不整单拒绝。未知 id 在下方通用
144
+ // 校验里另行报错,这里 snapshot.get 为 undefined 时跳过护栏判断。
145
+ if (local.length === 0 && d?.action === "archive") {
146
+ const guardedTypes = new Set();
147
+ for (const id of d.ids) {
148
+ const mem = snapshot.get(id);
149
+ if (mem && ARCHIVE_GUARDED_TYPES.has(mem.type)) guardedTypes.add(mem.type);
150
+ }
151
+ if (guardedTypes.size > 0 && !ARCHIVE_RATIONALE_RE.test(String(d.reason ?? ""))) {
152
+ local.push(`${at}: archive of long-retention type(s) ${[...guardedTypes].join(", ")} needs a duplicate/outdated rationale (重复/过时), got: ${JSON.stringify(String(d.reason ?? "")).slice(0, 60)}`);
153
+ }
154
+ }
155
+ if (local.length === 0 && d?.action === "update") {
156
+ // 只能更新单条
157
+ if (!Array.isArray(d.ids) || d.ids.length !== 1) {
158
+ local.push(`${at}: update must target exactly one id`);
159
+ } else {
160
+ // 必须产生实际变化
161
+ const mem = snapshot.get(d.ids[0]);
162
+ const hasChange = (d.title !== undefined && d.title !== mem?.title)
163
+ || (d.content !== undefined && d.content !== mem?.content)
164
+ || (d.importance !== undefined && d.importance !== mem?.importance);
165
+ if (!hasChange) {
166
+ local.push(`${at}: update must change at least one field`);
167
+ } else if (mem?.type === "summary") {
168
+ // 不能更新 summary
169
+ local.push(`${at}: cannot update summary via update action`);
170
+ } else {
171
+ // 保护期:新建记忆不可立即被 update(可配置)
172
+ const ageHours = (Date.now() - new Date(mem?.created_at).getTime()) / 3600000;
173
+ if (ageHours < minAgeHours) {
174
+ local.push(`${at}: memory too young (< ${minAgeHours}h)`);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ if (local.length === 0 && d && d.action !== "create") {
180
+ // seen 捕获同一条决策内的重复 id;claimed 只含先前存活决策的 id
181
+ // (被跳过的决策不 claim,其目标留给其它合法决策/隐式 keep)。
182
+ const seen = new Set();
183
+ for (const id of ids) {
184
+ const mem = snapshot.get(id);
185
+ if (!mem) {
186
+ local.push(`${at}: unknown id ${JSON.stringify(id)}`);
187
+ } else if (mem.archived || mem.type === "summary") {
188
+ local.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
189
+ }
190
+ if (claimed.has(id) || seen.has(id)) {
191
+ local.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
192
+ }
193
+ seen.add(id);
194
+ }
195
+ if (local.length === 0 && d.action === "merge") {
196
+ if (!d.keepSource || !d.ids.includes(d.keepSource)) {
197
+ local.push(`${at}: merge keepSource must be one of ids`);
198
+ }
199
+ if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
200
+ local.push(`${at}: merge needs non-empty title and content`);
201
+ }
202
+ if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
203
+ local.push(`${at}: merge importance must be an integer 1-5 when provided`);
204
+ }
205
+ // Merging across types would blur preference/project/decision boundaries
206
+ // in the injected context; the snapshot carries each entry's type.
207
+ // Issue #26 (P1):默认禁止跨类型合并。用户显式开启 allowCrossTypeMerge
208
+ // 后放宽该检查,类型边界由用户自行承担。
209
+ const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
210
+ if (mergeTypes.size > 1 && options.allowCrossTypeMerge !== true) {
211
+ local.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
212
+ }
213
+ }
214
+ }
215
+ if (local.length > 0) {
216
+ if (skipInvalid) {
217
+ // 单条非法 → 跳过该决策,不 claim id(其目标记忆留给其它合法决策/隐式
218
+ // keep),并记录到 skipped 供调用方日志/审计。信息性跳过绝不写入全局
219
+ // errors,否则会误触发下方的整单拒绝。
220
+ skipped.push({ index, action: d?.action, ids, error: local.join("; ") });
221
+ } else {
222
+ errors.push(...local);
223
+ }
224
+ continue;
225
+ }
226
+ if (d.action !== "create") {
227
+ for (const id of ids) claimed.add(id);
228
+ }
229
+ survivors.push(d);
230
+ }
231
+ // Cap update churn: too many edits in one cycle signals a runaway model.
232
+ // 全局信号——skipInvalid 模式下依旧整单拒绝(见函数头注释)。
233
+ const updateCount = survivors.filter((d) => d.action === "update").length;
234
+ if (updateCount > maxUpdatePerRun) {
235
+ errors.push(`too many update decisions: ${updateCount} > ${maxUpdatePerRun}`);
236
+ }
237
+ // Cap pattern minting per run (sleepMaxPatternPerRun passes through here).
238
+ const createCount = survivors.filter((d) => d.action === "create").length;
239
+ const maxCreatePerRun = options.maxCreatePerRun ?? 5;
240
+ if (createCount > maxCreatePerRun) {
241
+ errors.push(`too many create decisions: ${createCount} > ${maxCreatePerRun}`);
242
+ }
243
+ // Issue #104 方向 2:archive 批量上限——一次性大扫除(12 条互不相关主题被
244
+ // 批量归档)是失控信号,与 update 上限同一类全局闸门:skipInvalid 也不豁免,
245
+ // 超限整单拒绝;正常的大规模清理由用户调高 dreamMaxArchivePerRun。
246
+ const archiveCount = survivors.filter((d) => d.action === "archive").length;
247
+ const maxArchivePerRun = options.maxArchivePerRun ?? 8;
248
+ if (archiveCount > maxArchivePerRun) {
249
+ errors.push(`too many archive decisions: ${archiveCount} > ${maxArchivePerRun}`);
250
+ }
251
+ // Issue #89 防洗白核心(#104 方向 1 重审后保留):全部决策都被跳过、合法
252
+ // 子集为空时仍整单拒绝——宽容的前提是「有合法子集可应用」;模型输出整体
253
+ // 非法(如全部幻觉 id)是真故障,不能被隐式 keep 洗成 ok。#104 只豁免
254
+ // 「有合法子集但覆盖率不足」的良性挑重点(见下方 coverageShortfall)。
255
+ if (options.skipInvalid === true && skipped.length > 0 && survivors.length === 0 && errors.length === 0) {
256
+ errors.push(`all ${skipped.length} decision(s) invalid — nothing valid survived validation`);
257
+ return { ok: false, errors, skipped, resolvedShortIds };
258
+ }
259
+ // v0.4.4: 隐式 keep。默认(dreamImplicitKeep !== false)下,未 claim 的
260
+ // snapshot 记忆自动补 {action:"keep"},而不是整体拒绝——大记忆量下 LLM 漏报
261
+ // 一两条就全拒(636 记忆 → 677 errors)会白白浪费整轮 run。设 false 则保留
262
+ // 旧的严格"全量覆盖"校验。补齐的 keep 直接 append 到 decisions,调用方
263
+ // (runDream/applyDecisions/audit)复用同一数组即可覆盖全部 snapshot 记忆。
264
+ //
265
+ // v0.4.4 fix(残缺输出防洗白)→ Issue #104 方向 1 重审:显式覆盖率护栏的
266
+ // 初衷是拦「输出截断 → 只 claim 少量 → 其余被隐式 keep 洗白」,但它无法区分
267
+ // 恶性截断与良性挑重点——而提示词硬性规则本身要求「无问题的条目无需输出」,
268
+ // 挑重点正是要求的行为。官方路由 + 强模型的实测(heptaspirit:81 轮 failed
269
+ // 全是 coverage,LLM 调用本身成功、applied=0)证明这是常规路径而非边角。
270
+ // 处置:覆盖率不足不再 ok:false 整单拒绝,改为返回 coverageShortfall 理由、
271
+ // 照常补齐隐式 keep——调用方把 run 记 degraded(合法子集已应用),护栏以
272
+ // 状态暴露而非一票否决,与 skipInvalid 同一宽容哲学。明确异常信号(create
273
+ // 上限等硬错误)保持整单拒绝。要恢复旧行为可设 dreamImplicitKeep:false
274
+ // (严格模式,缺失即 error)或 dreamMinExplicitCoverage: 0(关护栏)。
275
+ // 非覆盖类硬错误(create 上限溢出、严格模式缺失 id)仍然先整单拒绝——
276
+ // #104 方向 1 只豁免 coverage 这一个信号,防洗白语义对它们原样保留。
277
+ if (errors.length > 0) {
278
+ return { ok: false, errors, skipped, resolvedShortIds };
279
+ }
280
+ const minCoverage = options.dreamMinExplicitCoverage ?? 0.5;
281
+ let coverageShortfall = null;
282
+ if (options.dreamImplicitKeep !== false) {
283
+ const coverage = snapshot.size > 0 ? claimed.size / snapshot.size : 1;
284
+ if (coverage < minCoverage) {
285
+ coverageShortfall = `explicit decision coverage ${Math.round(coverage * 100)}% < minimum ${Math.round(minCoverage * 100)}%`;
286
+ }
287
+ for (const id of snapshot.keys()) {
288
+ if (!claimed.has(id)) survivors.push({ action: "keep", ids: [id] });
289
+ }
290
+ } else {
291
+ for (const id of snapshot.keys()) {
292
+ if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
293
+ }
294
+ if (errors.length > 0) return { ok: false, errors, skipped, resolvedShortIds };
295
+ }
296
+ // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
297
+ // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
298
+ // 不能以 survivors.length !== decisions.length 作为是否 splice 的判据:
299
+ // 当"被跳过的非法决策数 == 隐式补齐的 keep 数"时长度回到相等但内容已变,
300
+ // 被跳过的决策会残留进 apply/audit。一律无条件 splice 最安全。
301
+ decisions.splice(0, decisions.length, ...survivors);
302
+ return { ok: true, errors, skipped, resolvedShortIds, coverageShortfall };
303
+ }
304
+
305
+ /** Marker thrown when a decision target changed since the run snapshot. */
306
+ export class CasConflictError extends Error {
307
+ constructor(action, ids, reason) {
308
+ super(`cas conflict: ${action} targets changed since snapshot (${reason})`);
309
+ this.name = "CasConflictError";
310
+ this.action = action;
311
+ this.ids = ids;
312
+ }
313
+ }
314
+
315
+ function decisionIds(d) {
316
+ return d.action === "conflict" || d.action === "supersede" ? [d.winner, d.loser] : (d.ids ?? []);
317
+ }
318
+
319
+ /**
320
+ * CAS guard (item ①): every target memory must still match what the run
321
+ * snapshot captured — otherwise the decision was computed against stale state
322
+ * and applying it would overwrite a concurrent edit. Snapshotless replays skip
323
+ * the guard entirely (per-action idempotency checks handle those). Throws
324
+ * CasConflictError on the first mismatch; the caller's transaction rolls back.
325
+ */
326
+ function casGuard(service, snapshot, ids) {
327
+ if (!snapshot) return;
328
+ for (const id of ids) {
329
+ const expect = snapshot.get(id);
330
+ if (!expect) continue; // not in snapshot: validated elsewhere, skip guard
331
+ const current = service.getById(id);
332
+ if (!current) {
333
+ throw new CasConflictError("deleted", [id], `memory ${id} was removed`);
334
+ }
335
+ const changed = expect.updated_at !== undefined
336
+ ? current.updated_at !== expect.updated_at
337
+ : current.content !== expect.content || current.title !== expect.title;
338
+ if (changed) {
339
+ throw new CasConflictError(
340
+ "changed",
341
+ [id],
342
+ `memory ${id} was concurrently modified (expected updated_at=${expect.updated_at}, got ${current.updated_at})`
343
+ );
344
+ }
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Apply a validated decision list to the service. Caller must validate first.
350
+ * Each decision runs inside its own SQLite transaction (item ②): the multi-step
351
+ * mutation of a decision is atomic, so a merge can never leave "keeper updated
352
+ * but source not archived" or vice versa — a throwing sub-step rolls the whole
353
+ * decision back.
354
+ *
355
+ * @param decisions - validated decision list.
356
+ * @param service - memory service (saveWithDedupe/getById/update/setArchived/transaction).
357
+ * @param logger - optional logger ({ warn }); per-decision failures are logged.
358
+ * @param snapshot - optional Map<id, memory> captured before the LLM call; when
359
+ * provided, every decision target is CAS-checked against it and a decision
360
+ * computed from stale state is skipped and reported as a conflict instead of
361
+ * overwriting concurrent writes (item ①).
362
+ * @returns {{ applied: number, conflicts: Array, failures: Array, committed: Array }}
363
+ * applied - number of decisions/memories actually committed (archive counts
364
+ * each archived memory as one, merge/conflict/update count one).
365
+ * conflicts - decisions skipped because a target changed since the snapshot.
366
+ * failures - decisions that threw mid-transaction (fully rolled back).
367
+ * committed - the decisions that actually landed, for outcome/receipt based
368
+ * on real committed sub-steps rather than the raw LLM list.
369
+ */
370
+ export function applyDecisions(decisions, service, logger = null, snapshot = null, config = {}) {
371
+ let applied = 0;
372
+ const conflicts = [];
373
+ const failures = [];
374
+ const committed = [];
375
+ for (const [i, d] of decisions.entries()) {
376
+ try {
377
+ // keep is a confirmed no-op: it commits nothing but still records the
378
+ // per-id disposition so the outcome covers every snapshot memory.
379
+ if (d.action === "keep") {
380
+ committed.push({ action: "keep", ids: d.ids });
381
+ continue;
382
+ }
383
+ const outcome = applyOne(d, service, snapshot, config);
384
+ if (outcome === "skipped") continue;
385
+ applied += outcome.applied;
386
+ committed.push(outcome.committed);
387
+ } catch (error) {
388
+ if (error instanceof CasConflictError) {
389
+ conflicts.push({ index: i, action: d.action, ids: error.ids, reason: error.message });
390
+ logger?.warn?.(`dsh-mneme dream: ${error.message}`);
391
+ } else {
392
+ failures.push({ index: i, action: d.action, ids: decisionIds(d), reason: error.message });
393
+ logger?.warn?.(`dsh-mneme dream: failed to apply ${d.action} at index ${i}: ${error.message}`);
394
+ }
395
+ }
396
+ }
397
+ return { applied, conflicts, failures, committed };
398
+ }
399
+
400
+ function applyOne(d, service, snapshot, config = {}) {
401
+ switch (d.action) {
402
+ case "archive": return applyArchive(d, service, snapshot);
403
+ case "merge": return applyMerge(d, service, snapshot, config);
404
+ case "conflict": return applyConflict(d, service, snapshot, config);
405
+ case "supersede": return applySupersede(d, service, snapshot, config);
406
+ case "differentiate": return applyDifferentiate(d, service, snapshot, config);
407
+ case "create": return applyCreate(d, service, config);
408
+ default: return applyUpdate(d, service, snapshot, config);
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Highest-epistemic-priority UNARCHIVED id among `ids` (ties break toward
414
+ * `preferred`). Archived memories are never eligible keepers — promoting one
415
+ * would demote the real keepSource to a source and then hit the archived-keeper
416
+ * guard in applyMerge, silently skipping the whole merge. When `preferred`
417
+ * itself is archived (or missing), fall back to any unarchived candidate.
418
+ */
419
+ function pickBestKeeper(ids, preferred, service) {
420
+ let best = null;
421
+ let bestP = -1;
422
+ for (const id of ids) {
423
+ const mem = service.getById(id);
424
+ if (!mem || mem.archived) continue; // archived/missing: ineligible keeper
425
+ const p = EPISTEMIC_PRIORITY[mem.epistemic_status] ?? 0;
426
+ if (p > bestP || (p === bestP && id === preferred)) {
427
+ bestP = p;
428
+ best = id;
429
+ }
430
+ }
431
+ return best ?? preferred;
432
+ }
433
+
434
+ /**
435
+ * Mint a fresh memory (pattern discovery). No existing target, so no CAS guard.
436
+ * Evidence ids ride in the content so a pattern stays traceable to its source
437
+ * memories. saveWithDedupe dedupes identical mints (idempotent replay-safe).
438
+ */
439
+ function applyCreate(d, service, config = {}) {
440
+ const language = langOf(config);
441
+ const title = String(d.title ?? "").trim();
442
+ const content = String(d.content ?? "").trim();
443
+ const importance = Number.isInteger(d.importance) ? d.importance : 3;
444
+ const type = typeof d.type === "string" ? d.type : "pattern";
445
+ const evidence = Array.isArray(d.evidence)
446
+ ? d.evidence.filter((id) => typeof id === "string")
447
+ : [];
448
+ const body = evidence.length > 0
449
+ ? STR.evidenceSuffix[language](content, evidence)
450
+ : content;
451
+ const created = service.saveWithDedupe({ type, title, content: body, importance });
452
+ const memory = created?.memory;
453
+ if (!memory) return "skipped"; // deduped/subsumed: nothing minted, clean no-op
454
+ return { applied: 1, committed: { action: "create", id: memory.id, type } };
455
+ }
456
+
457
+ function applyArchive(d, service, snapshot) {
458
+ const targets = d.ids.filter((id) => {
459
+ const mem = service.getById(id);
460
+ return mem && !mem.archived; // existing, not-yet-archived rows only
461
+ });
462
+ if (targets.length === 0) return "skipped"; // all already archived: idempotent replay
463
+ service.transaction(() => {
464
+ casGuard(service, snapshot, d.ids);
465
+ for (const id of d.ids) {
466
+ const mem = service.getById(id);
467
+ if (mem && !mem.archived) service.setArchived(id, true);
468
+ }
469
+ });
470
+ return { applied: targets.length, committed: { action: "archive", ids: targets } };
471
+ }
472
+
473
+ function applyMerge(d, service, snapshot, config = {}) {
474
+ // Epistemic trust (v0.4.5): when enabled, prefer an observation keeper over a
475
+ // subjective/inferred one. Mutating the decision keeps the receipt + committed
476
+ // record aligned with the actual keeper.
477
+ if (config.trustEpistemicWeighting === true) {
478
+ const best = pickBestKeeper(d.ids, d.keepSource, service);
479
+ if (best && best !== d.keepSource) d.keepSource = best;
480
+ }
481
+ const sources = d.ids.filter((id) => id !== d.keepSource);
482
+ // Idempotent replay: if every other source is already archived, this merge
483
+ // already landed — skip so a replayed/concurrent decision never double-counts
484
+ // or re-applies (guard against duplicate merges).
485
+ if (sources.every((id) => service.getById(id)?.archived)) return "skipped";
486
+ service.transaction(() => {
487
+ casGuard(service, snapshot, d.ids);
488
+ const keeper = service.getById(d.keepSource);
489
+ if (!keeper || keeper.archived) return; // missing keeper: no write, still a clean commit
490
+ service.update(d.keepSource, {
491
+ title: d.title,
492
+ content: d.content,
493
+ importance: d.importance ?? Math.max(keeper.importance, ...d.ids.map((id) => service.getById(id)?.importance ?? 1))
494
+ });
495
+ for (const id of sources) {
496
+ const mem = service.getById(id);
497
+ if (mem && !mem.archived) service.setArchived(id, true);
498
+ }
499
+ // 4.3.2 迁移实体关联(opt-in):将 loser(source)记忆关联的 entity_attrs 的
500
+ // memory_id 迁移到 keeper;keeper 已有同 entity+key 的当前属性时 loser 行被
501
+ // 失效。单个 source 迁移失败只告警,绝不能导致整个 merge 事务回滚(fail-safe)。
502
+ if (config.entityExtractionEnabled && typeof service.migrateAttrsToMemory === "function") {
503
+ for (const id of sources) {
504
+ try {
505
+ service.migrateAttrsToMemory(id, d.keepSource, new Date().toISOString());
506
+ } catch (error) {
507
+ logger?.warn?.(`dsh-mneme dream: failed to migrate attrs from ${id} to ${d.keepSource}: ${error.message}`);
508
+ }
509
+ }
510
+ }
511
+ });
512
+ return {
513
+ applied: 1,
514
+ committed: { action: "merge", ids: d.ids, keepSource: d.keepSource, title: d.title, content: d.content, importance: d.importance, count_before: d.ids.length, count_after: 1 }
515
+ };
516
+ }
517
+
518
+ function applyConflict(d, service, snapshot, config = {}) {
519
+ const language = langOf(config);
520
+ // Epistemic trust (v0.4.5): when enabled, the observation side of a conflict
521
+ // is preferred as winner over a subjective/inferred one.
522
+ if (config.trustEpistemicWeighting === true) {
523
+ const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
524
+ const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
525
+ if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
526
+ }
527
+ const winner = service.getById(d.winner);
528
+ const loser = service.getById(d.loser);
529
+ if (!winner || !loser) return "skipped";
530
+ // Idempotent replay: an already-archived loser means the conflict was already
531
+ // adjudicated — skip so the provenance note is never re-appended and the loser
532
+ // is not re-archived.
533
+ if (loser.archived) return "skipped";
534
+ service.transaction(() => {
535
+ casGuard(service, snapshot, [d.winner, d.loser]);
536
+ const winnerNow = service.getById(d.winner);
537
+ const loserNow = service.getById(d.loser);
538
+ if (!winnerNow || !loserNow || loserNow.archived) return;
539
+ service.update(d.winner, {
540
+ content: STR.supersededSuffix[language](winnerNow.content, [...loserNow.content].slice(0, 100).join(""))
541
+ });
542
+ service.setArchived(d.loser, true);
543
+ });
544
+ return { applied: 1, committed: { action: "conflict", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
545
+ }
546
+
547
+ /**
548
+ * supersede(Issue #126,sleepActionSet="full"):演进型重复——新版本取代旧版本。
549
+ * 与 conflict 的关键差别:**注记追加到 loser(被取代方)而不是 winner**。conflict
550
+ * 把"已否决旧信息"写进赢家正文,赢家因此被污染——这正是 #126 的原始抱怨;
551
+ * supersede 把可追溯性留在被归档的那一侧,赢家正文一字不动。
552
+ *
553
+ * 幂等:loser 已归档即视为该决策已落地(重放/并发不会重复追加注记或重复归档)。
554
+ */
555
+ function applySupersede(d, service, snapshot, config = {}) {
556
+ const language = langOf(config);
557
+ // Epistemic trust(与 conflict 同款):可信度更高的一侧优先作为取代方。
558
+ if (config.trustEpistemicWeighting === true) {
559
+ const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
560
+ const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
561
+ if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
562
+ }
563
+ const winner = service.getById(d.winner);
564
+ const loser = service.getById(d.loser);
565
+ if (!winner || !loser) return "skipped";
566
+ if (loser.archived) return "skipped"; // 幂等重放:已经取代过了
567
+ service.transaction(() => {
568
+ casGuard(service, snapshot, [d.winner, d.loser]);
569
+ const winnerNow = service.getById(d.winner);
570
+ const loserNow = service.getById(d.loser);
571
+ if (!winnerNow || !loserNow || loserNow.archived) return;
572
+ service.update(d.loser, {
573
+ content: STR.supersededBySuffix[language](loserNow.content, winnerNow.title)
574
+ });
575
+ service.setArchived(d.loser, true);
576
+ });
577
+ return { applied: 1, committed: { action: "supersede", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
578
+ }
579
+
580
+ /**
581
+ * differentiate(Issue #126,sleepActionSet="full"):互补型重复——两条各自成立、
582
+ * 覆盖不同侧面,不该判输赢。双方都保留(不归档),各追加同一段差异注记;注记进
583
+ * 正文 → 进注入与 embedding → 下一轮不会再被判成重复(这是本动作存在的意义)。
584
+ *
585
+ * 注记由插件按 distinctions 渲染,**不让模型整段重写 content**(重写有篡改/丢失
586
+ * 风险)。幂等:注记已在正文里就不重复追加,否则同一决策重放会不断堆叠。
587
+ */
588
+ function applyDifferentiate(d, service, snapshot, config = {}) {
589
+ const language = langOf(config);
590
+ const ids = Array.isArray(d.ids) ? d.ids : [];
591
+ const notes = (Array.isArray(d.distinctions) ? d.distinctions : [])
592
+ .filter((s) => typeof s === "string" && s.trim())
593
+ .map((s) => s.trim());
594
+ const marker = STR.differentiatedMarker[language](notes);
595
+ const alive = ids.filter((id) => {
596
+ const m = service.getById(id);
597
+ return m && !m.archived;
598
+ });
599
+ if (alive.length < 2) return "skipped"; // 缺一条即已处理/不可用(幂等)
600
+ if (alive.every((id) => String(service.getById(id)?.content ?? "").includes(marker))) {
601
+ return "skipped"; // 同一条决策重放:注记已存在
602
+ }
603
+ service.transaction(() => {
604
+ casGuard(service, snapshot, ids);
605
+ for (const id of ids) {
606
+ const m = service.getById(id);
607
+ if (!m || m.archived) continue;
608
+ if (String(m.content).includes(marker)) continue; // 单条已注记过
609
+ service.update(id, { content: `${m.content}${marker}` });
610
+ }
611
+ });
612
+ return {
613
+ applied: 1,
614
+ committed: { action: "differentiate", ids, count_before: ids.length, count_after: ids.length }
615
+ };
616
+ }
617
+
618
+ function applyUpdate(d, service, snapshot, config = {}) {
619
+ const id = d.ids[0];
620
+ const mem = service.getById(id);
621
+ if (!mem || mem.archived) return "skipped";
622
+ // 幂等检查:如果字段已与目标一致则跳过
623
+ const same = (d.title === undefined || d.title === mem.title)
624
+ && (d.content === undefined || d.content === mem.content)
625
+ && (d.importance === undefined || d.importance === mem.importance);
626
+ if (same) return "skipped";
627
+ service.transaction(() => {
628
+ casGuard(service, snapshot, [id]);
629
+ const cur = service.getById(id);
630
+ if (!cur || cur.archived) return;
631
+ service.update(id, {
632
+ title: d.title ?? cur.title,
633
+ content: d.content ?? cur.content,
634
+ importance: d.importance ?? cur.importance
635
+ });
636
+ });
637
+ // 4.3.1 supersedes 关系(opt-in):事务提交成功后,为该记忆关联的每条实体属性
638
+ // 建立自引用 supersedes 关系,表示"此属性版本已被替代"。仅记录、绝不阻断主流程
639
+ // (fail-safe):记录失败只告警,update 本身照常生效。
640
+ if (config.entityExtractionEnabled && typeof service.saveRelation === "function" && typeof service.getAttrsByMemory === "function") {
641
+ try {
642
+ const oldAttrs = service.getAttrsByMemory(id);
643
+ for (const attr of oldAttrs) {
644
+ if (!attr.entity_id) continue;
645
+ service.saveRelation({
646
+ from_entity: attr.entity_id,
647
+ to_entity: attr.entity_id,
648
+ relation_type: "supersedes",
649
+ memory_id: id,
650
+ metadata: JSON.stringify({ attr_key: attr.attr_key, old_value: attr.attr_value })
651
+ });
652
+ }
653
+ } catch (error) {
654
+ logger?.warn?.(`dsh-mneme dream: failed to record supersedes relations for ${id}: ${error.message}`);
655
+ }
656
+ }
657
+ return { applied: 1, committed: { action: "update", ids: [id], title: d.title, content: d.content, importance: d.importance, count_before: 1, count_after: 1 } };
658
+ }