@modusensus/dsh-mneme 0.6.9 → 0.6.10

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/LICENSE +21 -21
  2. package/README.md +468 -219
  3. package/{dsh-mneme/cordis.patch.yml → cordis.patch.yml} +15 -15
  4. package/{dsh-mneme/src → lib}/api.js +783 -783
  5. package/{dsh-mneme/lib → lib}/client.js +1754 -1757
  6. package/{dsh-mneme/src → lib}/commands.js +64 -64
  7. package/{dsh-mneme/lib → lib}/config.js +298 -298
  8. package/{dsh-mneme/lib → lib}/dream/clustering.js +118 -118
  9. package/{dsh-mneme/lib → lib}/dream/decisions.js +488 -488
  10. package/{dsh-mneme/lib → lib}/dream/sleep.js +561 -561
  11. package/{dsh-mneme/src → lib}/dream/tag-extractor.js +156 -156
  12. package/{dsh-mneme/lib → lib}/dream.js +958 -958
  13. package/{dsh-mneme/src → lib}/embedding.js +154 -154
  14. package/{dsh-mneme/src → lib}/entities/extractor.js +242 -242
  15. package/{dsh-mneme/lib → lib}/hot-memory.js +53 -53
  16. package/{dsh-mneme/lib → lib}/index.js +361 -361
  17. package/{dsh-mneme/src → lib}/inject.js +208 -208
  18. package/{dsh-mneme/lib → lib}/local-embedder.js +282 -282
  19. package/{dsh-mneme/lib → lib}/mirror.js +170 -170
  20. package/{dsh-mneme/lib → lib}/parser/tag.js +59 -59
  21. package/{dsh-mneme/lib → lib}/parser/wiki-link.js +38 -38
  22. package/{dsh-mneme/src → lib}/quality-filter.js +123 -123
  23. package/{dsh-mneme/lib → lib}/reranker.js +218 -218
  24. package/{dsh-mneme/src → lib}/search/adaptive.js +22 -22
  25. package/{dsh-mneme/src → lib}/search/bm25.js +96 -96
  26. package/{dsh-mneme/src → lib}/search/tag-boost.js +61 -61
  27. package/{dsh-mneme/src → lib}/service.js +1726 -1726
  28. package/{dsh-mneme/lib → lib}/settings.js +172 -172
  29. package/{dsh-mneme/src → lib}/store.js +2238 -2238
  30. package/{dsh-mneme/src → lib}/summarize.js +236 -236
  31. package/{dsh-mneme/lib → lib}/tools.js +290 -290
  32. package/{dsh-mneme/lib → lib}/vector-index.js +116 -116
  33. package/package.json +40 -18
  34. package/{dsh-mneme/scripts → scripts}/benchmark-embed.js +201 -201
  35. package/{dsh-mneme/scripts → scripts}/benchmark-recall.js +133 -133
  36. package/{dsh-mneme/scripts → scripts}/benchmark-rerank.js +166 -166
  37. package/{dsh-mneme/scripts → scripts}/e2e-dsh.js +218 -218
  38. package/{dsh-mneme/scripts → scripts}/stress-dsh.js +255 -255
  39. package/{dsh-mneme/scripts → scripts}/sync-lib.js +52 -52
  40. package/{dsh-mneme/lib → src}/api.js +783 -783
  41. package/{dsh-mneme/lib → src}/commands.js +64 -64
  42. package/{dsh-mneme/src → src}/config.js +298 -298
  43. package/{dsh-mneme/src → src}/dream/clustering.js +118 -118
  44. package/{dsh-mneme/src → src}/dream/decisions.js +488 -488
  45. package/{dsh-mneme/src → src}/dream/sleep.js +561 -561
  46. package/{dsh-mneme/lib → src}/dream/tag-extractor.js +156 -156
  47. package/{dsh-mneme/src → src}/dream.js +958 -958
  48. package/{dsh-mneme/lib → src}/embedding.js +154 -154
  49. package/{dsh-mneme/lib → src}/entities/extractor.js +242 -242
  50. package/{dsh-mneme/src → src}/hot-memory.js +53 -53
  51. package/{dsh-mneme/src → src}/index.js +361 -361
  52. package/{dsh-mneme/lib → src}/inject.js +208 -208
  53. package/{dsh-mneme/src → src}/local-embedder.js +282 -282
  54. package/{dsh-mneme/src → src}/mirror.js +170 -170
  55. package/{dsh-mneme/src → src}/parser/tag.js +59 -59
  56. package/{dsh-mneme/src → src}/parser/wiki-link.js +38 -38
  57. package/{dsh-mneme/lib → src}/quality-filter.js +123 -123
  58. package/{dsh-mneme/src → src}/reranker.js +218 -218
  59. package/{dsh-mneme/lib → src}/search/adaptive.js +22 -22
  60. package/{dsh-mneme/lib → src}/search/bm25.js +96 -96
  61. package/{dsh-mneme/lib → src}/search/tag-boost.js +61 -61
  62. package/{dsh-mneme/lib → src}/service.js +1726 -1726
  63. package/{dsh-mneme/src → src}/settings.js +172 -172
  64. package/{dsh-mneme/lib → src}/store.js +2238 -2238
  65. package/{dsh-mneme/lib → src}/summarize.js +236 -236
  66. package/{dsh-mneme/src → src}/tools.js +290 -290
  67. package/{dsh-mneme/src → src}/vector-index.js +116 -116
  68. package/{dsh-mneme/test → test}/api.test.js +594 -594
  69. package/{dsh-mneme/test → test}/audit.test.js +448 -448
  70. package/{dsh-mneme/test → test}/benchmark.test.js +35 -35
  71. package/{dsh-mneme/test → test}/boundary-v0625.test.js +82 -82
  72. package/{dsh-mneme/test → test}/client.test.js +368 -368
  73. package/{dsh-mneme/test → test}/clustering.test.js +100 -100
  74. package/{dsh-mneme/test → test}/commands.test.js +69 -69
  75. package/{dsh-mneme/test → test}/config.test.js +50 -50
  76. package/{dsh-mneme/test → test}/conflict-freeze.test.js +290 -290
  77. package/{dsh-mneme/test → test}/directory.test.js +134 -134
  78. package/{dsh-mneme/test → test}/dream.test.js +1060 -1060
  79. package/{dsh-mneme/test → test}/entities.test.js +522 -522
  80. package/{dsh-mneme/test → test}/epistemic.test.js +298 -298
  81. package/{dsh-mneme/test → test}/fnew-0112.test.js +311 -311
  82. package/{dsh-mneme/test → test}/fnew-03.test.js +422 -422
  83. package/{dsh-mneme/test → test}/graph-api.test.js +175 -175
  84. package/{dsh-mneme/test → test}/helpers/dream-mock.js +82 -82
  85. package/{dsh-mneme/test → test}/hot-memory.test.js +174 -174
  86. package/{dsh-mneme/test → test}/inject.test.js +103 -103
  87. package/{dsh-mneme/test → test}/llm-audit.test.js +279 -279
  88. package/{dsh-mneme/test → test}/local-embedder.test.js +227 -227
  89. package/{dsh-mneme/test → test}/mirror-dirty.test.js +424 -424
  90. package/{dsh-mneme/test → test}/mirror-edit-digest.test.js +187 -187
  91. package/{dsh-mneme/test → test}/mirror-generation.test.js +499 -499
  92. package/{dsh-mneme/test → test}/mirror.test.js +249 -249
  93. package/{dsh-mneme/test → test}/normalize-decisions.test.js +120 -120
  94. package/{dsh-mneme/test → test}/peer-blockers.test.js +190 -190
  95. package/{dsh-mneme/test → test}/policy-epoch.test.js +259 -259
  96. package/{dsh-mneme/test → test}/provenance.test.js +103 -103
  97. package/{dsh-mneme/test → test}/quality-filter.test.js +118 -118
  98. package/{dsh-mneme/test → test}/reasoning-effort.test.js +199 -199
  99. package/{dsh-mneme/test → test}/recall-evals.test.js +235 -235
  100. package/{dsh-mneme/test → test}/recall-layer.test.js +315 -315
  101. package/{dsh-mneme/test → test}/receipt-chain.test.js +451 -451
  102. package/{dsh-mneme/test → test}/reflection.test.js +226 -226
  103. package/{dsh-mneme/test → test}/reranker.test.js +240 -240
  104. package/{dsh-mneme/test → test}/search-fusion.test.js +90 -90
  105. package/{dsh-mneme/test → test}/semantic.test.js +124 -124
  106. package/{dsh-mneme/test → test}/service-search.test.js +199 -199
  107. package/{dsh-mneme/test → test}/service.test.js +435 -435
  108. package/{dsh-mneme/test → test}/settings.test.js +118 -118
  109. package/{dsh-mneme/test → test}/sleep.test.js +365 -365
  110. package/{dsh-mneme/test → test}/store.test.js +436 -436
  111. package/{dsh-mneme/test → test}/stress.test.js +209 -209
  112. package/{dsh-mneme/test → test}/summarize.test.js +191 -191
  113. package/{dsh-mneme/test → test}/tag-boost.test.js +125 -125
  114. package/{dsh-mneme/test → test}/tag.test.js +312 -312
  115. package/{dsh-mneme/test → test}/tools.test.js +285 -285
  116. package/{dsh-mneme/test → test}/vector-index.test.js +221 -221
  117. package/{dsh-mneme/test → test}/wiki-link.test.js +332 -332
  118. package/.github/workflows/test.yml +0 -32
  119. package/.release-notes-v0.6.9.md +0 -13
  120. package/CHANGELOG.md +0 -89
  121. package/SECURITY.md +0 -544
  122. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +0 -247
  123. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +0 -145
  124. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +0 -56
  125. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +0 -77
  126. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +0 -64
  127. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +0 -90
  128. package/dsh-mneme/CHANGELOG.md +0 -248
  129. package/dsh-mneme/LICENSE +0 -21
  130. package/dsh-mneme/README.md +0 -465
  131. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +0 -183
  132. package/dsh-mneme/docs/ENTITIES.md +0 -245
  133. package/dsh-mneme/docs/LOCAL_MODEL.md +0 -141
  134. package/dsh-mneme/docs/MIGRATION.md +0 -127
  135. package/dsh-mneme/docs/SEMANTIC.md +0 -256
  136. package/dsh-mneme/docs/SLEEP.md +0 -163
  137. package/dsh-mneme/package-lock.json +0 -1936
  138. package/dsh-mneme/package.json +0 -80
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,488 +1,488 @@
1
- const ACTIONS = new Set(["keep", "merge", "archive", "conflict", "update", "create"]);
2
-
3
- // Epistemic trust (v0.4.5): when config.trustEpistemicWeighting is on, merge
4
- // keepSource and conflict winners prefer the higher-trust memory. Higher value
5
- // = preferred. observation (measured) > inferred (derived) > subjective (guess).
6
- const EPISTEMIC_PRIORITY = { observation: 3, inferred: 2, subjective: 1 };
7
-
8
- /**
9
- * Validate a dream decision list against a snapshot of eligible memories.
10
- *
11
- * Issue #26 (skipInvalid): 模型几乎必然为了语义相关性而产出跨类型 merge
12
- * (type 不同,硬性禁止),这类"单条非法"此前让整批校验 ok:false、整单拒绝
13
- * (applied=0、白耗一次 LLM 调用)。`options.skipInvalid` 开启后,逐条非法的
14
- * 决策被跳过(从 decisions 中移除、不 claim 任何 id、记录到 `skipped`),
15
- * 只有全局性错误(update/create 超量、显式覆盖率不足——
16
- * 这些是"模型失控/输出被截断"信号)仍整单拒绝,防洗白语义不变。
17
- * `options.allowCrossTypeMerge`(Issue #26 P1)显式放宽跨类型合并检查——
18
- * 默认 false 保持现有类型边界,true 时跨类型 merge 被允许(类型边界由
19
- * 用户自行承担)。
20
- *
21
- * @param decisions - LLM-produced decision list. In skipInvalid mode, invalid
22
- * entries are spliced out in place so the caller's downstream apply/audit
23
- * operates on the surviving subset only.
24
- * @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
25
- * @returns {{ok: boolean, errors: string[], skipped?: Array<{index, action, ids, error}>}}
26
- */
27
- export function validateDecisions(decisions, snapshot, options = {}) {
28
- const errors = [];
29
- const skipped = [];
30
- const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
31
- const minAgeHours = options.minAgeHours ?? 24;
32
- const skipInvalid = options.skipInvalid === true;
33
- if (!Array.isArray(decisions) || decisions.length === 0) {
34
- return { ok: false, errors: ["decision list must be a non-empty array"] };
35
- }
36
- const claimed = new Set();
37
- const survivors = [];
38
- for (const [index, d] of decisions.entries()) {
39
- const at = `decision[${index}]`;
40
- const local = [];
41
- const ids = d && d.action === "conflict" ? [d.winner, d.loser] : (d?.ids ?? []);
42
- if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
43
- local.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
44
- } else {
45
- if (d.action === "conflict") {
46
- if (!d.winner || !d.loser || d.winner === d.loser) {
47
- local.push(`${at}: conflict needs distinct winner and loser`);
48
- }
49
- } else if (d.action === "create") {
50
- // Mint a fresh memory (sleep pattern discovery). Claims no existing id,
51
- // so it skips the claiming loop below; evidence is optional provenance
52
- // (already filtered to real ids by the caller) and is stored in content.
53
- if (typeof d.title !== "string" || !d.title.trim()) {
54
- local.push(`${at}: create needs non-empty title`);
55
- }
56
- if (typeof d.content !== "string" || !d.content.trim()) {
57
- local.push(`${at}: create needs non-empty content`);
58
- }
59
- if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
60
- local.push(`${at}: create importance must be an integer 1-5 when provided`);
61
- }
62
- if (typeof d.type !== "string" || !d.type.trim()) {
63
- local.push(`${at}: create needs non-empty type`);
64
- }
65
- } else if (!Array.isArray(d.ids) || d.ids.length === 0) {
66
- local.push(`${at}: ${d.action} needs non-empty ids`);
67
- }
68
- // update-specific field validation runs BEFORE claiming ids, so a failing
69
- // update never pollutes the claimed set (which drives the "every id must
70
- // appear in a decision" check below).
71
- if (d.action === "update") {
72
- // 只能更新单条
73
- if (!Array.isArray(d.ids) || d.ids.length !== 1) {
74
- local.push(`${at}: update must target exactly one id`);
75
- } else {
76
- // 必须产生实际变化
77
- const mem = snapshot.get(d.ids[0]);
78
- const hasChange = (d.title !== undefined && d.title !== mem?.title)
79
- || (d.content !== undefined && d.content !== mem?.content)
80
- || (d.importance !== undefined && d.importance !== mem?.importance);
81
- if (!hasChange) {
82
- local.push(`${at}: update must change at least one field`);
83
- }
84
- // 不能更新 summary
85
- if (mem?.type === "summary") {
86
- local.push(`${at}: cannot update summary via update action`);
87
- }
88
- // 保护期:新建记忆不可立即被 update(可配置)
89
- const ageHours = (Date.now() - new Date(mem?.created_at).getTime()) / 3600000;
90
- if (ageHours < minAgeHours) {
91
- local.push(`${at}: memory too young (< ${minAgeHours}h)`);
92
- }
93
- }
94
- }
95
- if (d.action !== "create") {
96
- const seen = new Set();
97
- for (const id of ids) {
98
- const mem = snapshot.get(id);
99
- if (!mem) {
100
- local.push(`${at}: unknown id ${JSON.stringify(id)}`);
101
- } else if (mem.archived || mem.type === "summary") {
102
- local.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
103
- }
104
- // 单决策内重复 id(同一决策引用同一记忆两次)→ 非法;跨决策重复由
105
- // 全局 claimed 检测(只含已通过校验的幸存决策的 claim)。
106
- if (seen.has(id)) {
107
- local.push(`${at}: duplicate id ${JSON.stringify(id)} within one decision`);
108
- }
109
- if (claimed.has(id)) {
110
- local.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
111
- }
112
- seen.add(id);
113
- }
114
- if (d.action === "merge") {
115
- if (!d.keepSource || !d.ids.includes(d.keepSource)) {
116
- local.push(`${at}: merge keepSource must be one of ids`);
117
- }
118
- if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
119
- local.push(`${at}: merge needs non-empty title and content`);
120
- }
121
- if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
122
- local.push(`${at}: merge importance must be an integer 1-5 when provided`);
123
- }
124
- // Merging across types would blur preference/project/decision boundaries
125
- // in the injected context; the snapshot carries each entry's type.
126
- // Issue #26 (P1): 默认禁止跨类型合并(类型有语义作用——preference 注入
127
- // 权重更高、decision/project 注入上下文不同,合并会丢类型边界)。用户显式
128
- // 开启 allowCrossTypeMerge 后放宽该检查,类型边界由用户自行承担。
129
- const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
130
- if (mergeTypes.size > 1 && options.allowCrossTypeMerge !== true) {
131
- local.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
132
- }
133
- }
134
- }
135
- }
136
- if (local.length > 0) {
137
- if (skipInvalid) {
138
- // 单条非法 → 跳过该决策,不 claim id(其目标记忆留给其它合法决策/
139
- // 隐式 keep),并记录到 skipped 供调用方日志/审计。信息性跳过绝不
140
- // 写入全局 errors,否则会误触发下方的整单拒绝。
141
- skipped.push({
142
- index,
143
- action: d?.action,
144
- ids,
145
- error: local.join("; ")
146
- });
147
- } else {
148
- errors.push(...local);
149
- }
150
- continue;
151
- }
152
- if (d.action !== "create") {
153
- for (const id of ids) claimed.add(id);
154
- }
155
- survivors.push(d);
156
- }
157
- // Cap update churn: too many edits in one cycle signals a runaway model.
158
- // These are GLOBAL signals — in skipInvalid mode they still reject the whole
159
- // batch, because a model that floods updates/creates is broken, not just
160
- // slightly schema-drifting.
161
- const updateCount = survivors.filter((d) => d.action === "update").length;
162
- if (updateCount > maxUpdatePerRun) {
163
- errors.push(`too many update decisions: ${updateCount} > ${maxUpdatePerRun}`);
164
- }
165
- // Cap pattern minting per run (sleepMaxPatternPerRun passes through here).
166
- const createCount = survivors.filter((d) => d.action === "create").length;
167
- const maxCreatePerRun = options.maxCreatePerRun ?? 5;
168
- if (createCount > maxCreatePerRun) {
169
- errors.push(`too many create decisions: ${createCount} > ${maxCreatePerRun}`);
170
- }
171
- // v0.4.4: 隐式 keep。默认(dreamImplicitKeep !== false)下,未 claim 的
172
- // snapshot 记忆自动补 {action:"keep"},而不是整体拒绝——大记忆量下 LLM 漏报
173
- // 一两条就全拒(636 记忆 → 677 errors)会白白浪费整轮 run。设 false 则保留
174
- // 旧的严格"全量覆盖"校验。补齐的 keep 直接 append 到 decisions,调用方
175
- // (runDream/applyDecisions/audit)复用同一数组即可覆盖全部 snapshot 记忆。
176
- //
177
- // v0.4.4 fix(残缺输出防洗白):先收集所有非覆盖类 errors,有错直接 ok:false
178
- // 且绝不 push 任何补齐 keep——残缺决策必须被真实拒绝,不能被隐式 keep 洗白成
179
- // ok 后再 apply。只有无错时才检查显式覆盖率:LLM 输出被截断只 claim 少量
180
- // snapshot(claimed.size / snapshot.size < dreamMinExplicitCoverage)时整单拒绝,
181
- // 而不是用 keep 把绝大部分 snapshot 全部"通过"。
182
- if (errors.length > 0) {
183
- return { ok: false, errors, skipped };
184
- }
185
- const minCoverage = options.dreamMinExplicitCoverage ?? 0.5;
186
- if (options.dreamImplicitKeep !== false) {
187
- const coverage = snapshot.size > 0 ? claimed.size / snapshot.size : 1;
188
- if (coverage < minCoverage) {
189
- errors.push(`explicit decision coverage ${Math.round(coverage * 100)}% < minimum ${Math.round(minCoverage * 100)}%`);
190
- return { ok: false, errors, skipped };
191
- }
192
- for (const id of snapshot.keys()) {
193
- if (!claimed.has(id)) survivors.push({ action: "keep", ids: [id] });
194
- }
195
- } else {
196
- for (const id of snapshot.keys()) {
197
- if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
198
- }
199
- if (errors.length > 0) return { ok: false, errors, skipped };
200
- }
201
- // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
202
- // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
203
- // 内容一致时(无跳过、无补齐)为 no-op。
204
- if (survivors.length !== decisions.length) {
205
- decisions.splice(0, decisions.length, ...survivors);
206
- }
207
- return { ok: true, errors, skipped };
208
- }
209
-
210
- /** Marker thrown when a decision target changed since the run snapshot. */
211
- export class CasConflictError extends Error {
212
- constructor(action, ids, reason) {
213
- super(`cas conflict: ${action} targets changed since snapshot (${reason})`);
214
- this.name = "CasConflictError";
215
- this.action = action;
216
- this.ids = ids;
217
- }
218
- }
219
-
220
- function decisionIds(d) {
221
- return d.action === "conflict" ? [d.winner, d.loser] : (d.ids ?? []);
222
- }
223
-
224
- /**
225
- * CAS guard (item ①): every target memory must still match what the run
226
- * snapshot captured — otherwise the decision was computed against stale state
227
- * and applying it would overwrite a concurrent edit. Snapshotless replays skip
228
- * the guard entirely (per-action idempotency checks handle those). Throws
229
- * CasConflictError on the first mismatch; the caller's transaction rolls back.
230
- */
231
- function casGuard(service, snapshot, ids) {
232
- if (!snapshot) return;
233
- for (const id of ids) {
234
- const expect = snapshot.get(id);
235
- if (!expect) continue; // not in snapshot: validated elsewhere, skip guard
236
- const current = service.getById(id);
237
- if (!current) {
238
- throw new CasConflictError("deleted", [id], `memory ${id} was removed`);
239
- }
240
- const changed = expect.updated_at !== undefined
241
- ? current.updated_at !== expect.updated_at
242
- : current.content !== expect.content || current.title !== expect.title;
243
- if (changed) {
244
- throw new CasConflictError(
245
- "changed",
246
- [id],
247
- `memory ${id} was concurrently modified (expected updated_at=${expect.updated_at}, got ${current.updated_at})`
248
- );
249
- }
250
- }
251
- }
252
-
253
- /**
254
- * Apply a validated decision list to the service. Caller must validate first.
255
- * Each decision runs inside its own SQLite transaction (item ②): the multi-step
256
- * mutation of a decision is atomic, so a merge can never leave "keeper updated
257
- * but source not archived" or vice versa — a throwing sub-step rolls the whole
258
- * decision back.
259
- *
260
- * @param decisions - validated decision list.
261
- * @param service - memory service (saveWithDedupe/getById/update/setArchived/transaction).
262
- * @param logger - optional logger ({ warn }); per-decision failures are logged.
263
- * @param snapshot - optional Map<id, memory> captured before the LLM call; when
264
- * provided, every decision target is CAS-checked against it and a decision
265
- * computed from stale state is skipped and reported as a conflict instead of
266
- * overwriting concurrent writes (item ①).
267
- * @returns {{ applied: number, conflicts: Array, failures: Array, committed: Array }}
268
- * applied - number of decisions/memories actually committed (archive counts
269
- * each archived memory as one, merge/conflict/update count one).
270
- * conflicts - decisions skipped because a target changed since the snapshot.
271
- * failures - decisions that threw mid-transaction (fully rolled back).
272
- * committed - the decisions that actually landed, for outcome/receipt based
273
- * on real committed sub-steps rather than the raw LLM list.
274
- */
275
- export function applyDecisions(decisions, service, logger = null, snapshot = null, config = {}) {
276
- let applied = 0;
277
- const conflicts = [];
278
- const failures = [];
279
- const committed = [];
280
- for (const [i, d] of decisions.entries()) {
281
- try {
282
- // keep is a confirmed no-op: it commits nothing but still records the
283
- // per-id disposition so the outcome covers every snapshot memory.
284
- if (d.action === "keep") {
285
- committed.push({ action: "keep", ids: d.ids });
286
- continue;
287
- }
288
- const outcome = applyOne(d, service, snapshot, config);
289
- if (outcome === "skipped") continue;
290
- applied += outcome.applied;
291
- committed.push(outcome.committed);
292
- } catch (error) {
293
- if (error instanceof CasConflictError) {
294
- conflicts.push({ index: i, action: d.action, ids: error.ids, reason: error.message });
295
- logger?.warn?.(`dsh-mneme dream: ${error.message}`);
296
- } else {
297
- failures.push({ index: i, action: d.action, ids: decisionIds(d), reason: error.message });
298
- logger?.warn?.(`dsh-mneme dream: failed to apply ${d.action} at index ${i}: ${error.message}`);
299
- }
300
- }
301
- }
302
- return { applied, conflicts, failures, committed };
303
- }
304
-
305
- function applyOne(d, service, snapshot, config = {}) {
306
- switch (d.action) {
307
- case "archive": return applyArchive(d, service, snapshot);
308
- case "merge": return applyMerge(d, service, snapshot, config);
309
- case "conflict": return applyConflict(d, service, snapshot, config);
310
- case "create": return applyCreate(d, service, config);
311
- default: return applyUpdate(d, service, snapshot, config);
312
- }
313
- }
314
-
315
- /**
316
- * Highest-epistemic-priority UNARCHIVED id among `ids` (ties break toward
317
- * `preferred`). Archived memories are never eligible keepers — promoting one
318
- * would demote the real keepSource to a source and then hit the archived-keeper
319
- * guard in applyMerge, silently skipping the whole merge. When `preferred`
320
- * itself is archived (or missing), fall back to any unarchived candidate.
321
- */
322
- function pickBestKeeper(ids, preferred, service) {
323
- let best = null;
324
- let bestP = -1;
325
- for (const id of ids) {
326
- const mem = service.getById(id);
327
- if (!mem || mem.archived) continue; // archived/missing: ineligible keeper
328
- const p = EPISTEMIC_PRIORITY[mem.epistemic_status] ?? 0;
329
- if (p > bestP || (p === bestP && id === preferred)) {
330
- bestP = p;
331
- best = id;
332
- }
333
- }
334
- return best ?? preferred;
335
- }
336
-
337
- /**
338
- * Mint a fresh memory (pattern discovery). No existing target, so no CAS guard.
339
- * Evidence ids ride in the content so a pattern stays traceable to its source
340
- * memories. saveWithDedupe dedupes identical mints (idempotent replay-safe).
341
- */
342
- function applyCreate(d, service, config = {}) {
343
- const title = String(d.title ?? "").trim();
344
- const content = String(d.content ?? "").trim();
345
- const importance = Number.isInteger(d.importance) ? d.importance : 3;
346
- const type = typeof d.type === "string" ? d.type : "pattern";
347
- const evidence = Array.isArray(d.evidence)
348
- ? d.evidence.filter((id) => typeof id === "string")
349
- : [];
350
- const body = evidence.length > 0
351
- ? `${content}\n\n[证据: ${evidence.join(", ")}]`
352
- : content;
353
- const created = service.saveWithDedupe({ type, title, content: body, importance });
354
- const memory = created?.memory;
355
- if (!memory) return "skipped"; // deduped/subsumed: nothing minted, clean no-op
356
- return { applied: 1, committed: { action: "create", id: memory.id, type } };
357
- }
358
-
359
- function applyArchive(d, service, snapshot) {
360
- const targets = d.ids.filter((id) => {
361
- const mem = service.getById(id);
362
- return mem && !mem.archived; // existing, not-yet-archived rows only
363
- });
364
- if (targets.length === 0) return "skipped"; // all already archived: idempotent replay
365
- service.transaction(() => {
366
- casGuard(service, snapshot, d.ids);
367
- for (const id of d.ids) {
368
- const mem = service.getById(id);
369
- if (mem && !mem.archived) service.setArchived(id, true);
370
- }
371
- });
372
- return { applied: targets.length, committed: { action: "archive", ids: targets } };
373
- }
374
-
375
- function applyMerge(d, service, snapshot, config = {}) {
376
- // Epistemic trust (v0.4.5): when enabled, prefer an observation keeper over a
377
- // subjective/inferred one. Mutating the decision keeps the receipt + committed
378
- // record aligned with the actual keeper.
379
- if (config.trustEpistemicWeighting === true) {
380
- const best = pickBestKeeper(d.ids, d.keepSource, service);
381
- if (best && best !== d.keepSource) d.keepSource = best;
382
- }
383
- const sources = d.ids.filter((id) => id !== d.keepSource);
384
- // Idempotent replay: if every other source is already archived, this merge
385
- // already landed — skip so a replayed/concurrent decision never double-counts
386
- // or re-applies (guard against duplicate merges).
387
- if (sources.every((id) => service.getById(id)?.archived)) return "skipped";
388
- service.transaction(() => {
389
- casGuard(service, snapshot, d.ids);
390
- const keeper = service.getById(d.keepSource);
391
- if (!keeper || keeper.archived) return; // missing keeper: no write, still a clean commit
392
- service.update(d.keepSource, {
393
- title: d.title,
394
- content: d.content,
395
- importance: d.importance ?? Math.max(keeper.importance, ...d.ids.map((id) => service.getById(id)?.importance ?? 1))
396
- });
397
- for (const id of sources) {
398
- const mem = service.getById(id);
399
- if (mem && !mem.archived) service.setArchived(id, true);
400
- }
401
- // 4.3.2 迁移实体关联(opt-in):将 loser(source)记忆关联的 entity_attrs 的
402
- // memory_id 迁移到 keeper;keeper 已有同 entity+key 的当前属性时 loser 行被
403
- // 失效。单个 source 迁移失败只告警,绝不能导致整个 merge 事务回滚(fail-safe)。
404
- if (config.entityExtractionEnabled && typeof service.migrateAttrsToMemory === "function") {
405
- for (const id of sources) {
406
- try {
407
- service.migrateAttrsToMemory(id, d.keepSource, new Date().toISOString());
408
- } catch (error) {
409
- logger?.warn?.(`dsh-mneme dream: failed to migrate attrs from ${id} to ${d.keepSource}: ${error.message}`);
410
- }
411
- }
412
- }
413
- });
414
- return {
415
- applied: 1,
416
- 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 }
417
- };
418
- }
419
-
420
- function applyConflict(d, service, snapshot, config = {}) {
421
- // Epistemic trust (v0.4.5): when enabled, the observation side of a conflict
422
- // is preferred as winner over a subjective/inferred one.
423
- if (config.trustEpistemicWeighting === true) {
424
- const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
425
- const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
426
- if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
427
- }
428
- const winner = service.getById(d.winner);
429
- const loser = service.getById(d.loser);
430
- if (!winner || !loser) return "skipped";
431
- // Idempotent replay: an already-archived loser means the conflict was already
432
- // adjudicated — skip so the provenance note is never re-appended and the loser
433
- // is not re-archived.
434
- if (loser.archived) return "skipped";
435
- service.transaction(() => {
436
- casGuard(service, snapshot, [d.winner, d.loser]);
437
- const winnerNow = service.getById(d.winner);
438
- const loserNow = service.getById(d.loser);
439
- if (!winnerNow || !loserNow || loserNow.archived) return;
440
- service.update(d.winner, {
441
- content: `${winnerNow.content}\n\n(已否决旧信息:${[...loserNow.content].slice(0, 100).join("")})`
442
- });
443
- service.setArchived(d.loser, true);
444
- });
445
- return { applied: 1, committed: { action: "conflict", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
446
- }
447
-
448
- function applyUpdate(d, service, snapshot, config = {}) {
449
- const id = d.ids[0];
450
- const mem = service.getById(id);
451
- if (!mem || mem.archived) return "skipped";
452
- // 幂等检查:如果字段已与目标一致则跳过
453
- const same = (d.title === undefined || d.title === mem.title)
454
- && (d.content === undefined || d.content === mem.content)
455
- && (d.importance === undefined || d.importance === mem.importance);
456
- if (same) return "skipped";
457
- service.transaction(() => {
458
- casGuard(service, snapshot, [id]);
459
- const cur = service.getById(id);
460
- if (!cur || cur.archived) return;
461
- service.update(id, {
462
- title: d.title ?? cur.title,
463
- content: d.content ?? cur.content,
464
- importance: d.importance ?? cur.importance
465
- });
466
- });
467
- // 4.3.1 supersedes 关系(opt-in):事务提交成功后,为该记忆关联的每条实体属性
468
- // 建立自引用 supersedes 关系,表示"此属性版本已被替代"。仅记录、绝不阻断主流程
469
- // (fail-safe):记录失败只告警,update 本身照常生效。
470
- if (config.entityExtractionEnabled && typeof service.saveRelation === "function" && typeof service.getAttrsByMemory === "function") {
471
- try {
472
- const oldAttrs = service.getAttrsByMemory(id);
473
- for (const attr of oldAttrs) {
474
- if (!attr.entity_id) continue;
475
- service.saveRelation({
476
- from_entity: attr.entity_id,
477
- to_entity: attr.entity_id,
478
- relation_type: "supersedes",
479
- memory_id: id,
480
- metadata: JSON.stringify({ attr_key: attr.attr_key, old_value: attr.attr_value })
481
- });
482
- }
483
- } catch (error) {
484
- logger?.warn?.(`dsh-mneme dream: failed to record supersedes relations for ${id}: ${error.message}`);
485
- }
486
- }
487
- return { applied: 1, committed: { action: "update", ids: [id], title: d.title, content: d.content, importance: d.importance, count_before: 1, count_after: 1 } };
488
- }
1
+ const ACTIONS = new Set(["keep", "merge", "archive", "conflict", "update", "create"]);
2
+
3
+ // Epistemic trust (v0.4.5): when config.trustEpistemicWeighting is on, merge
4
+ // keepSource and conflict winners prefer the higher-trust memory. Higher value
5
+ // = preferred. observation (measured) > inferred (derived) > subjective (guess).
6
+ const EPISTEMIC_PRIORITY = { observation: 3, inferred: 2, subjective: 1 };
7
+
8
+ /**
9
+ * Validate a dream decision list against a snapshot of eligible memories.
10
+ *
11
+ * Issue #26 (skipInvalid): 模型几乎必然为了语义相关性而产出跨类型 merge
12
+ * (type 不同,硬性禁止),这类"单条非法"此前让整批校验 ok:false、整单拒绝
13
+ * (applied=0、白耗一次 LLM 调用)。`options.skipInvalid` 开启后,逐条非法的
14
+ * 决策被跳过(从 decisions 中移除、不 claim 任何 id、记录到 `skipped`),
15
+ * 只有全局性错误(update/create 超量、显式覆盖率不足——
16
+ * 这些是"模型失控/输出被截断"信号)仍整单拒绝,防洗白语义不变。
17
+ * `options.allowCrossTypeMerge`(Issue #26 P1)显式放宽跨类型合并检查——
18
+ * 默认 false 保持现有类型边界,true 时跨类型 merge 被允许(类型边界由
19
+ * 用户自行承担)。
20
+ *
21
+ * @param decisions - LLM-produced decision list. In skipInvalid mode, invalid
22
+ * entries are spliced out in place so the caller's downstream apply/audit
23
+ * operates on the surviving subset only.
24
+ * @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
25
+ * @returns {{ok: boolean, errors: string[], skipped?: Array<{index, action, ids, error}>}}
26
+ */
27
+ export function validateDecisions(decisions, snapshot, options = {}) {
28
+ const errors = [];
29
+ const skipped = [];
30
+ const maxUpdatePerRun = options.maxUpdatePerRun ?? 2;
31
+ const minAgeHours = options.minAgeHours ?? 24;
32
+ const skipInvalid = options.skipInvalid === true;
33
+ if (!Array.isArray(decisions) || decisions.length === 0) {
34
+ return { ok: false, errors: ["decision list must be a non-empty array"] };
35
+ }
36
+ const claimed = new Set();
37
+ const survivors = [];
38
+ for (const [index, d] of decisions.entries()) {
39
+ const at = `decision[${index}]`;
40
+ const local = [];
41
+ const ids = d && d.action === "conflict" ? [d.winner, d.loser] : (d?.ids ?? []);
42
+ if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
43
+ local.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
44
+ } else {
45
+ if (d.action === "conflict") {
46
+ if (!d.winner || !d.loser || d.winner === d.loser) {
47
+ local.push(`${at}: conflict needs distinct winner and loser`);
48
+ }
49
+ } else if (d.action === "create") {
50
+ // Mint a fresh memory (sleep pattern discovery). Claims no existing id,
51
+ // so it skips the claiming loop below; evidence is optional provenance
52
+ // (already filtered to real ids by the caller) and is stored in content.
53
+ if (typeof d.title !== "string" || !d.title.trim()) {
54
+ local.push(`${at}: create needs non-empty title`);
55
+ }
56
+ if (typeof d.content !== "string" || !d.content.trim()) {
57
+ local.push(`${at}: create needs non-empty content`);
58
+ }
59
+ if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
60
+ local.push(`${at}: create importance must be an integer 1-5 when provided`);
61
+ }
62
+ if (typeof d.type !== "string" || !d.type.trim()) {
63
+ local.push(`${at}: create needs non-empty type`);
64
+ }
65
+ } else if (!Array.isArray(d.ids) || d.ids.length === 0) {
66
+ local.push(`${at}: ${d.action} needs non-empty ids`);
67
+ }
68
+ // update-specific field validation runs BEFORE claiming ids, so a failing
69
+ // update never pollutes the claimed set (which drives the "every id must
70
+ // appear in a decision" check below).
71
+ if (d.action === "update") {
72
+ // 只能更新单条
73
+ if (!Array.isArray(d.ids) || d.ids.length !== 1) {
74
+ local.push(`${at}: update must target exactly one id`);
75
+ } else {
76
+ // 必须产生实际变化
77
+ const mem = snapshot.get(d.ids[0]);
78
+ const hasChange = (d.title !== undefined && d.title !== mem?.title)
79
+ || (d.content !== undefined && d.content !== mem?.content)
80
+ || (d.importance !== undefined && d.importance !== mem?.importance);
81
+ if (!hasChange) {
82
+ local.push(`${at}: update must change at least one field`);
83
+ }
84
+ // 不能更新 summary
85
+ if (mem?.type === "summary") {
86
+ local.push(`${at}: cannot update summary via update action`);
87
+ }
88
+ // 保护期:新建记忆不可立即被 update(可配置)
89
+ const ageHours = (Date.now() - new Date(mem?.created_at).getTime()) / 3600000;
90
+ if (ageHours < minAgeHours) {
91
+ local.push(`${at}: memory too young (< ${minAgeHours}h)`);
92
+ }
93
+ }
94
+ }
95
+ if (d.action !== "create") {
96
+ const seen = new Set();
97
+ for (const id of ids) {
98
+ const mem = snapshot.get(id);
99
+ if (!mem) {
100
+ local.push(`${at}: unknown id ${JSON.stringify(id)}`);
101
+ } else if (mem.archived || mem.type === "summary") {
102
+ local.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
103
+ }
104
+ // 单决策内重复 id(同一决策引用同一记忆两次)→ 非法;跨决策重复由
105
+ // 全局 claimed 检测(只含已通过校验的幸存决策的 claim)。
106
+ if (seen.has(id)) {
107
+ local.push(`${at}: duplicate id ${JSON.stringify(id)} within one decision`);
108
+ }
109
+ if (claimed.has(id)) {
110
+ local.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
111
+ }
112
+ seen.add(id);
113
+ }
114
+ if (d.action === "merge") {
115
+ if (!d.keepSource || !d.ids.includes(d.keepSource)) {
116
+ local.push(`${at}: merge keepSource must be one of ids`);
117
+ }
118
+ if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
119
+ local.push(`${at}: merge needs non-empty title and content`);
120
+ }
121
+ if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
122
+ local.push(`${at}: merge importance must be an integer 1-5 when provided`);
123
+ }
124
+ // Merging across types would blur preference/project/decision boundaries
125
+ // in the injected context; the snapshot carries each entry's type.
126
+ // Issue #26 (P1): 默认禁止跨类型合并(类型有语义作用——preference 注入
127
+ // 权重更高、decision/project 注入上下文不同,合并会丢类型边界)。用户显式
128
+ // 开启 allowCrossTypeMerge 后放宽该检查,类型边界由用户自行承担。
129
+ const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
130
+ if (mergeTypes.size > 1 && options.allowCrossTypeMerge !== true) {
131
+ local.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
132
+ }
133
+ }
134
+ }
135
+ }
136
+ if (local.length > 0) {
137
+ if (skipInvalid) {
138
+ // 单条非法 → 跳过该决策,不 claim id(其目标记忆留给其它合法决策/
139
+ // 隐式 keep),并记录到 skipped 供调用方日志/审计。信息性跳过绝不
140
+ // 写入全局 errors,否则会误触发下方的整单拒绝。
141
+ skipped.push({
142
+ index,
143
+ action: d?.action,
144
+ ids,
145
+ error: local.join("; ")
146
+ });
147
+ } else {
148
+ errors.push(...local);
149
+ }
150
+ continue;
151
+ }
152
+ if (d.action !== "create") {
153
+ for (const id of ids) claimed.add(id);
154
+ }
155
+ survivors.push(d);
156
+ }
157
+ // Cap update churn: too many edits in one cycle signals a runaway model.
158
+ // These are GLOBAL signals — in skipInvalid mode they still reject the whole
159
+ // batch, because a model that floods updates/creates is broken, not just
160
+ // slightly schema-drifting.
161
+ const updateCount = survivors.filter((d) => d.action === "update").length;
162
+ if (updateCount > maxUpdatePerRun) {
163
+ errors.push(`too many update decisions: ${updateCount} > ${maxUpdatePerRun}`);
164
+ }
165
+ // Cap pattern minting per run (sleepMaxPatternPerRun passes through here).
166
+ const createCount = survivors.filter((d) => d.action === "create").length;
167
+ const maxCreatePerRun = options.maxCreatePerRun ?? 5;
168
+ if (createCount > maxCreatePerRun) {
169
+ errors.push(`too many create decisions: ${createCount} > ${maxCreatePerRun}`);
170
+ }
171
+ // v0.4.4: 隐式 keep。默认(dreamImplicitKeep !== false)下,未 claim 的
172
+ // snapshot 记忆自动补 {action:"keep"},而不是整体拒绝——大记忆量下 LLM 漏报
173
+ // 一两条就全拒(636 记忆 → 677 errors)会白白浪费整轮 run。设 false 则保留
174
+ // 旧的严格"全量覆盖"校验。补齐的 keep 直接 append 到 decisions,调用方
175
+ // (runDream/applyDecisions/audit)复用同一数组即可覆盖全部 snapshot 记忆。
176
+ //
177
+ // v0.4.4 fix(残缺输出防洗白):先收集所有非覆盖类 errors,有错直接 ok:false
178
+ // 且绝不 push 任何补齐 keep——残缺决策必须被真实拒绝,不能被隐式 keep 洗白成
179
+ // ok 后再 apply。只有无错时才检查显式覆盖率:LLM 输出被截断只 claim 少量
180
+ // snapshot(claimed.size / snapshot.size < dreamMinExplicitCoverage)时整单拒绝,
181
+ // 而不是用 keep 把绝大部分 snapshot 全部"通过"。
182
+ if (errors.length > 0) {
183
+ return { ok: false, errors, skipped };
184
+ }
185
+ const minCoverage = options.dreamMinExplicitCoverage ?? 0.5;
186
+ if (options.dreamImplicitKeep !== false) {
187
+ const coverage = snapshot.size > 0 ? claimed.size / snapshot.size : 1;
188
+ if (coverage < minCoverage) {
189
+ errors.push(`explicit decision coverage ${Math.round(coverage * 100)}% < minimum ${Math.round(minCoverage * 100)}%`);
190
+ return { ok: false, errors, skipped };
191
+ }
192
+ for (const id of snapshot.keys()) {
193
+ if (!claimed.has(id)) survivors.push({ action: "keep", ids: [id] });
194
+ }
195
+ } else {
196
+ for (const id of snapshot.keys()) {
197
+ if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
198
+ }
199
+ if (errors.length > 0) return { ok: false, errors, skipped };
200
+ }
201
+ // 调用方下游(apply/audit)复用同一 decisions 引用:就地同步为 survivors——
202
+ // 在 skipInvalid 模式下去掉被跳过的非法决策;在隐式 keep 下追加补齐的 keep。
203
+ // 内容一致时(无跳过、无补齐)为 no-op。
204
+ if (survivors.length !== decisions.length) {
205
+ decisions.splice(0, decisions.length, ...survivors);
206
+ }
207
+ return { ok: true, errors, skipped };
208
+ }
209
+
210
+ /** Marker thrown when a decision target changed since the run snapshot. */
211
+ export class CasConflictError extends Error {
212
+ constructor(action, ids, reason) {
213
+ super(`cas conflict: ${action} targets changed since snapshot (${reason})`);
214
+ this.name = "CasConflictError";
215
+ this.action = action;
216
+ this.ids = ids;
217
+ }
218
+ }
219
+
220
+ function decisionIds(d) {
221
+ return d.action === "conflict" ? [d.winner, d.loser] : (d.ids ?? []);
222
+ }
223
+
224
+ /**
225
+ * CAS guard (item ①): every target memory must still match what the run
226
+ * snapshot captured — otherwise the decision was computed against stale state
227
+ * and applying it would overwrite a concurrent edit. Snapshotless replays skip
228
+ * the guard entirely (per-action idempotency checks handle those). Throws
229
+ * CasConflictError on the first mismatch; the caller's transaction rolls back.
230
+ */
231
+ function casGuard(service, snapshot, ids) {
232
+ if (!snapshot) return;
233
+ for (const id of ids) {
234
+ const expect = snapshot.get(id);
235
+ if (!expect) continue; // not in snapshot: validated elsewhere, skip guard
236
+ const current = service.getById(id);
237
+ if (!current) {
238
+ throw new CasConflictError("deleted", [id], `memory ${id} was removed`);
239
+ }
240
+ const changed = expect.updated_at !== undefined
241
+ ? current.updated_at !== expect.updated_at
242
+ : current.content !== expect.content || current.title !== expect.title;
243
+ if (changed) {
244
+ throw new CasConflictError(
245
+ "changed",
246
+ [id],
247
+ `memory ${id} was concurrently modified (expected updated_at=${expect.updated_at}, got ${current.updated_at})`
248
+ );
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Apply a validated decision list to the service. Caller must validate first.
255
+ * Each decision runs inside its own SQLite transaction (item ②): the multi-step
256
+ * mutation of a decision is atomic, so a merge can never leave "keeper updated
257
+ * but source not archived" or vice versa — a throwing sub-step rolls the whole
258
+ * decision back.
259
+ *
260
+ * @param decisions - validated decision list.
261
+ * @param service - memory service (saveWithDedupe/getById/update/setArchived/transaction).
262
+ * @param logger - optional logger ({ warn }); per-decision failures are logged.
263
+ * @param snapshot - optional Map<id, memory> captured before the LLM call; when
264
+ * provided, every decision target is CAS-checked against it and a decision
265
+ * computed from stale state is skipped and reported as a conflict instead of
266
+ * overwriting concurrent writes (item ①).
267
+ * @returns {{ applied: number, conflicts: Array, failures: Array, committed: Array }}
268
+ * applied - number of decisions/memories actually committed (archive counts
269
+ * each archived memory as one, merge/conflict/update count one).
270
+ * conflicts - decisions skipped because a target changed since the snapshot.
271
+ * failures - decisions that threw mid-transaction (fully rolled back).
272
+ * committed - the decisions that actually landed, for outcome/receipt based
273
+ * on real committed sub-steps rather than the raw LLM list.
274
+ */
275
+ export function applyDecisions(decisions, service, logger = null, snapshot = null, config = {}) {
276
+ let applied = 0;
277
+ const conflicts = [];
278
+ const failures = [];
279
+ const committed = [];
280
+ for (const [i, d] of decisions.entries()) {
281
+ try {
282
+ // keep is a confirmed no-op: it commits nothing but still records the
283
+ // per-id disposition so the outcome covers every snapshot memory.
284
+ if (d.action === "keep") {
285
+ committed.push({ action: "keep", ids: d.ids });
286
+ continue;
287
+ }
288
+ const outcome = applyOne(d, service, snapshot, config);
289
+ if (outcome === "skipped") continue;
290
+ applied += outcome.applied;
291
+ committed.push(outcome.committed);
292
+ } catch (error) {
293
+ if (error instanceof CasConflictError) {
294
+ conflicts.push({ index: i, action: d.action, ids: error.ids, reason: error.message });
295
+ logger?.warn?.(`dsh-mneme dream: ${error.message}`);
296
+ } else {
297
+ failures.push({ index: i, action: d.action, ids: decisionIds(d), reason: error.message });
298
+ logger?.warn?.(`dsh-mneme dream: failed to apply ${d.action} at index ${i}: ${error.message}`);
299
+ }
300
+ }
301
+ }
302
+ return { applied, conflicts, failures, committed };
303
+ }
304
+
305
+ function applyOne(d, service, snapshot, config = {}) {
306
+ switch (d.action) {
307
+ case "archive": return applyArchive(d, service, snapshot);
308
+ case "merge": return applyMerge(d, service, snapshot, config);
309
+ case "conflict": return applyConflict(d, service, snapshot, config);
310
+ case "create": return applyCreate(d, service, config);
311
+ default: return applyUpdate(d, service, snapshot, config);
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Highest-epistemic-priority UNARCHIVED id among `ids` (ties break toward
317
+ * `preferred`). Archived memories are never eligible keepers — promoting one
318
+ * would demote the real keepSource to a source and then hit the archived-keeper
319
+ * guard in applyMerge, silently skipping the whole merge. When `preferred`
320
+ * itself is archived (or missing), fall back to any unarchived candidate.
321
+ */
322
+ function pickBestKeeper(ids, preferred, service) {
323
+ let best = null;
324
+ let bestP = -1;
325
+ for (const id of ids) {
326
+ const mem = service.getById(id);
327
+ if (!mem || mem.archived) continue; // archived/missing: ineligible keeper
328
+ const p = EPISTEMIC_PRIORITY[mem.epistemic_status] ?? 0;
329
+ if (p > bestP || (p === bestP && id === preferred)) {
330
+ bestP = p;
331
+ best = id;
332
+ }
333
+ }
334
+ return best ?? preferred;
335
+ }
336
+
337
+ /**
338
+ * Mint a fresh memory (pattern discovery). No existing target, so no CAS guard.
339
+ * Evidence ids ride in the content so a pattern stays traceable to its source
340
+ * memories. saveWithDedupe dedupes identical mints (idempotent replay-safe).
341
+ */
342
+ function applyCreate(d, service, config = {}) {
343
+ const title = String(d.title ?? "").trim();
344
+ const content = String(d.content ?? "").trim();
345
+ const importance = Number.isInteger(d.importance) ? d.importance : 3;
346
+ const type = typeof d.type === "string" ? d.type : "pattern";
347
+ const evidence = Array.isArray(d.evidence)
348
+ ? d.evidence.filter((id) => typeof id === "string")
349
+ : [];
350
+ const body = evidence.length > 0
351
+ ? `${content}\n\n[证据: ${evidence.join(", ")}]`
352
+ : content;
353
+ const created = service.saveWithDedupe({ type, title, content: body, importance });
354
+ const memory = created?.memory;
355
+ if (!memory) return "skipped"; // deduped/subsumed: nothing minted, clean no-op
356
+ return { applied: 1, committed: { action: "create", id: memory.id, type } };
357
+ }
358
+
359
+ function applyArchive(d, service, snapshot) {
360
+ const targets = d.ids.filter((id) => {
361
+ const mem = service.getById(id);
362
+ return mem && !mem.archived; // existing, not-yet-archived rows only
363
+ });
364
+ if (targets.length === 0) return "skipped"; // all already archived: idempotent replay
365
+ service.transaction(() => {
366
+ casGuard(service, snapshot, d.ids);
367
+ for (const id of d.ids) {
368
+ const mem = service.getById(id);
369
+ if (mem && !mem.archived) service.setArchived(id, true);
370
+ }
371
+ });
372
+ return { applied: targets.length, committed: { action: "archive", ids: targets } };
373
+ }
374
+
375
+ function applyMerge(d, service, snapshot, config = {}) {
376
+ // Epistemic trust (v0.4.5): when enabled, prefer an observation keeper over a
377
+ // subjective/inferred one. Mutating the decision keeps the receipt + committed
378
+ // record aligned with the actual keeper.
379
+ if (config.trustEpistemicWeighting === true) {
380
+ const best = pickBestKeeper(d.ids, d.keepSource, service);
381
+ if (best && best !== d.keepSource) d.keepSource = best;
382
+ }
383
+ const sources = d.ids.filter((id) => id !== d.keepSource);
384
+ // Idempotent replay: if every other source is already archived, this merge
385
+ // already landed — skip so a replayed/concurrent decision never double-counts
386
+ // or re-applies (guard against duplicate merges).
387
+ if (sources.every((id) => service.getById(id)?.archived)) return "skipped";
388
+ service.transaction(() => {
389
+ casGuard(service, snapshot, d.ids);
390
+ const keeper = service.getById(d.keepSource);
391
+ if (!keeper || keeper.archived) return; // missing keeper: no write, still a clean commit
392
+ service.update(d.keepSource, {
393
+ title: d.title,
394
+ content: d.content,
395
+ importance: d.importance ?? Math.max(keeper.importance, ...d.ids.map((id) => service.getById(id)?.importance ?? 1))
396
+ });
397
+ for (const id of sources) {
398
+ const mem = service.getById(id);
399
+ if (mem && !mem.archived) service.setArchived(id, true);
400
+ }
401
+ // 4.3.2 迁移实体关联(opt-in):将 loser(source)记忆关联的 entity_attrs 的
402
+ // memory_id 迁移到 keeper;keeper 已有同 entity+key 的当前属性时 loser 行被
403
+ // 失效。单个 source 迁移失败只告警,绝不能导致整个 merge 事务回滚(fail-safe)。
404
+ if (config.entityExtractionEnabled && typeof service.migrateAttrsToMemory === "function") {
405
+ for (const id of sources) {
406
+ try {
407
+ service.migrateAttrsToMemory(id, d.keepSource, new Date().toISOString());
408
+ } catch (error) {
409
+ logger?.warn?.(`dsh-mneme dream: failed to migrate attrs from ${id} to ${d.keepSource}: ${error.message}`);
410
+ }
411
+ }
412
+ }
413
+ });
414
+ return {
415
+ applied: 1,
416
+ 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 }
417
+ };
418
+ }
419
+
420
+ function applyConflict(d, service, snapshot, config = {}) {
421
+ // Epistemic trust (v0.4.5): when enabled, the observation side of a conflict
422
+ // is preferred as winner over a subjective/inferred one.
423
+ if (config.trustEpistemicWeighting === true) {
424
+ const pw = EPISTEMIC_PRIORITY[service.getById(d.winner)?.epistemic_status] ?? 0;
425
+ const pl = EPISTEMIC_PRIORITY[service.getById(d.loser)?.epistemic_status] ?? 0;
426
+ if (pl > pw) [d.winner, d.loser] = [d.loser, d.winner];
427
+ }
428
+ const winner = service.getById(d.winner);
429
+ const loser = service.getById(d.loser);
430
+ if (!winner || !loser) return "skipped";
431
+ // Idempotent replay: an already-archived loser means the conflict was already
432
+ // adjudicated — skip so the provenance note is never re-appended and the loser
433
+ // is not re-archived.
434
+ if (loser.archived) return "skipped";
435
+ service.transaction(() => {
436
+ casGuard(service, snapshot, [d.winner, d.loser]);
437
+ const winnerNow = service.getById(d.winner);
438
+ const loserNow = service.getById(d.loser);
439
+ if (!winnerNow || !loserNow || loserNow.archived) return;
440
+ service.update(d.winner, {
441
+ content: `${winnerNow.content}\n\n(已否决旧信息:${[...loserNow.content].slice(0, 100).join("")})`
442
+ });
443
+ service.setArchived(d.loser, true);
444
+ });
445
+ return { applied: 1, committed: { action: "conflict", winner: d.winner, loser: d.loser, count_before: 2, count_after: 1 } };
446
+ }
447
+
448
+ function applyUpdate(d, service, snapshot, config = {}) {
449
+ const id = d.ids[0];
450
+ const mem = service.getById(id);
451
+ if (!mem || mem.archived) return "skipped";
452
+ // 幂等检查:如果字段已与目标一致则跳过
453
+ const same = (d.title === undefined || d.title === mem.title)
454
+ && (d.content === undefined || d.content === mem.content)
455
+ && (d.importance === undefined || d.importance === mem.importance);
456
+ if (same) return "skipped";
457
+ service.transaction(() => {
458
+ casGuard(service, snapshot, [id]);
459
+ const cur = service.getById(id);
460
+ if (!cur || cur.archived) return;
461
+ service.update(id, {
462
+ title: d.title ?? cur.title,
463
+ content: d.content ?? cur.content,
464
+ importance: d.importance ?? cur.importance
465
+ });
466
+ });
467
+ // 4.3.1 supersedes 关系(opt-in):事务提交成功后,为该记忆关联的每条实体属性
468
+ // 建立自引用 supersedes 关系,表示"此属性版本已被替代"。仅记录、绝不阻断主流程
469
+ // (fail-safe):记录失败只告警,update 本身照常生效。
470
+ if (config.entityExtractionEnabled && typeof service.saveRelation === "function" && typeof service.getAttrsByMemory === "function") {
471
+ try {
472
+ const oldAttrs = service.getAttrsByMemory(id);
473
+ for (const attr of oldAttrs) {
474
+ if (!attr.entity_id) continue;
475
+ service.saveRelation({
476
+ from_entity: attr.entity_id,
477
+ to_entity: attr.entity_id,
478
+ relation_type: "supersedes",
479
+ memory_id: id,
480
+ metadata: JSON.stringify({ attr_key: attr.attr_key, old_value: attr.attr_value })
481
+ });
482
+ }
483
+ } catch (error) {
484
+ logger?.warn?.(`dsh-mneme dream: failed to record supersedes relations for ${id}: ${error.message}`);
485
+ }
486
+ }
487
+ return { applied: 1, committed: { action: "update", ids: [id], title: d.title, content: d.content, importance: d.importance, count_before: 1, count_after: 1 } };
488
+ }