@modusensus/dsh-mneme 0.8.4 → 0.8.5

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