@modusensus/dsh-mneme 0.6.7 → 0.6.9

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