@modusensus/dsh-mneme 0.8.2 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +718 -633
- package/bin/cli.mjs +0 -0
- package/bin/dsh-mneme-mcp.mjs +502 -0
- package/cordis.patch.yml +21 -21
- package/lib/api-standalone.js +495 -316
- package/lib/api.js +1382 -1316
- package/lib/bootstrap.js +211 -0
- package/lib/client.js +4475 -4362
- package/lib/commands.js +95 -95
- package/lib/config.js +533 -500
- package/lib/dream/clustering.js +118 -118
- package/lib/dream/decisions.js +658 -658
- package/lib/dream/narratives.js +44 -0
- package/lib/dream/sleep.js +700 -700
- package/lib/dream.js +1319 -1216
- package/lib/embedding.js +177 -177
- package/lib/entities/extractor.js +249 -249
- package/lib/heat.js +142 -136
- package/lib/hot-memory.js +46 -46
- package/lib/index.js +515 -513
- package/lib/inject.js +299 -253
- package/lib/lang.js +202 -179
- package/lib/local-embedder.js +320 -308
- package/lib/mirror.js +198 -198
- package/lib/quality-filter.js +126 -126
- package/lib/recall-stats.js +103 -0
- package/lib/reranker.js +269 -260
- package/lib/runtime/adopt.js +176 -176
- package/lib/runtime/closure.js +172 -172
- package/lib/runtime/download.js +247 -247
- package/lib/runtime/layout.js +235 -235
- package/lib/runtime/loader.js +249 -249
- package/lib/runtime/model-fetch.js +361 -0
- package/lib/runtime/provision.js +237 -237
- package/lib/runtime/tarball.js +130 -130
- package/lib/runtime/verify.js +191 -191
- package/lib/scope.js +118 -118
- package/lib/search/adaptive.js +22 -22
- package/lib/search/bm25.js +96 -96
- package/lib/service.js +2171 -2071
- package/lib/settings.js +430 -419
- package/lib/store.js +2448 -2367
- package/lib/summarize.js +575 -449
- package/lib/tools.js +574 -574
- package/lib/vector-index.js +110 -110
- package/lib/version-check.js +122 -122
- package/package.json +109 -108
- package/runtime-manifest.json +596 -596
- package/scripts/benchmark-embed.js +201 -201
- package/scripts/benchmark-recall.js +199 -199
- package/scripts/benchmark-rerank.js +166 -166
- package/scripts/build-runtime-manifest.mjs +217 -217
- package/scripts/check-sync.js +42 -42
- package/scripts/e2e-dsh.js +220 -220
- package/scripts/mneme-runtime.mjs +277 -277
- package/scripts/stress-dsh.js +255 -255
- package/scripts/sync-lib.js +47 -47
- package/scripts/sync-test-badge.mjs +61 -61
- package/src/api-standalone.js +495 -316
- package/src/api.js +1382 -1316
- package/src/bootstrap.js +211 -0
- package/src/commands.js +95 -95
- package/src/config.js +533 -500
- package/src/dream/clustering.js +118 -118
- package/src/dream/decisions.js +658 -658
- package/src/dream/narratives.js +44 -0
- package/src/dream/sleep.js +700 -700
- package/src/dream.js +1319 -1216
- package/src/embedding.js +177 -177
- package/src/entities/extractor.js +249 -249
- package/src/heat.js +142 -136
- package/src/hot-memory.js +46 -46
- package/src/index.js +515 -513
- package/src/inject.js +299 -253
- package/src/lang.js +202 -179
- package/src/local-embedder.js +320 -308
- package/src/mirror.js +198 -198
- package/src/quality-filter.js +126 -126
- package/src/recall-stats.js +103 -0
- package/src/reranker.js +269 -260
- package/src/runtime/adopt.js +176 -176
- package/src/runtime/closure.js +172 -172
- package/src/runtime/download.js +247 -247
- package/src/runtime/layout.js +235 -235
- package/src/runtime/loader.js +249 -249
- package/src/runtime/model-fetch.js +361 -0
- package/src/runtime/provision.js +237 -237
- package/src/runtime/tarball.js +130 -130
- package/src/runtime/verify.js +191 -191
- package/src/scope.js +118 -118
- package/src/search/adaptive.js +22 -22
- package/src/search/bm25.js +96 -96
- package/src/service.js +2171 -2071
- package/src/settings.js +430 -419
- package/src/store.js +2448 -2367
- package/src/summarize.js +575 -449
- package/src/tools.js +574 -574
- package/src/vector-index.js +110 -110
- package/src/version-check.js +122 -122
- package/test/api-routes-gaps.test.js +218 -218
- package/test/api.test.js +1578 -1481
- package/test/audit.test.js +448 -448
- package/test/benchmark.test.js +94 -94
- package/test/bootstrap.test.js +220 -0
- package/test/client.test.js +799 -736
- package/test/clustering.test.js +100 -100
- package/test/commands.test.js +106 -106
- package/test/config.test.js +66 -66
- package/test/conflict-freeze.test.js +300 -300
- package/test/dream-archive-guardrail.test.js +116 -116
- package/test/dream-candidate-hybrid.test.js +281 -281
- package/test/dream-coverage-degrade.test.js +86 -86
- package/test/dream.test.js +1257 -1254
- package/test/embedding-ready.test.js +196 -196
- package/test/entities.test.js +547 -547
- package/test/entity-recall.test.js +179 -0
- package/test/epistemic.test.js +298 -298
- package/test/fnew-0112.test.js +311 -311
- package/test/fnew-03.test.js +422 -422
- package/test/graph-api.test.js +175 -175
- package/test/heat.test.js +175 -148
- package/test/helpers/dream-mock.js +82 -82
- package/test/helpers/peer-worker.mjs +25 -25
- package/test/helpers/runtime-source.js +60 -60
- package/test/helpers/tar-builder.js +80 -80
- package/test/hot-memory.test.js +145 -145
- package/test/inject-content-cap.test.js +89 -0
- package/test/inject-first-round-bm25.test.js +89 -89
- package/test/inject-heat.test.js +61 -0
- package/test/inject-rotation.test.js +161 -0
- package/test/inject.test.js +249 -249
- package/test/lang.test.js +87 -87
- package/test/lib-smoke.test.js +96 -96
- package/test/llm-audit.test.js +309 -309
- package/test/llm-message-source.test.js +177 -177
- package/test/local-embedder.test.js +249 -229
- package/test/mcp-stdio.test.js +385 -0
- package/test/mirror-dirty.test.js +424 -424
- package/test/mirror-edit-digest.test.js +187 -187
- package/test/mirror-generation.test.js +499 -499
- package/test/mirror.test.js +249 -249
- package/test/narrative-bars.test.js +162 -0
- package/test/peer-blockers.test.js +193 -193
- package/test/policy-epoch.test.js +259 -259
- package/test/quality-filter.test.js +186 -186
- package/test/reasoning-effort.test.js +746 -746
- package/test/recall-evals.test.js +235 -235
- package/test/recall-layer.test.js +326 -326
- package/test/recall-stats.test.js +117 -0
- package/test/receipt-chain.test.js +451 -451
- package/test/reflection.test.js +226 -226
- package/test/reindex-backfill.test.js +62 -62
- package/test/reranker-single-logit.test.js +73 -73
- package/test/reranker.test.js +197 -197
- package/test/resident-status.test.js +83 -0
- package/test/runtime-adopt.test.js +206 -206
- package/test/runtime-cli.test.js +89 -89
- package/test/runtime-closure.test.js +193 -193
- package/test/runtime-download.test.js +302 -302
- package/test/runtime-layout.test.js +163 -163
- package/test/runtime-loader.test.js +237 -237
- package/test/runtime-manifest.test.js +158 -158
- package/test/runtime-model-fetch.test.js +348 -0
- package/test/runtime-provision.test.js +101 -101
- package/test/runtime-tarball.test.js +81 -81
- package/test/runtime-verify.test.js +214 -214
- package/test/scope-candidates.test.js +239 -239
- package/test/scope-explicit.test.js +452 -452
- package/test/scope-retrieval.test.js +197 -197
- package/test/scope-storage.test.js +255 -255
- package/test/scope-strict.test.js +231 -231
- package/test/search-fusion.test.js +90 -90
- package/test/semantic.test.js +124 -124
- package/test/service-search.test.js +174 -174
- package/test/service.test.js +405 -405
- package/test/settings.test.js +261 -261
- package/test/skip-invalid-restore.test.js +262 -262
- package/test/sleep-action-set.test.js +422 -422
- package/test/sleep-heat.test.js +126 -125
- package/test/sleep-scheduler-rearm.test.js +89 -89
- package/test/sleep.test.js +373 -373
- package/test/standalone-api.test.js +544 -359
- package/test/store-vector-cache.test.js +98 -98
- package/test/store.test.js +383 -383
- package/test/stress.test.js +209 -209
- package/test/summarize.test.js +884 -575
- package/test/tools-memory-get-schema.test.js +65 -65
- package/test/tools.test.js +341 -341
- package/test/updated-at-semantics.test.js +113 -113
- package/test/vector-index.test.js +221 -221
- package/test/version-check.test.js +152 -152
- package/test/webServer-optional.test.js +82 -82
package/src/dream.js
CHANGED
|
@@ -1,1216 +1,1319 @@
|
|
|
1
|
-
import { validateDecisions, applyDecisions } from "./dream/decisions.js";
|
|
2
|
-
import { clusterMemories, findPotentialConflicts, cosineSimilarity } from "./dream/clustering.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
cleaned =
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
.
|
|
60
|
-
.
|
|
61
|
-
.join("\
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* the
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
byId[d.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
//
|
|
116
|
-
|
|
117
|
-
byId[d.
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
* digest
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
.
|
|
136
|
-
.
|
|
137
|
-
.join("
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
//
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
//
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (chunk.type === "
|
|
235
|
-
if (chunk.type === "
|
|
236
|
-
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
// chunk
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
return code
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
let
|
|
274
|
-
let
|
|
275
|
-
let
|
|
276
|
-
let
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
const
|
|
282
|
-
|
|
283
|
-
if (Number.isFinite(
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
//
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
//
|
|
296
|
-
//
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
*
|
|
337
|
-
*
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
//
|
|
346
|
-
//
|
|
347
|
-
//
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
// "
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
* (
|
|
382
|
-
*
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
const
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
//
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
*
|
|
460
|
-
*
|
|
461
|
-
*
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
if (
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
return
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
logger?.warn?.(
|
|
925
|
-
return finish({ ok: false, error: "llm
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
//
|
|
1074
|
-
//
|
|
1075
|
-
//
|
|
1076
|
-
//
|
|
1077
|
-
//
|
|
1078
|
-
//
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
//
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
//
|
|
1180
|
-
//
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
//
|
|
1185
|
-
|
|
1186
|
-
//
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
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
|
+
}
|