@modusensus/dsh-mneme 0.8.3 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +718 -636
- 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 -4366
- package/lib/commands.js +95 -95
- package/lib/config.js +533 -510
- 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 -515
- package/lib/inject.js +299 -295
- package/lib/lang.js +202 -179
- package/lib/local-embedder.js +320 -320
- 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 -269
- 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 -361
- 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 -2087
- package/lib/settings.js +430 -420
- 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 -510
- 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 -515
- package/src/inject.js +299 -295
- package/src/lang.js +202 -179
- package/src/local-embedder.js +320 -320
- 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 -269
- 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 -361
- 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 -2087
- package/src/settings.js +430 -420
- 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 -1482
- 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 -161
- 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 -249
- 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 -348
- 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/service.js
CHANGED
|
@@ -1,2087 +1,2171 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { TYPE_FILE } from "./mirror.js";
|
|
3
|
-
import { updatedAtBounds } from "./store.js";
|
|
4
|
-
import { normalizeExplicitScope, scopeKeyOf } from "./scope.js";
|
|
5
|
-
import { STR, langOf } from "./lang.js";
|
|
6
|
-
import { computeHeat } from "./heat.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
//
|
|
16
|
-
//
|
|
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
|
-
// scope
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
&&
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
&&
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (
|
|
80
|
-
if (bounds.
|
|
81
|
-
return
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
* (
|
|
87
|
-
* agent
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
//
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
//
|
|
172
|
-
//
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
let
|
|
178
|
-
let
|
|
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
|
-
let
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
if (
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
.
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
embedReadyTimer
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
if (
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
embedPending.
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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
|
-
if (
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
*
|
|
323
|
-
*
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
* @param {
|
|
348
|
-
* @param {
|
|
349
|
-
* @
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
356
|
-
const
|
|
357
|
-
const
|
|
358
|
-
const
|
|
359
|
-
|
|
360
|
-
for (const mem of
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
* @param {string
|
|
373
|
-
* @param {
|
|
374
|
-
* @param {
|
|
375
|
-
* @
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
//
|
|
381
|
-
//
|
|
382
|
-
|
|
383
|
-
const
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
394
|
-
*
|
|
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
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
*
|
|
434
|
-
*
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
925
|
-
|
|
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
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
return memory;
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
const merged =
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
}
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
);
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
const
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
}
|
|
1735
|
-
|
|
1736
|
-
//
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
//
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
},
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
//
|
|
2026
|
-
//
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
//
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { TYPE_FILE } from "./mirror.js";
|
|
3
|
+
import { updatedAtBounds } from "./store.js";
|
|
4
|
+
import { normalizeExplicitScope, scopeKeyOf } from "./scope.js";
|
|
5
|
+
import { STR, langOf } from "./lang.js";
|
|
6
|
+
import { computeHeat } from "./heat.js";
|
|
7
|
+
import { recallStats } from "./recall-stats.js";
|
|
8
|
+
import { evaluateMemoryQuality } from "./quality-filter.js";
|
|
9
|
+
import { applyDecisions } from "./dream/decisions.js";
|
|
10
|
+
import { createBM25Index } from "./search/bm25.js";
|
|
11
|
+
import { adaptiveThreshold } from "./search/adaptive.js";
|
|
12
|
+
|
|
13
|
+
const INJECT_TYPES = new Set(["preference", "project", "decision", "summary", "rejected_solution", "pitfall", "constraint"]);
|
|
14
|
+
|
|
15
|
+
// 编码记忆类型(codingRetrospect):rejected_solution / pitfall / constraint
|
|
16
|
+
// 只在编码任务时注入(防噪声污染其他业务),且编码场景下按 codingBoostFactor
|
|
17
|
+
// 加权排序提前。
|
|
18
|
+
const CODING_MEMORY_TYPES = new Set(["rejected_solution", "pitfall", "constraint"]);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 判断一段文本是否编码类任务(关键词匹配,codingRetrospect 读取侧门控)。
|
|
22
|
+
* 纯函数,无副作用,便于单测。
|
|
23
|
+
*/
|
|
24
|
+
export function isCodingTask(text, keywords = []) {
|
|
25
|
+
const t = String(text ?? "").toLowerCase();
|
|
26
|
+
return keywords.some((kw) => t.includes(String(kw).toLowerCase()));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Epistemic trust weights (v0.4.5): when config.trustEpistemicWeighting is on,
|
|
30
|
+
// each recall candidate's existing score is multiplied by the weight of its
|
|
31
|
+
// epistemic_status before ranking — measured facts outrank guesses. Missing /
|
|
32
|
+
// unknown statuses are unscaled (×1). Off by default, so nothing changes.
|
|
33
|
+
const EPISTEMIC_WEIGHTS = { observation: 1.0, inferred: 0.85, subjective: 0.7 };
|
|
34
|
+
|
|
35
|
+
// Bug5: content version history cap (FIFO — the newest 20 versions are kept,
|
|
36
|
+
// older ones dropped). Entries are {content, source, updated_at}; source marks
|
|
37
|
+
// how the version was superseded (auto_merge | human_override | overwrite).
|
|
38
|
+
const CONTENT_HISTORY_MAX = 20;
|
|
39
|
+
|
|
40
|
+
// Issue #135 附属发现 2:质量过滤器写下的系统信号标签(「为什么被降权/归档」的
|
|
41
|
+
// 唯一审计线索)。更新路径整组替换 tags 会把它们抹掉——更新时按此清单并集保留。
|
|
42
|
+
// 清单必须与 quality-filter.js 的写入端对齐(6 个,含 type 自指的 self_referential)。
|
|
43
|
+
const SIGNAL_TAGS = ["low_quality", "duplicate", "meta", "repetitive", "short_content", "self_referential"];
|
|
44
|
+
|
|
45
|
+
// scopeKeyOf 已上提到 ./scope.js(v0.8.1,issue #170 第 2 步):与 sleep 的跨
|
|
46
|
+
// scope 配对共用同一把比较钥匙,避免两处定义漂移。
|
|
47
|
+
|
|
48
|
+
// v0.8.0 A2(issue #17)scope 检索加权系数:两维都无法确立 foreign 的候选
|
|
49
|
+
// (命中行、未标注行、当前侧维度解析不到的行)→ 加成;只有确立了 foreign
|
|
50
|
+
// (记忆带标注 + 当前维度可解析 + 值不等)→ 降权但保留可见(硬过滤是 A3
|
|
51
|
+
// strictScope)。即未标注行与命中行同列、不吃惩罚,但注意它们吃的是 BOOST
|
|
52
|
+
// 而非 ×1 中性。系数是模块常量而非配置项:A2 只定性行为,数值要等线上检索
|
|
53
|
+
// 质量反馈再调(加配置面=提前优化)。
|
|
54
|
+
const SCOPE_MATCH_BOOST = 1.25;
|
|
55
|
+
const SCOPE_FOREIGN_PENALTY = 0.5;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 单条候选的 scope 乘数。匹配语义与去重键一致(scopeKeyOf):记忆侧未标注视同
|
|
59
|
+
* 该维度命中(全局记忆对谁都可见);当前会话侧某维度解析不到则该维度不参与
|
|
60
|
+
* 比较(无法比较 ≠ 不匹配)。
|
|
61
|
+
*/
|
|
62
|
+
function scopeMultiplier(m, current) {
|
|
63
|
+
const agentForeign = scopeKeyOf(m.agent_scope) !== null
|
|
64
|
+
&& current.agent_scope !== null
|
|
65
|
+
&& scopeKeyOf(m.agent_scope) !== current.agent_scope;
|
|
66
|
+
const workspaceForeign = scopeKeyOf(m.workspace_scope) !== null
|
|
67
|
+
&& current.workspace_scope !== null
|
|
68
|
+
&& scopeKeyOf(m.workspace_scope) !== current.workspace_scope;
|
|
69
|
+
return (agentForeign || workspaceForeign) ? SCOPE_FOREIGN_PENALTY : SCOPE_MATCH_BOOST;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* v0.8.0 A2:occurred_at 后置过滤谓词(搜索融合池用)。行侧取
|
|
74
|
+
* COALESCE(occurred_at, created_at)——与 store.list 的 SQL 过滤同口径,未标注
|
|
75
|
+
* 行回退创建时间;时间戳损坏的行保留(宁可放宽也不误杀,同 summarize inWindow)。
|
|
76
|
+
*/
|
|
77
|
+
function inOccurredBounds(m, bounds) {
|
|
78
|
+
const t = Date.parse(String(m.occurred_at ?? m.created_at ?? ""));
|
|
79
|
+
if (!Number.isFinite(t)) return true;
|
|
80
|
+
if (bounds.from && t < Date.parse(bounds.from)) return false;
|
|
81
|
+
if (bounds.to && t > Date.parse(bounds.to)) return false;
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* v0.8.0 A3(issue #17)strictScope 可见性谓词:issue 的四象限可见性公式
|
|
87
|
+
* (agent 不对称可见性)——记忆对当前会话可见 ⇔ (agent 维:未标注 或 命中当前
|
|
88
|
+
* agent) AND (workspace 维:未标注 或 命中当前 workspace)。NULL=未标注=全局;
|
|
89
|
+
* 当前会话某维度解析不到时,该维度带标注的记忆一律不可见(fail-closed:身份
|
|
90
|
+
* 不明的会话只见全局,不冒认)。sensitivity 是标签不参与可见性判定(其语义
|
|
91
|
+
* 留给后续批次)。store.list 的 SQL 过滤与此谓词同口径(见 store.js visibility)。
|
|
92
|
+
*/
|
|
93
|
+
function isVisibleInScope(m, current) {
|
|
94
|
+
// v0.8.1 第 3 步(issue #170 4.3,作者已确认):硬过滤只认显式声明。某维
|
|
95
|
+
// 仅当「该维有标注且来源为 explicit」才构成硬墙;auto(含 v0.8.0 存量的
|
|
96
|
+
// NULL 来源行)只吃 A2 软加权(foreign ×0.5 保留可见),不进硬过滤。
|
|
97
|
+
// 显式全局(值 NULL + source explicit)与未标注同形,天然恒可见。
|
|
98
|
+
if (m.agent_scope_source === "explicit") {
|
|
99
|
+
const agent = scopeKeyOf(m.agent_scope);
|
|
100
|
+
if (agent !== null && (current.agent_scope === null || agent !== current.agent_scope)) return false;
|
|
101
|
+
}
|
|
102
|
+
if (m.workspace_scope_source === "explicit") {
|
|
103
|
+
const ws = scopeKeyOf(m.workspace_scope);
|
|
104
|
+
if (ws !== null && (current.workspace_scope === null || ws !== current.workspace_scope)) return false;
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Prepend the previous content to a memory's content_history (FIFO capped). */
|
|
110
|
+
function pushContentHistory(existing, source) {
|
|
111
|
+
const history = Array.isArray(existing?.content_history) ? existing.content_history : [];
|
|
112
|
+
return [
|
|
113
|
+
{ content: existing?.content ?? "", source, updated_at: new Date().toISOString() },
|
|
114
|
+
...history
|
|
115
|
+
].slice(0, CONTENT_HISTORY_MAX);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Bug5: same-title merge appends the new content under a timestamped `---`
|
|
119
|
+
* separator instead of overwriting, so a re-noted memory never loses history.
|
|
120
|
+
* The `---` line is compatible with the mirror's readHumanEdits (which strips
|
|
121
|
+
* only the LAST structural `---` when parsing the human-editable file). */
|
|
122
|
+
function appendContent(oldContent, newContent) {
|
|
123
|
+
const ts = new Date().toISOString();
|
|
124
|
+
return `${oldContent}\n\n---\n[${ts}] ${newContent}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Standard retrieval-quality metrics over the ordered candidate ids actually
|
|
129
|
+
* returned vs the ids the evaluator marked relevant (方案 B). Pure + total, so
|
|
130
|
+
* callers (and tests) get deterministic numbers without touching a store:
|
|
131
|
+
* precision = |relevant ∩ retrieved| / |retrieved|
|
|
132
|
+
* recall = |relevant ∩ retrieved| / |expected|
|
|
133
|
+
* mrr = 1 / rank of the first relevant doc (0 when none retrieved)
|
|
134
|
+
* hit_count is the raw intersection size. Values are rounded to 4 decimals so
|
|
135
|
+
* repeated divisions (e.g. 1/3) never surface binary-float noise.
|
|
136
|
+
*/
|
|
137
|
+
export function computeRetrievalMetrics(actualIds, expectedIds) {
|
|
138
|
+
const expected = new Set(Array.isArray(expectedIds) ? expectedIds : []);
|
|
139
|
+
const actual = Array.isArray(actualIds) ? actualIds : [];
|
|
140
|
+
const relevant = actual.filter((id) => expected.has(id)).length;
|
|
141
|
+
const round4 = (x) => Math.round(x * 10000) / 10000;
|
|
142
|
+
let mrr = 0;
|
|
143
|
+
for (let i = 0; i < actual.length; i++) {
|
|
144
|
+
if (expected.has(actual[i])) { mrr = 1 / (i + 1); break; }
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
precision: round4(actual.length ? relevant / actual.length : 0),
|
|
148
|
+
recall: round4(expected.size ? relevant / expected.size : 0),
|
|
149
|
+
mrr: round4(mrr),
|
|
150
|
+
hit_count: relevant
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function createService({ store, mirror, config, onWrite, logger }) {
|
|
155
|
+
const language = langOf(config);
|
|
156
|
+
// Optional dream scheduler hook, installed via setDreamHook after creation
|
|
157
|
+
// (the scheduler holds a reference back to the service, so it cannot be
|
|
158
|
+
// passed in the constructor). Fired on the same write events as onWrite.
|
|
159
|
+
let dreamHook = null;
|
|
160
|
+
|
|
161
|
+
// Optional sleep scheduler hook (v0.4.0), installed via setSleepHook after
|
|
162
|
+
// creation. Fired on the same write events as onWrite: it tells the sleep
|
|
163
|
+
// scheduler the store just changed so the idle-detection clock resets.
|
|
164
|
+
let sleepHook = null;
|
|
165
|
+
|
|
166
|
+
// Optional vector embedder, installed via setEmbedder after creation. After
|
|
167
|
+
// any content write it fire-and-forgets a re-embed of the row so vector
|
|
168
|
+
// search stays in sync; failures are swallowed inside the embedder.
|
|
169
|
+
let embedder = null;
|
|
170
|
+
|
|
171
|
+
// Optional entity extractor, installed via setEntityExtractor after creation
|
|
172
|
+
// (index.js injects it so the service never depends on the LLM directly).
|
|
173
|
+
// After a new memory is saved it fire-and-forgets an extraction pass for the
|
|
174
|
+
// entity gene (v0.3.0); failures are swallowed so a broken extraction never
|
|
175
|
+
// surfaces as a write failure. Extraction only runs when
|
|
176
|
+
// config.entityExtractionEnabled is true.
|
|
177
|
+
let entityExtractor = null;
|
|
178
|
+
let vectorIndex = null;
|
|
179
|
+
let reranker = null;
|
|
180
|
+
|
|
181
|
+
// Optional recall recorder, installed via setRecallRecorder after creation.
|
|
182
|
+
// When searchMemories is called with recordRecall=true it receives the
|
|
183
|
+
// actual merged recall scene (candidates + scores + source + threshold) so
|
|
184
|
+
// the retrieval layer can be audited/replayed — the sibling of the dream
|
|
185
|
+
// judgment-layer audit trail (dream_runs).
|
|
186
|
+
let recallRecorder = null;
|
|
187
|
+
|
|
188
|
+
// Bug4: semantic recall cache for the injection path. The system-prompt
|
|
189
|
+
// interpolator renders context synchronously, so injectCandidates cannot
|
|
190
|
+
// fire a fresh async embed. The most recent searchMemories recall is cached
|
|
191
|
+
// here (query + ordered candidates) and reused when the injection query
|
|
192
|
+
// matches, giving semantic-first injection without breaking the sync render.
|
|
193
|
+
let lastSemanticRecall = null;
|
|
194
|
+
|
|
195
|
+
// Transaction nesting depth. Inside service.transaction the per-mutation side
|
|
196
|
+
// effects (mirror render, write notify, re-embed) are deferred so a ROLLBACK
|
|
197
|
+
// never leaves the mirror file diverged from the database; transaction()
|
|
198
|
+
// replays them exactly once against the committed state.
|
|
199
|
+
let txDepth = 0;
|
|
200
|
+
|
|
201
|
+
// Serial task queue (sleep v0.4.0). Long-running background passes — dream
|
|
202
|
+
// consolidation, sleep cycles — must never overlap: two sleep runs racing
|
|
203
|
+
// would double-demote or double-mint patterns. enqueue chains the task onto
|
|
204
|
+
// a promise tail so N callers can queue work that runs strictly one at a
|
|
205
|
+
// time. A task that rejects doesn't poison the queue (the tail swallows the
|
|
206
|
+
// rejection) but the rejection still propagates to that caller.
|
|
207
|
+
let queueTail = Promise.resolve();
|
|
208
|
+
function enqueue(fn) {
|
|
209
|
+
const next = queueTail.then(fn, fn);
|
|
210
|
+
queueTail = next.catch(() => {});
|
|
211
|
+
return next;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// issue #6 (part 2): startup race defense. A local embedder (LocalEmbedder /
|
|
215
|
+
// Ollama) exposes an async init(), so between `setEmbedder` and init()
|
|
216
|
+
// resolving there is a window where embedSingle would throw "not initialized"
|
|
217
|
+
// and the re-embed would be silently dropped. When the embedder carries a
|
|
218
|
+
// `ready` flag we queue writes in embedPending until init sets ready=true,
|
|
219
|
+
// then flush them through the embedder's real interface. Embedders without a
|
|
220
|
+
// `ready` flag (legacy OpenAI, instantly usable) keep their old behavior.
|
|
221
|
+
let embedPending = [];
|
|
222
|
+
let embedReadyTimer = null;
|
|
223
|
+
const EMBED_PENDING_MAX = 100; // bound the queue; drop oldest beyond this
|
|
224
|
+
const EMBED_READY_POLL_MS = 100;
|
|
225
|
+
const EMBED_READY_POLL_LIMIT = 30; // ~3s ceiling; never poll forever
|
|
226
|
+
|
|
227
|
+
/** Flush the queued re-embeds once the embedder is ready. Fail-safe. */
|
|
228
|
+
function flushEmbedPending() {
|
|
229
|
+
if (!embedder || embedPending.length === 0) return;
|
|
230
|
+
const batch = embedPending.splice(0, embedPending.length);
|
|
231
|
+
for (const memory of batch) {
|
|
232
|
+
try {
|
|
233
|
+
if (!memory?.id) continue;
|
|
234
|
+
if (typeof embedder.schedule === "function") {
|
|
235
|
+
embedder.schedule(memory);
|
|
236
|
+
} else if (typeof embedder.embedSingle === "function") {
|
|
237
|
+
const text = [memory.title, memory.content].filter(Boolean).join("\n");
|
|
238
|
+
if (!text) continue;
|
|
239
|
+
embedder
|
|
240
|
+
.embedSingle(text)
|
|
241
|
+
.then((vec) => {
|
|
242
|
+
if (Array.isArray(vec) && vec.length) {
|
|
243
|
+
store.setEmbedding(memory.id, vec);
|
|
244
|
+
}
|
|
245
|
+
})
|
|
246
|
+
.catch((err) => {
|
|
247
|
+
logger?.warn?.("flushEmbedPending embedSingle failed:", err);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
} catch (err) {
|
|
251
|
+
logger?.warn?.("flushEmbedPending failed:", err);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function stopEmbedReadyPolling() {
|
|
257
|
+
if (embedReadyTimer) {
|
|
258
|
+
clearInterval(embedReadyTimer);
|
|
259
|
+
embedReadyTimer = null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function scheduleEmbed(memory) {
|
|
264
|
+
try {
|
|
265
|
+
if (txDepth > 0) return; // deferred to the transaction's commit
|
|
266
|
+
if (!embedder || !memory?.id) return;
|
|
267
|
+
|
|
268
|
+
// Readiness gate: embedder exposes `ready` (async init) and is not ready
|
|
269
|
+
// yet — queue instead of firing embedSingle into a half-built extractor.
|
|
270
|
+
const hasReady = "ready" in embedder;
|
|
271
|
+
if (hasReady && embedder.ready !== true) {
|
|
272
|
+
if (embedPending.length >= EMBED_PENDING_MAX) embedPending.shift();
|
|
273
|
+
embedPending.push(memory);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (typeof embedder.schedule === "function") {
|
|
278
|
+
embedder.schedule(memory);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (typeof embedder.embedSingle === "function") {
|
|
283
|
+
const text = [memory.title, memory.content].filter(Boolean).join("\n");
|
|
284
|
+
if (!text) return;
|
|
285
|
+
|
|
286
|
+
embedder
|
|
287
|
+
.embedSingle(text)
|
|
288
|
+
.then((vec) => {
|
|
289
|
+
if (Array.isArray(vec) && vec.length) {
|
|
290
|
+
store.setEmbedding(memory.id, vec);
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
.catch((err) => {
|
|
294
|
+
logger?.warn?.("scheduleEmbed embedSingle failed:", err);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
} catch (err) {
|
|
298
|
+
logger?.warn?.("scheduleEmbed failed:", err);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Fire-and-forget entity extraction for a freshly saved memory (entity gene
|
|
304
|
+
* v0.3.0). Opt-in via config.entityExtractionEnabled; the extractor is
|
|
305
|
+
* injected as a hook so the service never needs a direct LLM reference.
|
|
306
|
+
* The hook itself is expected to resolve to { ok:boolean } and never throw;
|
|
307
|
+
* a thrown rejection is swallowed here as a final fail-safe.
|
|
308
|
+
*/
|
|
309
|
+
function scheduleEntityExtraction(memory) {
|
|
310
|
+
if (txDepth > 0) return; // deferred to the transaction's commit
|
|
311
|
+
if (!config.entityExtractionEnabled || !entityExtractor) return;
|
|
312
|
+
try {
|
|
313
|
+
entityExtractor(memory).catch((err) => {
|
|
314
|
+
logger?.warn?.("entity extraction failed:", err);
|
|
315
|
+
});
|
|
316
|
+
} catch (err) {
|
|
317
|
+
logger?.warn?.("entity extraction failed:", err);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Cross-encoder rerank over a candidate list (best effort). Reranker
|
|
323
|
+
* failures degrade to the original candidate order — reranking is an
|
|
324
|
+
* accuracy upgrade, never a correctness gate.
|
|
325
|
+
*/
|
|
326
|
+
async function rerankCandidates(query, candidates, topK) {
|
|
327
|
+
if (!reranker || !candidates.length) return candidates.slice(0, topK);
|
|
328
|
+
try {
|
|
329
|
+
const scored = await reranker.rerank(query, candidates.map((c) => ({ id: c.id, title: c.title, content: c.content })));
|
|
330
|
+
if (!Array.isArray(scored)) return candidates.slice(0, topK);
|
|
331
|
+
const byId = new Map(candidates.map((c) => [c.id, c]));
|
|
332
|
+
const out = [];
|
|
333
|
+
for (const s of scored) {
|
|
334
|
+
const c = byId.get(s.id);
|
|
335
|
+
if (c) { out.push({ ...c, score: s.score, source: "rerank" }); if (out.length >= topK) break; }
|
|
336
|
+
}
|
|
337
|
+
return out.length ? out : candidates.slice(0, topK);
|
|
338
|
+
} catch {
|
|
339
|
+
return candidates.slice(0, topK);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Search for memories attached to a named entity (v0.3.0 Phase 3).
|
|
345
|
+
* 合并优先级:entity_attrs.memory_id 精确关联 = 1.0 > 关键词提及 = 0.7;
|
|
346
|
+
* attr 命中不覆盖,keyword 只补充召回,最后按 _score 降序取 topK。
|
|
347
|
+
* @param {string} entityName
|
|
348
|
+
* @param {object} [options]
|
|
349
|
+
* @param {number} [options.topK=20]
|
|
350
|
+
* @returns {any[]}
|
|
351
|
+
*/
|
|
352
|
+
function searchByEntity(entityName, { topK = 20 } = {}) {
|
|
353
|
+
const entity = store.findEntityByName(entityName);
|
|
354
|
+
if (!entity) return [];
|
|
355
|
+
const attrs = store.getCurrentAttrs(entity.id);
|
|
356
|
+
const memoryIds = [...new Set(attrs.map((a) => a.memory_id).filter(Boolean))];
|
|
357
|
+
const attrHits = memoryIds.map((id) => store.getById(id)).filter(Boolean);
|
|
358
|
+
const keywordHits = store.search(entityName, { limit: topK });
|
|
359
|
+
const merged = new Map();
|
|
360
|
+
for (const mem of attrHits) merged.set(mem.id, { ...mem, _source: "entity_attr", _score: 1.0 });
|
|
361
|
+
for (const mem of keywordHits) {
|
|
362
|
+
if (!merged.has(mem.id)) merged.set(mem.id, { ...mem, _source: "keyword", _score: 0.7 });
|
|
363
|
+
}
|
|
364
|
+
const hits = Array.from(merged.values()).sort((a, b) => b._score - a._score).slice(0, topK);
|
|
365
|
+
touchRecalled(hits);
|
|
366
|
+
return hits;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Search for memories by attribute key/value (v0.3.0 Phase 3).
|
|
371
|
+
* value 为空时由 store.findMemoriesByAttr 返回该 key 的全部有效记忆。
|
|
372
|
+
* @param {string} key
|
|
373
|
+
* @param {string | undefined} value
|
|
374
|
+
* @param {object} [options]
|
|
375
|
+
* @param {number} [options.topK=20]
|
|
376
|
+
* @returns {any[]}
|
|
377
|
+
*/
|
|
378
|
+
function searchByAttr(key, value, { topK = 20 } = {}) {
|
|
379
|
+
if (!key) return [];
|
|
380
|
+
// value 可能为 undefined(attr:key 无 = 值):归一为空串后交给
|
|
381
|
+
// store.findMemoriesByAttr —— 空 value 契约 = 返回该 attr_key 的全部
|
|
382
|
+
// 当前有效记忆(v0.3.0,store.js 已实现)。
|
|
383
|
+
const rows = store.findMemoriesByAttr(key, value ?? "");
|
|
384
|
+
const hits = rows.slice(0, topK);
|
|
385
|
+
touchRecalled(hits);
|
|
386
|
+
return hits;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Semantic-aware memory search: keyword recall (store.search) plus optional
|
|
391
|
+
* vector recall + rerank. mode:
|
|
392
|
+
* auto (default) keyword first, vector fills remaining slots (legacy)
|
|
393
|
+
* hybrid vector first, keyword fills remaining slots
|
|
394
|
+
* vector vector only, falls back to keyword when unavailable
|
|
395
|
+
* keyword text only, never touches the embedder
|
|
396
|
+
* useRerank runs the cross-encoder over the merged list when a reranker is
|
|
397
|
+
* installed; results carry an extra `score` when reranked.
|
|
398
|
+
*/
|
|
399
|
+
// Weighted blend factor for hybrid search; exposed so callers can tune it.
|
|
400
|
+
const DEFAULT_HYBRID_WEIGHTS = { vector: 0.6, keyword: 0.4 };
|
|
401
|
+
|
|
402
|
+
// Cosine over two plain arrays (shared by the search-time semantic dedup).
|
|
403
|
+
function cosineVec(a, b) {
|
|
404
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
|
|
405
|
+
let dot = 0, na = 0, nb = 0;
|
|
406
|
+
for (let i = 0; i < a.length; i++) {
|
|
407
|
+
dot += a[i] * b[i];
|
|
408
|
+
na += a[i] * a[i];
|
|
409
|
+
nb += b[i] * b[i];
|
|
410
|
+
}
|
|
411
|
+
if (na === 0 || nb === 0) return 0;
|
|
412
|
+
return dot / (Math.sqrt(na) * Math.sqrt(nb));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* BM25 third recall path (v0.5.0 1.1). Scores the query tokens against the
|
|
417
|
+
* live non-archived rows and returns the top `limit` hits with scores
|
|
418
|
+
* normalized to [0,1]. Failures degrade to [] — BM25 is a recall booster,
|
|
419
|
+
* never a correctness gate.
|
|
420
|
+
*/
|
|
421
|
+
function bm25Recall(q, limit) {
|
|
422
|
+
if (config?.bm25SearchEnabled === false) return [];
|
|
423
|
+
try {
|
|
424
|
+
const docs = store.list({ limit: 500, includeForgotten: false }).filter((m) => !m.archived);
|
|
425
|
+
if (!docs.length) return [];
|
|
426
|
+
return createBM25Index(docs).search(q, { limit });
|
|
427
|
+
} catch {
|
|
428
|
+
return [];
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Graph fourth recall path (issue #219). When the query text mentions a
|
|
434
|
+
* known entity name, memories linked to that entity (attrs + relations)
|
|
435
|
+
* join the fusion pool as a confirm/backfill signal — same standing as
|
|
436
|
+
* BM25, never dominating the semantic ranking. Tier scores: attr-linked
|
|
437
|
+
* 1.0 (direct evidence, same source searchByEntity trusts) > relation
|
|
438
|
+
* edge 0.9. Archived/forgotten rows never participate. Failures degrade
|
|
439
|
+
* to [] — a recall booster, never a correctness gate (same contract as
|
|
440
|
+
* bm25Recall).
|
|
441
|
+
*/
|
|
442
|
+
function entityRecall(q, limit) {
|
|
443
|
+
if (config?.entityRecallEnabled !== true) return [];
|
|
444
|
+
try {
|
|
445
|
+
const entities = store.findEntitiesMentionedIn(q);
|
|
446
|
+
if (!entities.length) return [];
|
|
447
|
+
const linked = store.getLinkedMemoryIds(entities.map((e) => e.id));
|
|
448
|
+
if (!linked.size) return [];
|
|
449
|
+
const hits = [];
|
|
450
|
+
for (const [id, tier] of linked) {
|
|
451
|
+
const row = store.getById(id);
|
|
452
|
+
if (!row || row.archived || row.forgotten) continue;
|
|
453
|
+
hits.push({ ...row, score: tier === "attr" ? 1.0 : 0.9, source: "entity" });
|
|
454
|
+
if (hits.length >= limit * 2) break;
|
|
455
|
+
}
|
|
456
|
+
return hits;
|
|
457
|
+
} catch {
|
|
458
|
+
return [];
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Search-time semantic dedup (v0.5.0 2.3): greedy pass dropping candidates
|
|
464
|
+
* whose embedding similarity to an already-kept row exceeds the threshold.
|
|
465
|
+
* Rows without a stored embedding are always kept (no signal = no drop).
|
|
466
|
+
*/
|
|
467
|
+
function semanticDeduplicate(candidates) {
|
|
468
|
+
// Opt-in aggressive mode (default off): collapsing near-duplicates can
|
|
469
|
+
// drop legitimately distinct rows on small embedding models, so it ships
|
|
470
|
+
// behind searchSemanticDedup=true.
|
|
471
|
+
if (config?.searchSemanticDedup !== true || candidates.length < 2) return candidates;
|
|
472
|
+
const threshold = config?.searchSemanticDedupThreshold ?? 0.95;
|
|
473
|
+
try {
|
|
474
|
+
const vecs = store.getEmbeddings(candidates.map((c) => c.id));
|
|
475
|
+
if (vecs.size < 2) return candidates;
|
|
476
|
+
const kept = [];
|
|
477
|
+
for (const c of candidates) {
|
|
478
|
+
const v = vecs.get(c.id);
|
|
479
|
+
if (!v) { kept.push(c); continue; }
|
|
480
|
+
const dup = kept.some((k) => {
|
|
481
|
+
const kv = vecs.get(k.id);
|
|
482
|
+
return kv && cosineVec(v, kv) > threshold;
|
|
483
|
+
});
|
|
484
|
+
if (!dup) kept.push(c);
|
|
485
|
+
}
|
|
486
|
+
return kept;
|
|
487
|
+
} catch {
|
|
488
|
+
return candidates;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Give a keyword-hit row a relevance score in [0,1]: title hits score
|
|
494
|
+
* higher than content hits, then scaled by importance (1-5). This lets
|
|
495
|
+
* keyword results participate in weighted hybrid blends.
|
|
496
|
+
*/
|
|
497
|
+
function scoreKeyword(row, q) {
|
|
498
|
+
const ql = q.toLowerCase();
|
|
499
|
+
const title = (row.title ?? "").toLowerCase();
|
|
500
|
+
const content = (row.content ?? "").toLowerCase();
|
|
501
|
+
const titleHit = title.includes(ql);
|
|
502
|
+
const base = titleHit ? 1 : content.includes(ql) ? 0.6 : 0.3;
|
|
503
|
+
return base * (0.5 + (row.importance ?? 3) / 10);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Recall touch (v0.4.0 sleep; v0.7.0 heat gating): any memory surfaced by
|
|
508
|
+
* recall or auto-injection gets its last_accessed_at bumped, so the "unrecalled
|
|
509
|
+
* N days → demote/archive" tiering counts real access — and the heat clock
|
|
510
|
+
* resets (heat ref = last_accessed_at). Best-effort and gated on
|
|
511
|
+
* config.heatEnabled — when heat is off this is a complete no-op (no writes
|
|
512
|
+
* on the hot recall path). A touch failure must never break search/inject.
|
|
513
|
+
*/
|
|
514
|
+
function touchRecalled(memories) {
|
|
515
|
+
if (config?.heatEnabled === false || !Array.isArray(memories) || memories.length === 0) return;
|
|
516
|
+
for (const m of memories) {
|
|
517
|
+
if (!m?.id) continue;
|
|
518
|
+
try {
|
|
519
|
+
store.touchLastAccess(m.id);
|
|
520
|
+
} catch { /* touch is best effort */ }
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Recall fusion (plan #1). Turns the three ranked signal lists (keyword,
|
|
526
|
+
* vector, BM25) into a single merged list. Three recipes, selected by
|
|
527
|
+
* config.recallFusion:
|
|
528
|
+
* - blend (default): legacy behavior — weighted sum for vector/hybrid, union
|
|
529
|
+
* backfill for auto. Byte-identical to pre-fusion code, so enabling the
|
|
530
|
+
* config never regresses anybody.
|
|
531
|
+
* - rrf: Reciprocal Rank Fusion — Σ 1/(k + rank + 1) over each list a row
|
|
532
|
+
* appears in. Rank-based, so the unit mismatch (raw cosine vs keyword
|
|
533
|
+
* score vs normalized IDF) is irrelevant.
|
|
534
|
+
* - minmax: min-max normalize each source list's scores to [0,1] then take
|
|
535
|
+
* the weighted sum — a scale-aware version of `blend`.
|
|
536
|
+
* Returns { merged, signals }, where signals is Map<id, {keyword, vector,
|
|
537
|
+
* bm25}> so searchMemories can decorate rows when signalTransparency is on.
|
|
538
|
+
*/
|
|
539
|
+
function fuseRecall({ keyword, vector, bm25, entity, lim, mode, wv, wk, wb, we }) {
|
|
540
|
+
const recipe = config?.recallFusion ?? "blend";
|
|
541
|
+
|
|
542
|
+
// Per-source scores are recorded for every recipe so signalTransparency
|
|
543
|
+
// works regardless of how the ranking was produced.
|
|
544
|
+
const signals = new Map();
|
|
545
|
+
const addSig = (id, field, sc) => {
|
|
546
|
+
const cur = signals.get(id) ?? {};
|
|
547
|
+
cur[field] = sc;
|
|
548
|
+
signals.set(id, cur);
|
|
549
|
+
};
|
|
550
|
+
for (const m of keyword) addSig(m.id, "keyword", m.score ?? 0);
|
|
551
|
+
for (const m of vector) addSig(m.id, "vector", m.score ?? 0);
|
|
552
|
+
for (const m of bm25) addSig(m.id, "bm25", m.score ?? 0);
|
|
553
|
+
for (const m of entity) addSig(m.id, "entity", m.score ?? 0);
|
|
554
|
+
|
|
555
|
+
const vectorIds = new Set(vector.map((m) => m.id));
|
|
556
|
+
const keywordIds = new Set(keyword.map((m) => m.id));
|
|
557
|
+
|
|
558
|
+
// Mode contract (aligns rrf/minmax with blend): keyword-only searches must
|
|
559
|
+
// stay keyword-only regardless of recipe, so enabling an opt-in recipe can
|
|
560
|
+
// never pull vector/BM25 rows into a mode="keyword" request. This mirrors
|
|
561
|
+
// the blend branch's `mode === "keyword"` short-circuit (byte-for-byte).
|
|
562
|
+
if (mode === "keyword") {
|
|
563
|
+
return { merged: keyword.slice(0, lim), signals };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
let merged;
|
|
567
|
+
if (recipe === "rrf") {
|
|
568
|
+
// Rank-based: only the position of a row inside each surviving source
|
|
569
|
+
// list matters, so no cross-signal scale calibration is needed.
|
|
570
|
+
const k = 60; // standard RRF constant (plan #1 documents k=60)
|
|
571
|
+
const rows = new Map();
|
|
572
|
+
const addList = (list) => list.forEach((m, idx) => {
|
|
573
|
+
const s = 1 / (k + idx + 1);
|
|
574
|
+
const cur = rows.get(m.id);
|
|
575
|
+
if (cur) cur.score += s;
|
|
576
|
+
else rows.set(m.id, { ...m, score: s });
|
|
577
|
+
});
|
|
578
|
+
addList(keyword);
|
|
579
|
+
addList(vector);
|
|
580
|
+
addList(bm25);
|
|
581
|
+
addList(entity);
|
|
582
|
+
merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
|
|
583
|
+
} else if (recipe === "minmax") {
|
|
584
|
+
// Scale-aware weighted sum: each source list is min-max normalized to
|
|
585
|
+
// [0,1] before blending, so raw cosine and keyword score live on the
|
|
586
|
+
// same footing.
|
|
587
|
+
const norm = (list) => {
|
|
588
|
+
if (!list.length) return new Map();
|
|
589
|
+
let min = Infinity, max = -Infinity;
|
|
590
|
+
for (const m of list) { const s = m.score ?? 0; if (s < min) min = s; if (s > max) max = s; }
|
|
591
|
+
const range = max - min;
|
|
592
|
+
const out = new Map();
|
|
593
|
+
for (const m of list) out.set(m.id, range > 0 ? ((m.score ?? 0) - min) / range : 0.5);
|
|
594
|
+
return out;
|
|
595
|
+
};
|
|
596
|
+
const kw = norm(keyword), ve = norm(vector), bm = norm(bm25), en = norm(entity);
|
|
597
|
+
const rows = new Map();
|
|
598
|
+
const seed = (m) => { if (!rows.has(m.id)) rows.set(m.id, { ...m, score: 0 }); };
|
|
599
|
+
for (const m of keyword) seed(m);
|
|
600
|
+
for (const m of vector) seed(m);
|
|
601
|
+
for (const m of bm25) seed(m);
|
|
602
|
+
for (const m of entity) seed(m);
|
|
603
|
+
for (const [id, row] of rows) {
|
|
604
|
+
const k = kw.get(id) ?? 0;
|
|
605
|
+
const v = ve.get(id) ?? 0;
|
|
606
|
+
const b = bm.get(id) ?? 0;
|
|
607
|
+
const e = en.get(id) ?? 0;
|
|
608
|
+
row.score = v * wv + k * wk + b * wb + e * we;
|
|
609
|
+
}
|
|
610
|
+
merged = [...rows.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, lim);
|
|
611
|
+
} else {
|
|
612
|
+
// blend — the pre-existing per-mode behavior, extracted verbatim.
|
|
613
|
+
if (mode === "keyword") {
|
|
614
|
+
merged = keyword;
|
|
615
|
+
} else if (mode === "vector" || mode === "hybrid") {
|
|
616
|
+
const byId = new Map();
|
|
617
|
+
for (const m of vector) {
|
|
618
|
+
const rec = byId.get(m.id);
|
|
619
|
+
byId.set(m.id, rec ? { ...rec, score: Math.max(rec.score ?? 0, m.score ?? 0) } : m);
|
|
620
|
+
}
|
|
621
|
+
for (const m of keyword) {
|
|
622
|
+
const rec = byId.get(m.id);
|
|
623
|
+
if (rec) {
|
|
624
|
+
byId.set(m.id, { ...rec, score: (rec.score ?? 0) * wv + (m.score ?? 0) * wk });
|
|
625
|
+
} else {
|
|
626
|
+
byId.set(m.id, m);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
for (const m of bm25) {
|
|
630
|
+
const rec = byId.get(m.id);
|
|
631
|
+
if (rec) {
|
|
632
|
+
if (keywordIds.has(m.id)) continue;
|
|
633
|
+
byId.set(m.id, { ...rec, score: (rec.score ?? 0) + wb * (m.score ?? 0) });
|
|
634
|
+
} else {
|
|
635
|
+
byId.set(m.id, { ...m, score: wb * (m.score ?? 0) });
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// Entity axis (#219): same confirm/backfill contract as BM25 —
|
|
639
|
+
// seen rows get a weighted bonus, unseen ids backfill at we·score.
|
|
640
|
+
for (const m of entity) {
|
|
641
|
+
const rec = byId.get(m.id);
|
|
642
|
+
if (rec) {
|
|
643
|
+
byId.set(m.id, { ...rec, score: (rec.score ?? 0) + we * (m.score ?? 0) });
|
|
644
|
+
} else {
|
|
645
|
+
byId.set(m.id, { ...m, score: we * (m.score ?? 0) });
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
const ranked = [...byId.values()].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
|
|
649
|
+
merged = ranked.slice(0, lim);
|
|
650
|
+
if (merged.length < lim && !merged.length) {
|
|
651
|
+
merged = keyword.slice(0, lim);
|
|
652
|
+
}
|
|
653
|
+
} else {
|
|
654
|
+
// auto: keyword leads, vector + BM25 + entity fill remaining slots.
|
|
655
|
+
merged = keyword.slice(0, lim);
|
|
656
|
+
const seen = new Set(merged.map((m) => m.id));
|
|
657
|
+
for (const m of vector) {
|
|
658
|
+
if (merged.length >= lim) break;
|
|
659
|
+
if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
|
|
660
|
+
}
|
|
661
|
+
for (const m of bm25) {
|
|
662
|
+
if (merged.length >= lim) break;
|
|
663
|
+
if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
|
|
664
|
+
}
|
|
665
|
+
for (const m of entity) {
|
|
666
|
+
if (merged.length >= lim) break;
|
|
667
|
+
if (!seen.has(m.id)) { seen.add(m.id); merged.push(m); }
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Mode contract, auto (aligns rrf/minmax with blend): keyword leads, the
|
|
673
|
+
// recipe fills the remaining slots. blend.auto already front-loads keyword;
|
|
674
|
+
// rrf/minmax rank across sources, so re-apply the same "keyword first"
|
|
675
|
+
// ordering here to preserve the pre-fusion auto contract — the keyword
|
|
676
|
+
// hit list keeps its power, and only slots it couldn't fill go to the
|
|
677
|
+
// recipe's ranking.
|
|
678
|
+
if (recipe !== "blend" && mode === "auto" && keyword.length) {
|
|
679
|
+
const head = keyword.slice(0, lim);
|
|
680
|
+
const seen = new Set(head.map((m) => m.id));
|
|
681
|
+
const tail = merged.filter((m) => !seen.has(m.id)).slice(0, Math.max(0, lim - head.length));
|
|
682
|
+
merged = head.concat(tail);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
return { merged, signals };
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Search memories for a query. Merges up to four recall sources (keyword,
|
|
690
|
+
* vector, BM25, and — when config.entityRecallEnabled is on — entity-linked
|
|
691
|
+
* memories whose entity names the query mentions; see fuseRecall) according
|
|
692
|
+
* to config.recallFusion (blend/rrf/minmax — see
|
|
693
|
+
* fuseRecall), then optionally decorates rows with per-source signals
|
|
694
|
+
* (config.signalTransparency), applies semantic dedup (non-keyword modes),
|
|
695
|
+
* reranking, and epistemic trust re-weighting, and finally hands the merged
|
|
696
|
+
* list to the recall-layer recorder.
|
|
697
|
+
*
|
|
698
|
+
* options:
|
|
699
|
+
* mode — 'auto' (default) | 'keyword' | 'vector' | 'hybrid'
|
|
700
|
+
* topK — max rows (default 20)
|
|
701
|
+
* threshold — explicit vector score floor (overrides adaptive)
|
|
702
|
+
* useRerank — apply the reranker if available (default true)
|
|
703
|
+
* recordRecall — write a recall_runs audit row (default from config)
|
|
704
|
+
*
|
|
705
|
+
* Returns an array of memory rows { id, title, content, score, source, ... },
|
|
706
|
+
* with `signals` added when config.signalTransparency is on. Never throws:
|
|
707
|
+
* a vector/rerank failure degrades to keyword results.
|
|
708
|
+
*/
|
|
709
|
+
async function searchMemories(query, options = {}) {
|
|
710
|
+
const {
|
|
711
|
+
mode = "auto",
|
|
712
|
+
topK = 20,
|
|
713
|
+
threshold,
|
|
714
|
+
useRerank = true,
|
|
715
|
+
// v0.8.0 A2(issue #17):当前会话 scope(工具层从 exec 解析后传入)与
|
|
716
|
+
// occurred_at 时间窗。两者都只在显式传入时生效,既有调用方(注入/梦/评测)
|
|
717
|
+
// 不传 → 行为与 A2 前一致。
|
|
718
|
+
scope = null,
|
|
719
|
+
occurredFrom = null,
|
|
720
|
+
occurredTo = null,
|
|
721
|
+
recordRecall = options.recordRecall ?? (config?.recallRecordDefault ?? true)
|
|
722
|
+
} = options;
|
|
723
|
+
const q = String(query ?? "").trim();
|
|
724
|
+
if (!q) return [];
|
|
725
|
+
|
|
726
|
+
// entity:/attr: 前缀路由(v0.3.0 Phase 3)。entitySearchEnabled 关闭时走原逻辑。
|
|
727
|
+
if (config?.entitySearchEnabled) {
|
|
728
|
+
if (q.startsWith("entity:")) {
|
|
729
|
+
return searchByEntity(q.slice(7).trim(), options);
|
|
730
|
+
}
|
|
731
|
+
if (q.startsWith("attr:")) {
|
|
732
|
+
const [key, value] = q.slice(5).split("=");
|
|
733
|
+
return searchByAttr(key, value, options);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
const lim = topK > 0 ? topK : 20;
|
|
738
|
+
|
|
739
|
+
// Keyword results, decorated with a score so they can be weight-blended
|
|
740
|
+
// with vector results and reported uniformly. source tracks where each
|
|
741
|
+
// candidate came from for the recall layer receipt.
|
|
742
|
+
const rawKeyword = store.search(q, { limit: lim });
|
|
743
|
+
const keyword = rawKeyword.map((m) => ({ ...m, score: scoreKeyword(m, q), source: "keyword" }));
|
|
744
|
+
const wantVector = mode === "vector" || mode === "hybrid" || (mode === "auto" && !!embedder);
|
|
745
|
+
let vector = [];
|
|
746
|
+
if (wantVector && embedder) {
|
|
747
|
+
try {
|
|
748
|
+
// Legacy embedders expose embed(query); local ones expose embedSingle.
|
|
749
|
+
const embedSingle = typeof embedder.embedSingle === "function"
|
|
750
|
+
? embedder.embedSingle.bind(embedder)
|
|
751
|
+
: embedder.embed.bind(embedder);
|
|
752
|
+
const qv = await embedSingle(q);
|
|
753
|
+
if (qv?.length) {
|
|
754
|
+
// Adaptive threshold (v0.5.0 1.2): the fetch runs at the loosest
|
|
755
|
+
// branch floor so the head-gap rule can still re-admit the tail;
|
|
756
|
+
// the final cutoff is computed against the fetched score
|
|
757
|
+
// distribution. Explicit `threshold` wins; disabled → legacy 0.
|
|
758
|
+
const adaptive = config?.adaptiveThresholdEnabled !== false;
|
|
759
|
+
const fetchThreshold = adaptive && threshold === undefined
|
|
760
|
+
? Math.min(0.5, adaptiveThreshold(q))
|
|
761
|
+
: (threshold ?? 0);
|
|
762
|
+
const search = vectorIndex
|
|
763
|
+
? vectorIndex.search(qv, { limit: lim * 2, threshold: fetchThreshold })
|
|
764
|
+
: store.searchVector(qv, { limit: lim * 2, threshold: fetchThreshold });
|
|
765
|
+
const finalThreshold = adaptive && threshold === undefined
|
|
766
|
+
? adaptiveThreshold(q, search)
|
|
767
|
+
: (threshold ?? 0);
|
|
768
|
+
vector = search
|
|
769
|
+
.filter((m) => (m.score ?? 1) >= finalThreshold)
|
|
770
|
+
.map((m) => ({ ...m, vector: true, source: "vector" }));
|
|
771
|
+
}
|
|
772
|
+
} catch { /* vector unavailable: keep keyword results */ }
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// BM25 third path (v0.5.0 1.1): IDF-weighted token overlap recalls rows
|
|
776
|
+
// whose query terms are scattered — the gap LIKE substring matching
|
|
777
|
+
// cannot close. Scores are already normalized to [0,1].
|
|
778
|
+
const bm25 = bm25Recall(q, lim).map((m) => ({ ...m, source: "bm25" }));
|
|
779
|
+
// Loose blend weight: BM25 confirms and backfills, never dominates the
|
|
780
|
+
// semantic signal. Same-memory overlap boosts, unseen ids backfill.
|
|
781
|
+
const wb = 0.3;
|
|
782
|
+
|
|
783
|
+
// Graph fourth path (issue #219, opt-in entityRecallEnabled): query-
|
|
784
|
+
// mentioned entities pull their linked memories into the pool. Keyword
|
|
785
|
+
// mode stays text-only per the mode contract, so the axis is skipped
|
|
786
|
+
// there even when enabled.
|
|
787
|
+
const entity = mode === "keyword" ? [] : entityRecall(q, lim);
|
|
788
|
+
// Entity axis shares BM25's backfill weight (we = wb) until #217 recall
|
|
789
|
+
// data justifies a distinct entity weight.
|
|
790
|
+
|
|
791
|
+
// Hybrid blending weights from config when provided.
|
|
792
|
+
const wv = config?.hybridSearchVectorWeight ?? DEFAULT_HYBRID_WEIGHTS.vector;
|
|
793
|
+
const wk = config?.hybridSearchKeywordWeight ?? DEFAULT_HYBRID_WEIGHTS.keyword;
|
|
794
|
+
|
|
795
|
+
const { merged: fusedMerged, signals } = fuseRecall({ keyword, vector, bm25, entity, lim, mode, wv, wk, wb, we: wb });
|
|
796
|
+
let merged = fusedMerged;
|
|
797
|
+
// v0.8.0 A3(issue #17):strictScope 硬过滤——他 scope 的候选直接出局
|
|
798
|
+
// (区别于 A2 的降权保留可见);未标注行与命中行保留。strict 与 A2 加权
|
|
799
|
+
// 叠加:过滤后剩下的命中行仍吃加成。scope 未传(flag 关)或完全解析不到
|
|
800
|
+
// 时跳过——identity 为空的对象({null,null})按 fail-closed 过滤。
|
|
801
|
+
if (config.strictScope === true && scope) {
|
|
802
|
+
merged = merged.filter((m) => isVisibleInScope(m, scope));
|
|
803
|
+
}
|
|
804
|
+
// v0.8.0 A2:occurred_at 时间过滤——在融合池上先滤再 dedup/slice,rerank
|
|
805
|
+
// 只看窗内候选,topK 槽位不被窗外行占用。
|
|
806
|
+
const occurredBounds = updatedAtBounds(occurredFrom, occurredTo);
|
|
807
|
+
if (occurredBounds.from || occurredBounds.to) {
|
|
808
|
+
merged = merged.filter((m) => inOccurredBounds(m, occurredBounds));
|
|
809
|
+
}
|
|
810
|
+
// Signal transparency (#2): decorate each returned row with its per-source
|
|
811
|
+
// scores and the final fused score. Purely additive — never changes rank.
|
|
812
|
+
if (config?.signalTransparency === true) {
|
|
813
|
+
merged = merged.map((m) => ({ ...m, signals: { ...(signals.get(m.id) ?? {}), final: m.score ?? 0 } }));
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// Search-time semantic dedup (v0.5.0 2.3): near-duplicate rows are
|
|
817
|
+
// dropped before the reranker sees them, so topK slots carry distinct
|
|
818
|
+
// information instead of the same memory twice. Keyword mode is exempt —
|
|
819
|
+
// it is the documented text-only path and must not be altered by
|
|
820
|
+
// embedding state.
|
|
821
|
+
merged = mode === "keyword" ? merged : semanticDeduplicate(merged);
|
|
822
|
+
merged = merged.slice(0, lim);
|
|
823
|
+
let result = useRerank && reranker && merged.length
|
|
824
|
+
? await rerankCandidates(q, merged, lim)
|
|
825
|
+
: merged;
|
|
826
|
+
// Epistemic trust (v0.4.5): opt-in re-weighting of the final candidate
|
|
827
|
+
// scores by source credibility. When off (default) `result` is returned
|
|
828
|
+
// untouched — exactly the legacy behavior.
|
|
829
|
+
if (config.trustEpistemicWeighting === true) {
|
|
830
|
+
result = result
|
|
831
|
+
.map((m) => ({
|
|
832
|
+
...m,
|
|
833
|
+
score: (m.score ?? 0) * (EPISTEMIC_WEIGHTS[m.epistemic_status] ?? 1)
|
|
834
|
+
}))
|
|
835
|
+
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
|
|
836
|
+
.slice(0, lim);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// v0.8.0 A2(issue #17):scope 检索加权——两维都无法确立 foreign 的候选
|
|
840
|
+
// (命中/未标注/当前侧解析不到)加成,确立 foreign 的候选降权但保留可见
|
|
841
|
+
// (硬过滤是 A3 strictScope);未标注行与命中行同列吃 BOOST、不被压制。
|
|
842
|
+
// flag 关或调用方未传 scope 时不动分,排序与 A2 前逐字节一致。与
|
|
843
|
+
// epistemic 加权同款收尾:乘分 → 降序 → 截 topK。
|
|
844
|
+
if (config.scopeEnabled === true && scope && (scope.agent_scope || scope.workspace_scope)) {
|
|
845
|
+
result = result
|
|
846
|
+
.map((m) => ({ ...m, score: (m.score ?? 0) * scopeMultiplier(m, scope) }))
|
|
847
|
+
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
|
|
848
|
+
.slice(0, lim);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// Recall layer receipt: with recordRecall on, hand the actual merged
|
|
852
|
+
// candidate list (id/title/content/score/source) to the injected recorder
|
|
853
|
+
// before returning, making the retrieval scene replayable — the sibling of
|
|
854
|
+
// the dream judgment-layer audit trail. Recorder failures must never break
|
|
855
|
+
// the search itself.
|
|
856
|
+
if (recordRecall && recallRecorder) {
|
|
857
|
+
try {
|
|
858
|
+
recallRecorder({
|
|
859
|
+
query: q,
|
|
860
|
+
mode,
|
|
861
|
+
topK: lim,
|
|
862
|
+
threshold: threshold ?? null,
|
|
863
|
+
candidates: result.map((m) => ({
|
|
864
|
+
id: m.id,
|
|
865
|
+
title: m.title,
|
|
866
|
+
content: m.content,
|
|
867
|
+
score: m.score ?? null,
|
|
868
|
+
source: m.source ?? "keyword"
|
|
869
|
+
})),
|
|
870
|
+
createdAt: new Date().toISOString()
|
|
871
|
+
});
|
|
872
|
+
} catch { /* recall receipt is best effort */ }
|
|
873
|
+
}
|
|
874
|
+
// Bug4: cache the latest semantic recall so the sync injection path can
|
|
875
|
+
// reuse it when the injection query matches (no async embed available).
|
|
876
|
+
lastSemanticRecall = { query: q, items: result };
|
|
877
|
+
touchRecalled(result);
|
|
878
|
+
return result;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* Retrieval evaluation (方案 B): run one search for `query`, compare the ids
|
|
883
|
+
* it actually returned against `expectedIds`, and return the computed
|
|
884
|
+
* metrics. When persistence is on (config.evalPersistTestResults, or an
|
|
885
|
+
* explicit `persist` override per call) the snapshot is written to the
|
|
886
|
+
* recall_evals table — a SEPARATE store from the recall_runs production audit,
|
|
887
|
+
* so test/eval data never inflates the production trail.
|
|
888
|
+
*
|
|
889
|
+
* options:
|
|
890
|
+
* mode/topK/threshold/useRerank — passed through to searchMemories
|
|
891
|
+
* evalType — label for the snapshot (default 'manual')
|
|
892
|
+
* recordRecall — also write a recall_runs audit row for the
|
|
893
|
+
* same scene and link it via recall_run_id
|
|
894
|
+
* (default false: eval stays unlinked)
|
|
895
|
+
* recallRunId — explicit link to an existing recall_runs id
|
|
896
|
+
* persist — override the config gate for this call
|
|
897
|
+
*
|
|
898
|
+
* Returns { metrics, actualIds, expectedIds, recallRunId, persisted }.
|
|
899
|
+
* Never throws on persistence failures: a broken eval write must not break
|
|
900
|
+
* the retrieval quality measurement.
|
|
901
|
+
*/
|
|
902
|
+
async function evaluateRetrieval(query, expectedIds, options = {}) {
|
|
903
|
+
const q = String(query ?? "").trim();
|
|
904
|
+
const expected = Array.isArray(expectedIds) ? expectedIds : [];
|
|
905
|
+
const {
|
|
906
|
+
mode = "auto",
|
|
907
|
+
topK = 20,
|
|
908
|
+
threshold,
|
|
909
|
+
useRerank = true,
|
|
910
|
+
evalType = "manual",
|
|
911
|
+
recordRecall = false,
|
|
912
|
+
recallRunId = null,
|
|
913
|
+
persist = config.evalPersistTestResults === true
|
|
914
|
+
} = options;
|
|
915
|
+
if (!q) {
|
|
916
|
+
const empty = computeRetrievalMetrics([], expected);
|
|
917
|
+
return { metrics: empty, actualIds: [], expectedIds: expected, recallRunId: null, persisted: false };
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
const rows = await searchMemories(q, { mode, topK, threshold, useRerank, recordRecall: false });
|
|
921
|
+
const actualIds = rows.map((m) => m.id);
|
|
922
|
+
const metrics = computeRetrievalMetrics(actualIds, expected);
|
|
923
|
+
|
|
924
|
+
// Optional recall_runs audit for the same scene; the eval row then links to
|
|
925
|
+
// it. Kept separate from the production recorder (which fires only on
|
|
926
|
+
// recordRecall=true inside searchMemories) — eval never double-records.
|
|
927
|
+
// An explicit recallRunId wins; recordRecall only mints a NEW audit run when
|
|
928
|
+
// the caller did not already link one (never clobber an existing link).
|
|
929
|
+
let runId = recallRunId ?? null;
|
|
930
|
+
if (recordRecall && runId === null) {
|
|
931
|
+
try {
|
|
932
|
+
const run = store.saveRecallRun({
|
|
933
|
+
query: q,
|
|
934
|
+
mode,
|
|
935
|
+
topK,
|
|
936
|
+
threshold: threshold ?? null,
|
|
937
|
+
candidates: rows.map((m) => ({
|
|
938
|
+
id: m.id,
|
|
939
|
+
title: m.title,
|
|
940
|
+
content: m.content,
|
|
941
|
+
score: m.score ?? null,
|
|
942
|
+
source: m.source ?? "keyword"
|
|
943
|
+
})),
|
|
944
|
+
created_at: new Date().toISOString()
|
|
945
|
+
});
|
|
946
|
+
runId = run.id;
|
|
947
|
+
} catch { /* non-fatal: the eval itself still succeeds */ }
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
let persisted = false;
|
|
951
|
+
if (persist) {
|
|
952
|
+
try {
|
|
953
|
+
store.saveRecallEval({
|
|
954
|
+
recall_run_id: runId,
|
|
955
|
+
query: q,
|
|
956
|
+
expected_ids: expected,
|
|
957
|
+
actual_ids: actualIds,
|
|
958
|
+
metrics,
|
|
959
|
+
eval_type: evalType,
|
|
960
|
+
created_at: new Date().toISOString()
|
|
961
|
+
});
|
|
962
|
+
persisted = true;
|
|
963
|
+
} catch { /* non-fatal: measurement survives a failed eval write */ }
|
|
964
|
+
}
|
|
965
|
+
return { metrics, actualIds, expectedIds: expected, recallRunId: runId, persisted };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Fire-and-forget write notification; errors are swallowed to keep write
|
|
970
|
+
* paths clean. The store mutation has already committed, so a throwing
|
|
971
|
+
* subscriber must not surface as a write failure. Archive/forget flags are
|
|
972
|
+
* state toggles, not content writes, so they never notify.
|
|
973
|
+
*/
|
|
974
|
+
function notifyWrite() {
|
|
975
|
+
if (txDepth > 0) return; // deferred to the transaction's commit
|
|
976
|
+
if (onWrite) {
|
|
977
|
+
try { onWrite(); } catch { /* ignore */ }
|
|
978
|
+
}
|
|
979
|
+
if (dreamHook) {
|
|
980
|
+
try { dreamHook(); } catch { /* ignore */ }
|
|
981
|
+
}
|
|
982
|
+
if (sleepHook) {
|
|
983
|
+
try { sleepHook(); } catch { /* ignore */ }
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Run several store mutations atomically (SQLite BEGIN/COMMIT/ROLLBACK) and
|
|
989
|
+
* fire the deferred side effects once against the committed state. A throwing
|
|
990
|
+
* body rolls the whole batch back — no partial writes, no diverged mirror.
|
|
991
|
+
* Errors propagate to the caller. NOTE: the commit path re-renders the mirror
|
|
992
|
+
* and notifies subscribers, but re-embedding is left to the caller (the dream
|
|
993
|
+
* flow re-embeds through maintainIndexAfterDream).
|
|
994
|
+
*/
|
|
995
|
+
function transaction(fn) {
|
|
996
|
+
store.db.exec("BEGIN");
|
|
997
|
+
txDepth++;
|
|
998
|
+
try {
|
|
999
|
+
const result = fn();
|
|
1000
|
+
store.db.exec("COMMIT");
|
|
1001
|
+
return result;
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
try { store.db.exec("ROLLBACK"); } catch { /* store may be closed */ }
|
|
1004
|
+
throw error;
|
|
1005
|
+
} finally {
|
|
1006
|
+
txDepth--;
|
|
1007
|
+
// Sync failures are surfaced, not swallowed (peer blocker 2): the mirror
|
|
1008
|
+
// debt was already recorded by markMirrorDirty inside syncMirror, so a
|
|
1009
|
+
// restart recovers — but the operator must see it now, not after restart.
|
|
1010
|
+
const syncResult = syncMirror();
|
|
1011
|
+
if (!syncResult?.success && !syncResult?.deferred) {
|
|
1012
|
+
logger?.warn?.("mirror sync failed after transaction:", syncResult?.error);
|
|
1013
|
+
}
|
|
1014
|
+
notifyWrite();
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Embed an arbitrary query text and return its vector (null on failure / no
|
|
1020
|
+
* embedder). Used by the injector to prefetch the semantic-first recall
|
|
1021
|
+
* vector for the current user message — the system-prompt render is
|
|
1022
|
+
* synchronous, so the vector must be cached in advance (Bug4).
|
|
1023
|
+
*/
|
|
1024
|
+
async function embedQuery(query) {
|
|
1025
|
+
const q = String(query ?? "").trim();
|
|
1026
|
+
if (!q || !embedder) return null;
|
|
1027
|
+
try {
|
|
1028
|
+
const embedSingle = typeof embedder.embedSingle === "function"
|
|
1029
|
+
? embedder.embedSingle.bind(embedder)
|
|
1030
|
+
: embedder.embed.bind(embedder);
|
|
1031
|
+
const vector = await embedSingle(q);
|
|
1032
|
+
return Array.isArray(vector) && vector.length ? vector : null;
|
|
1033
|
+
} catch {
|
|
1034
|
+
return null;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/**
|
|
1039
|
+
* 写入端同会话语义去重(Issue #127,opt-in,默认 off):落库前把新条目与
|
|
1040
|
+
* 「同会话 + 时间窗」内已落库的记忆比对,命中即并入既有条目,不再新造一行。
|
|
1041
|
+
*
|
|
1042
|
+
* 分层:title 档走零成本的标题归一化;vector 档复用已有 embedding 列做近邻,
|
|
1043
|
+
* 新条目的向量由 embedder 现算(embedQuery),全程无 LLM 调用。embedder 不可用
|
|
1044
|
+
* 或向量缺失一律返回 undefined 回落正常写入——去重是增强,绝不能成为写入依赖。
|
|
1045
|
+
*
|
|
1046
|
+
* 作用域刻意限定「同会话」:跨会话的同类事实仍交给 autoDream / sleep 的批量裁决。
|
|
1047
|
+
* 比对逻辑与并入动作分别复用 cosineVec 与 saveWithDedupe 的 _mergeInto 分支。
|
|
1048
|
+
*
|
|
1049
|
+
* @returns {{action: "merged", memory: object, sim: number}|undefined} 命中则返回
|
|
1050
|
+
* 并入目标与相似度;未命中(含任何异常)返回 undefined。
|
|
1051
|
+
*/
|
|
1052
|
+
async function findSessionDuplicate(memory, { mode = "off", minSim = 0.92, windowHours = 24, source } = {}) {
|
|
1053
|
+
if (mode === "off" || !source || !memory?.title) return undefined;
|
|
1054
|
+
try {
|
|
1055
|
+
const sinceMs = windowHours > 0 ? Date.now() - windowHours * 3600000 : 0;
|
|
1056
|
+
const inWindow = (m) => {
|
|
1057
|
+
if (sinceMs <= 0) return true;
|
|
1058
|
+
const t = Date.parse(m.created_at ?? "");
|
|
1059
|
+
return !Number.isFinite(t) || t >= sinceMs; // 时间戳损坏时不误杀
|
|
1060
|
+
};
|
|
1061
|
+
const candidates = store
|
|
1062
|
+
.list({ type: memory.type, source, limit: 200 })
|
|
1063
|
+
.filter((m) => !m.archived && inWindow(m));
|
|
1064
|
+
if (!candidates.length) return undefined;
|
|
1065
|
+
|
|
1066
|
+
if (mode === "title") {
|
|
1067
|
+
const norm = (s) => String(s ?? "").toLowerCase().replace(/[\s\p{P}]+/gu, "");
|
|
1068
|
+
const key = norm(memory.title);
|
|
1069
|
+
if (!key) return undefined;
|
|
1070
|
+
const hit = candidates.find((m) => norm(m.title) === key);
|
|
1071
|
+
return hit ? { action: "merged", memory: hit, sim: 1 } : undefined;
|
|
1072
|
+
}
|
|
1073
|
+
if (mode !== "vector") return undefined;
|
|
1074
|
+
|
|
1075
|
+
const vecs = store.getEmbeddings(candidates.map((m) => m.id));
|
|
1076
|
+
if (!vecs.size) return undefined;
|
|
1077
|
+
const probe = await embedQuery([memory.title, memory.content].filter(Boolean).join("\n"));
|
|
1078
|
+
if (!probe) return undefined;
|
|
1079
|
+
let best;
|
|
1080
|
+
for (const m of candidates) {
|
|
1081
|
+
const v = vecs.get(m.id);
|
|
1082
|
+
if (!v) continue; // 无向量的既有行不参与比对(无信号 = 不判定)
|
|
1083
|
+
const sim = cosineVec(probe, v);
|
|
1084
|
+
if (sim >= minSim && (!best || sim > best.sim)) best = { action: "merged", memory: m, sim };
|
|
1085
|
+
}
|
|
1086
|
+
return best;
|
|
1087
|
+
} catch {
|
|
1088
|
+
return undefined; // 去重失败绝不阻塞写入
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/**
|
|
1093
|
+
* Save a memory, merging into an existing one when title matches within the same type.
|
|
1094
|
+
*
|
|
1095
|
+
* Bug5: a same-title merge no longer overwrites — the new content is appended
|
|
1096
|
+
* under a timestamped `---` separator (`旧内容\n\n---\n[时间戳] 新内容`) and the
|
|
1097
|
+
* previous content is archived into content_history (source: auto_merge, FIFO
|
|
1098
|
+
* capped at 20). importance takes the max of both (capped at 5). Callers that
|
|
1099
|
+
* truly replace a row (dream summary regeneration) pass `_overwrite: true` to
|
|
1100
|
+
* overwrite directly while still archiving the old version (source: overwrite).
|
|
1101
|
+
* mergeHumanEdits entry points pass `_humanEdited: true` — same direct
|
|
1102
|
+
* overwrite semantics, source: human_override.
|
|
1103
|
+
*
|
|
1104
|
+
* Bug7 (memory quality filter): when config.memoryQualityFilter.enabled, the
|
|
1105
|
+
* memory is scored after dedupe, before write:
|
|
1106
|
+
* score >= degradeThreshold → stored normally (score persisted)
|
|
1107
|
+
* archiveThreshold <= score < 60 → persisted + ranked degraded
|
|
1108
|
+
* score < archiveThreshold → archived + tagged low_quality (still
|
|
1109
|
+
* explicitly searchable via includeArchived)
|
|
1110
|
+
* @returns {{action: "created"|"merged", memory: object}}
|
|
1111
|
+
*/
|
|
1112
|
+
function saveWithDedupe(memory) {
|
|
1113
|
+
// Bug7: score quality once (after dedupe lookup, before write). Failures
|
|
1114
|
+
// inside the evaluator are impossible (pure function), but the write that
|
|
1115
|
+
// records the score must never fail the save — wrap defensively.
|
|
1116
|
+
const qf = config.memoryQualityFilter;
|
|
1117
|
+
let quality = null;
|
|
1118
|
+
if (qf?.enabled === true) {
|
|
1119
|
+
try {
|
|
1120
|
+
const recentContents = store.all().slice(0, 20).map((m) => m.content ?? "");
|
|
1121
|
+
quality = evaluateMemoryQuality(memory, {
|
|
1122
|
+
minContentLength: qf.minContentLength ?? 10,
|
|
1123
|
+
recentContents
|
|
1124
|
+
});
|
|
1125
|
+
} catch { /* quality scoring is best-effort */ }
|
|
1126
|
+
}
|
|
1127
|
+
// dream 总览按 source 身份去重,而非本地化标题:memory.language 切换后
|
|
1128
|
+
// 标题变化,若仍按 (type, title) 匹配会出现两个活跃的 summary 同时注入。
|
|
1129
|
+
// 其余类型维持 (type, title) 匹配不变。
|
|
1130
|
+
const candidates = store.list({ type: memory.type, limit: 100 });
|
|
1131
|
+
// v0.8.0 A1(issue #17):去重键由 (type, title) 扩展为
|
|
1132
|
+
// (type, title, agent_scope, workspace_scope, sensitivity)——不同作用域的同
|
|
1133
|
+
// 标题记忆绝不互相物理合并(旧逻辑跨 agent/workspace 并行,事后无法拆分)。
|
|
1134
|
+
// NULL 归一为「未标注」:未标注行之间互相匹配(含存量行),与已标注行不
|
|
1135
|
+
// 匹配。
|
|
1136
|
+
// v0.8.1(issue #170 复核项 1):比较不再受 scopeEnabled 门控——显式声明
|
|
1137
|
+
// flag 关也生效(工具层明写「读了自动标注也生效」,去重必须同口径),否则
|
|
1138
|
+
// 关自动标注后同标题不同 scope 的行会物理合并进第一行的归属。存量全 NULL
|
|
1139
|
+
// 行互相匹配,A1 前行为不变。
|
|
1140
|
+
const scopeMatches = (m) =>
|
|
1141
|
+
scopeKeyOf(m.agent_scope) === scopeKeyOf(memory.agent_scope) &&
|
|
1142
|
+
scopeKeyOf(m.workspace_scope) === scopeKeyOf(memory.workspace_scope) &&
|
|
1143
|
+
scopeKeyOf(m.sensitivity) === scopeKeyOf(memory.sensitivity);
|
|
1144
|
+
// Issue #127:写入端语义去重命中时,调用方用 _mergeInto 指定并入目标——复用
|
|
1145
|
+
// 下面这段并入逻辑(appendContent + content_history + 质量处置),不另写第二份
|
|
1146
|
+
// 实现。目标已被并发删除时回落到常规匹配。显式目标同样过 scope 门:跨作用域
|
|
1147
|
+
// 的语义相似不并入(防泄漏),回落为独立新行。
|
|
1148
|
+
const explicitTarget = memory._mergeInto ? store.getById(memory._mergeInto) : undefined;
|
|
1149
|
+
const existing = explicitTarget
|
|
1150
|
+
? (scopeMatches(explicitTarget) ? explicitTarget : undefined)
|
|
1151
|
+
: (memory.type === "summary" && memory.source === "dream")
|
|
1152
|
+
? (candidates.find((m) => m.source === "dream" && scopeMatches(m))
|
|
1153
|
+
?? candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim()))
|
|
1154
|
+
: (memory.type === "summary" && memory.source === "narrative")
|
|
1155
|
+
// 叙述条(#164)按主题键去重而非本地化标题:标题随语言变
|
|
1156
|
+
// (叙述:X / Narrative: X),title 匹配在语言切换后会残留同 tag 双行。
|
|
1157
|
+
// tag 存于 tags[0](generateNarratives 落库),跨语言稳定 → 原地刷新。
|
|
1158
|
+
? (candidates.find((m) => m.source === "narrative" && m.tags?.[0] === memory.tags?.[0] && scopeMatches(m))
|
|
1159
|
+
?? candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim()))
|
|
1160
|
+
: candidates.find((m) => scopeMatches(m) && m.title.trim() === String(memory.title).trim());
|
|
1161
|
+
if (existing) {
|
|
1162
|
+
const newContent = String(memory.content ?? "");
|
|
1163
|
+
if (!newContent.trim()) {
|
|
1164
|
+
// Nothing to merge: the row stays untouched.
|
|
1165
|
+
return { action: "merged", memory: existing };
|
|
1166
|
+
}
|
|
1167
|
+
const direct = memory._overwrite === true || memory._humanEdited === true;
|
|
1168
|
+
const content = direct
|
|
1169
|
+
? newContent
|
|
1170
|
+
: appendContent(existing.content, newContent);
|
|
1171
|
+
const importance = Math.min(5, Math.max(existing.importance, memory.importance ?? existing.importance));
|
|
1172
|
+
// v0.8.1 底座(issue #170):去重命中=scope 值完全同键,此时显式写入把
|
|
1173
|
+
// 被并入行的同维来源升级为 explicit(用户刚刚显式声明了同一归属),
|
|
1174
|
+
// 并刷新 scope_decided_at。仅升级来源、不改值——值改变会走新行。
|
|
1175
|
+
const scopeUpgrade = {};
|
|
1176
|
+
if (memory.agent_scope_source === "explicit" && existing.agent_scope_source !== "explicit") {
|
|
1177
|
+
scopeUpgrade.agent_scope_source = "explicit";
|
|
1178
|
+
}
|
|
1179
|
+
if (memory.workspace_scope_source === "explicit" && existing.workspace_scope_source !== "explicit") {
|
|
1180
|
+
scopeUpgrade.workspace_scope_source = "explicit";
|
|
1181
|
+
}
|
|
1182
|
+
if (Object.keys(scopeUpgrade).length) scopeUpgrade.scope_decided_at = new Date().toISOString();
|
|
1183
|
+
const merged = store.update(existing.id, {
|
|
1184
|
+
content,
|
|
1185
|
+
importance,
|
|
1186
|
+
tags: memory.tags ?? existing.tags,
|
|
1187
|
+
title: memory.title ?? existing.title,
|
|
1188
|
+
...(memory.evidence !== undefined ? { evidence: memory.evidence } : {}),
|
|
1189
|
+
content_history: pushContentHistory(existing, direct
|
|
1190
|
+
? (memory._humanEdited === true ? "human_override" : "overwrite")
|
|
1191
|
+
: "auto_merge"),
|
|
1192
|
+
...scopeUpgrade,
|
|
1193
|
+
...(quality ? { quality_score: quality.score } : {})
|
|
1194
|
+
});
|
|
1195
|
+
// v0.8.1(issue #170 review 3):来源升级也是归属性质改变——与
|
|
1196
|
+
// updateMemory 的显式修正同等待遇,落一行 scope_changes(actor=tool:
|
|
1197
|
+
// 只有 memory_save 的显式参数会带 explicit 来源走到这里)。审计失败只
|
|
1198
|
+
// warn 不反噬合并。升级只在来源首次变化时触发,不会每次并入都写。
|
|
1199
|
+
if (Object.keys(scopeUpgrade).length) {
|
|
1200
|
+
try {
|
|
1201
|
+
store.saveScopeChange({
|
|
1202
|
+
memory_id: existing.id,
|
|
1203
|
+
actor: "tool",
|
|
1204
|
+
prev_agent_scope: existing.agent_scope ?? null,
|
|
1205
|
+
prev_workspace_scope: existing.workspace_scope ?? null,
|
|
1206
|
+
next_agent_scope: merged.agent_scope ?? null,
|
|
1207
|
+
next_workspace_scope: merged.workspace_scope ?? null,
|
|
1208
|
+
agent_scope_source: merged.agent_scope_source ?? null,
|
|
1209
|
+
workspace_scope_source: merged.workspace_scope_source ?? null,
|
|
1210
|
+
decided_at: scopeUpgrade.scope_decided_at
|
|
1211
|
+
});
|
|
1212
|
+
} catch (e) {
|
|
1213
|
+
try { logger?.warn?.(`[dsh-mneme] scope upgrade audit failed: ${String(e)}`); } catch { /* 不反噬 */ }
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
// Bug7: a degraded/archived result is applied on top of the merged row.
|
|
1217
|
+
const result = applyQualityDisposition(merged, quality, qf);
|
|
1218
|
+
afterSync("write");
|
|
1219
|
+
notifyWrite();
|
|
1220
|
+
scheduleEmbed(result);
|
|
1221
|
+
return { action: "merged", memory: result };
|
|
1222
|
+
}
|
|
1223
|
+
const created = store.save({
|
|
1224
|
+
type: memory.type,
|
|
1225
|
+
title: memory.title,
|
|
1226
|
+
content: memory.content,
|
|
1227
|
+
tags: memory.tags ?? [],
|
|
1228
|
+
importance: memory.importance ?? 3,
|
|
1229
|
+
source: memory.source ?? "manual",
|
|
1230
|
+
...(memory.evidence !== undefined ? { evidence: memory.evidence } : {}),
|
|
1231
|
+
// v0.8.0 A1:scope 标注透传(store 端归一化,未标注落 NULL)。
|
|
1232
|
+
// v0.8.1 底座:来源(auto/explicit)与决策时间随行透传。
|
|
1233
|
+
agent_scope: memory.agent_scope,
|
|
1234
|
+
workspace_scope: memory.workspace_scope,
|
|
1235
|
+
agent_scope_source: memory.agent_scope_source,
|
|
1236
|
+
workspace_scope_source: memory.workspace_scope_source,
|
|
1237
|
+
scope_decided_at: memory.scope_decided_at,
|
|
1238
|
+
sensitivity: memory.sensitivity,
|
|
1239
|
+
occurred_at: memory.occurred_at,
|
|
1240
|
+
...(quality ? { quality_score: quality.score } : {})
|
|
1241
|
+
});
|
|
1242
|
+
const result = applyQualityDisposition(created, quality, qf);
|
|
1243
|
+
afterSync("write");
|
|
1244
|
+
notifyWrite();
|
|
1245
|
+
scheduleEmbed(result);
|
|
1246
|
+
scheduleEntityExtraction(result);
|
|
1247
|
+
return { action: "created", memory: result };
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* Bug7: apply the quality verdict to a freshly written row. Below the archive
|
|
1252
|
+
* threshold the memory is archived + tagged low_quality (still searchable
|
|
1253
|
+
* explicitly via includeArchived); between archive and degrade thresholds the
|
|
1254
|
+
* score is already persisted and only the injection ranking is affected
|
|
1255
|
+
* (importance × score/100). Best-effort: a disposition write failure must
|
|
1256
|
+
* never fail the save. Returns the (possibly refreshed) memory row so callers
|
|
1257
|
+
* see the archived/tagged state, not the pre-disposition snapshot.
|
|
1258
|
+
*
|
|
1259
|
+
* Issue #135 附属发现 1:importance ≥ memoryQualityFilter.exemptImportance
|
|
1260
|
+
* (默认 4)的记忆不参与静默自动归档——评分与信号标签照常写入(可观测),
|
|
1261
|
+
* 注入排序照常按 importance × score/100 降权,但 setArchived 跳过。报告实测
|
|
1262
|
+
* 150 条低分归档里 128 条 importance ≥ 4(51 条 = 5):一条被显式标为重要的
|
|
1263
|
+
* 记忆不该被规则分静默归档、无感知无豁免。
|
|
1264
|
+
*/
|
|
1265
|
+
function applyQualityDisposition(memory, quality, qf) {
|
|
1266
|
+
if (!quality || qf?.enabled !== true) return memory;
|
|
1267
|
+
const archiveThreshold = qf.archiveThreshold ?? 30;
|
|
1268
|
+
// Signal tags (meta / repetitive / duplicate / short_content / low_quality)
|
|
1269
|
+
// are merged onto the stored row in every assessed band so the verdict is
|
|
1270
|
+
// observable, not just the numeric score. Below the archive threshold the
|
|
1271
|
+
// memory is additionally archived (still explicitly searchable) — unless
|
|
1272
|
+
// its importance reaches the exemption floor (kept active, demoted only).
|
|
1273
|
+
const tags = [...new Set([...(memory.tags ?? []), ...(quality.tags ?? [])])];
|
|
1274
|
+
const exemptImportance = qf.exemptImportance ?? 4;
|
|
1275
|
+
const importanceExempt = Number.isInteger(memory.importance) && memory.importance >= exemptImportance;
|
|
1276
|
+
if (tags.length === (memory.tags?.length ?? 0) && (quality.score >= archiveThreshold || importanceExempt)) {
|
|
1277
|
+
return memory; // no tag drift and not archived → nothing extra to write
|
|
1278
|
+
}
|
|
1279
|
+
try {
|
|
1280
|
+
store.update(memory.id, { tags, quality_score: quality.score });
|
|
1281
|
+
if (quality.score < archiveThreshold && !importanceExempt) {
|
|
1282
|
+
store.setArchived(memory.id, true);
|
|
1283
|
+
} else if (quality.score < archiveThreshold) {
|
|
1284
|
+
logger?.info?.(`[dsh-mneme] quality filter: memory ${memory.id} scored ${quality.score} < ${archiveThreshold} but importance ${memory.importance} >= exemptImportance ${exemptImportance}; demoted, not archived`);
|
|
1285
|
+
}
|
|
1286
|
+
return store.getById(memory.id);
|
|
1287
|
+
} catch {
|
|
1288
|
+
return memory;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/**
|
|
1293
|
+
* Candidate memories for automatic context injection:
|
|
1294
|
+
* summaries first, then all preferences, then non-forgotten items with
|
|
1295
|
+
* importance >= threshold. History is never auto-injected. Archived entries
|
|
1296
|
+
* are excluded (store.list already filters them by default; the extra
|
|
1297
|
+
* !m.archived check is kept as double insurance).
|
|
1298
|
+
*
|
|
1299
|
+
* Bug4 (hybridInject): when a non-empty `query` is available and a matching
|
|
1300
|
+
* semantic recall was cached by the last searchMemories, the vector hits
|
|
1301
|
+
* lead the selection (up to maxItems*2 candidates) and the rule-based pick
|
|
1302
|
+
* fills + dedupes the remaining slots. Empty query / no cached recall /
|
|
1303
|
+
* hybridInject off → pure legacy rule-based selection.
|
|
1304
|
+
*/
|
|
1305
|
+
function injectCandidates({ query = "", maxItems = 5, threshold = 3, queryVector, scope = null, rotate = null, rotateWindow = 0 } = {}) {
|
|
1306
|
+
const q = String(query ?? "").trim();
|
|
1307
|
+
// codingRetrospect 读取侧门控:编码记忆(rejected_solution / pitfall /
|
|
1308
|
+
// constraint)只在编码任务时注入,防噪声污染其他业务;编码任务时按
|
|
1309
|
+
// codingBoostFactor 加权,让编码记忆在编码场景更靠前。
|
|
1310
|
+
const isCoding = isCodingTask(q, config.codingKeywords ?? []);
|
|
1311
|
+
const codingGate = (m) => isCoding || !CODING_MEMORY_TYPES.has(m.type);
|
|
1312
|
+
// Bug7: quality-weighted importance in the rule-based tier. Unassessed rows
|
|
1313
|
+
// (quality_score null) count as 100 (weight 1), so legacy stores keep their
|
|
1314
|
+
// exact summary>preference>importance ordering.
|
|
1315
|
+
const qualityWeight = (m) => (m.quality_score != null ? m.quality_score / 100 : 1);
|
|
1316
|
+
// Issue #205 补测:候选池必须比轮换窗口大——窗口 N 需要 maxItems×(N+1) 张
|
|
1317
|
+
// 不同的牌,池子只有 maxItems×2 时窗口一开就被吃光、只剩回填(重复率的
|
|
1318
|
+
// 结构性下限由池子大小决定)。无轮换时保持既有 maxItems×2 不变;规则路
|
|
1319
|
+
// 的 200 条上限同样给轮换让路(上限翻倍也只是多读一次 SQL LIMIT)。
|
|
1320
|
+
const rotateWindowN = Number.isInteger(rotateWindow) && rotateWindow > 0 ? rotateWindow : 0;
|
|
1321
|
+
const poolSize = rotateWindowN > 0
|
|
1322
|
+
? Math.max(maxItems * 2, maxItems * (rotateWindowN + 1))
|
|
1323
|
+
: maxItems * 2;
|
|
1324
|
+
const filtered = store.list({ limit: Math.max(200, poolSize), includeForgotten: false })
|
|
1325
|
+
.filter((m) => !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
|
|
1326
|
+
// 叙述条(#164 对齐)按需检索:source=narrative 的 per-topic 叙述不进
|
|
1327
|
+
// 注入候选——常驻位只留给 dream 总览(source=dream)。
|
|
1328
|
+
m.source !== "narrative" &&
|
|
1329
|
+
codingGate(m) &&
|
|
1330
|
+
(m.type === "summary" || m.type === "preference" || m.importance >= threshold));
|
|
1331
|
+
// #218 v1: heat 乘数——heatEnabled 时在优先级层内给 importance×quality 乘
|
|
1332
|
+
// heat(同级内的乘数;priority 分层、store 的 order=chrono 分页序与召回融
|
|
1333
|
+
// 合序都不动)。heat 关闭时不建表、不算 heat,权重恒 1,排序与改动前一致。
|
|
1334
|
+
// selectiveInject 相似度重排(下方)开启且向量可用时相似度优先——heat 只
|
|
1335
|
+
// 生效于规则路排序与语义路回填序。
|
|
1336
|
+
const heatMap = config?.heatEnabled === true
|
|
1337
|
+
? new Map(filtered.map((m) => [m.id, computeHeat(m, Date.now(), config)]))
|
|
1338
|
+
: null;
|
|
1339
|
+
const heatOf = (m) => (heatMap ? heatMap.get(m.id) ?? 1 : 1);
|
|
1340
|
+
const items = filtered.sort((a, b) => {
|
|
1341
|
+
// 编码记忆在编码任务时优先于普通 decision(与 preference 同级),
|
|
1342
|
+
// importance 乘 codingBoostFactor 加权(封顶 5,保持 importance 语义)。
|
|
1343
|
+
const priority = (m) => {
|
|
1344
|
+
if (m.type === "summary") return 0;
|
|
1345
|
+
if (m.type === "preference") return 1;
|
|
1346
|
+
if (isCoding && CODING_MEMORY_TYPES.has(m.type)) return 1;
|
|
1347
|
+
return 2;
|
|
1348
|
+
};
|
|
1349
|
+
const effImportance = (m) =>
|
|
1350
|
+
(isCoding && CODING_MEMORY_TYPES.has(m.type))
|
|
1351
|
+
? Math.min(5, m.importance * (config.codingBoostFactor ?? 2))
|
|
1352
|
+
: m.importance;
|
|
1353
|
+
const pa = priority(a);
|
|
1354
|
+
const pb = priority(b);
|
|
1355
|
+
return pa - pb ||
|
|
1356
|
+
(effImportance(b) * qualityWeight(b) * heatOf(b)) - (effImportance(a) * qualityWeight(a) * heatOf(a));
|
|
1357
|
+
});
|
|
1358
|
+
let candidates = items;
|
|
1359
|
+
if (config.hybridInject !== false && q) {
|
|
1360
|
+
// Bug4: semantic-first recall. Vector hits (queryVector, cached by the
|
|
1361
|
+
// injector's async prefetch) lead when present; otherwise the last
|
|
1362
|
+
// searchMemories recall for the exact same query is reused. Rule-based
|
|
1363
|
+
// items fill + dedupe the remaining slots. Empty query / no vector /
|
|
1364
|
+
// no cached recall → pure legacy rule-based selection.
|
|
1365
|
+
const semanticItems = [];
|
|
1366
|
+
if (Array.isArray(queryVector) && queryVector.length && vectorIndex) {
|
|
1367
|
+
try {
|
|
1368
|
+
const hits = vectorIndex.search(queryVector, { limit: poolSize, threshold: 0 });
|
|
1369
|
+
for (const m of hits) {
|
|
1370
|
+
if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten &&
|
|
1371
|
+
codingGate(m) &&
|
|
1372
|
+
(m.type === "summary" || m.type === "preference" || m.importance >= threshold)) {
|
|
1373
|
+
semanticItems.push(m);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
} catch { /* vector unavailable: fall through to the recall cache */ }
|
|
1377
|
+
}
|
|
1378
|
+
if (!semanticItems.length && lastSemanticRecall?.query === q && lastSemanticRecall.items?.length) {
|
|
1379
|
+
for (const m of lastSemanticRecall.items) {
|
|
1380
|
+
if (m && !m.archived && INJECT_TYPES.has(m.type) && !m.forgotten && codingGate(m)) semanticItems.push(m);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
// Issue #198:首轮(无向量、无缓存召回)的同步兜底——BM25 词法召回领位。
|
|
1384
|
+
// 注入渲染是同步的(宿主 systemPrompt 的 contexts 不支持异步 text),
|
|
1385
|
+
// 查询向量只能异步 prefetch 给下一轮,首轮必 miss;此时纯静态排序会让
|
|
1386
|
+
// 老的高重要性 summary/preference 占满槽位,当前话题的 decision/project
|
|
1387
|
+
// 进不来。查询文本本身就在手上,BM25 是纯进程内同步计算,词法相关性
|
|
1388
|
+
// 足以把当前话题顶到前排;门控与向量路径一致(含 importance 阈值)。
|
|
1389
|
+
// 语义向量命中时本分支不参与,行为不变。
|
|
1390
|
+
if (!semanticItems.length) {
|
|
1391
|
+
for (const hit of bm25Recall(q, poolSize)) {
|
|
1392
|
+
if (hit && !hit.archived && INJECT_TYPES.has(hit.type) && !hit.forgotten &&
|
|
1393
|
+
codingGate(hit) &&
|
|
1394
|
+
(hit.type === "summary" || hit.type === "preference" || hit.importance >= threshold)) {
|
|
1395
|
+
semanticItems.push(hit);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
if (semanticItems.length) {
|
|
1400
|
+
const seen = new Set();
|
|
1401
|
+
const merged = [];
|
|
1402
|
+
const push = (m) => {
|
|
1403
|
+
if (seen.has(m.id)) return;
|
|
1404
|
+
seen.add(m.id);
|
|
1405
|
+
merged.push(m);
|
|
1406
|
+
};
|
|
1407
|
+
for (const m of semanticItems) {
|
|
1408
|
+
push(m);
|
|
1409
|
+
if (merged.length >= poolSize) break;
|
|
1410
|
+
}
|
|
1411
|
+
for (const m of items) {
|
|
1412
|
+
if (merged.length >= poolSize) break;
|
|
1413
|
+
push(m);
|
|
1414
|
+
}
|
|
1415
|
+
candidates = merged;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
// Topic-ranked selection (v0.5.0 2.2): when the current query's vector is
|
|
1419
|
+
// available the whole candidate list is re-ordered by similarity to that
|
|
1420
|
+
// vector, so the injected slots go to memories on the current topic
|
|
1421
|
+
// rather than to the rule-based order. Rows the index did not return
|
|
1422
|
+
// keep their relative order after the scored ones.
|
|
1423
|
+
if (config?.selectiveInjectEnabled !== false && Array.isArray(queryVector) && queryVector.length && vectorIndex) {
|
|
1424
|
+
try {
|
|
1425
|
+
const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
|
|
1426
|
+
const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
|
|
1427
|
+
if (sim.size) {
|
|
1428
|
+
candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
|
|
1429
|
+
}
|
|
1430
|
+
} catch { /* topic re-rank unavailable: keep rule-based order */ }
|
|
1431
|
+
}
|
|
1432
|
+
// v0.8.0 A3(issue #17):strictScope 硬过滤同样作用于自动注入——scoped 记忆
|
|
1433
|
+
// 泄进无关注入上下文是最典型的越权通道,检索侧过滤挡不住这里。
|
|
1434
|
+
if (config?.strictScope === true && scope) {
|
|
1435
|
+
candidates = candidates.filter((m) => isVisibleInScope(m, scope));
|
|
1436
|
+
}
|
|
1437
|
+
// Issue #205:注入位跨轮轮换。rotate = 最近 N 轮注入过的 id 集合(由注入层
|
|
1438
|
+
// 按会话维护并传入):这些条目本轮不再优先——新鲜者前置(各自内部相对次序
|
|
1439
|
+
// 保持),不足时按原序回填,槽位数与 touchRecall 语义均不变。rotate 为空时
|
|
1440
|
+
// 行为与既有排序完全一致。
|
|
1441
|
+
if (rotate && rotate.size > 0 && candidates.length > 0) {
|
|
1442
|
+
const fresh = candidates.filter((m) => !rotate.has(m.id));
|
|
1443
|
+
if (fresh.length > 0) candidates = [...fresh, ...candidates.filter((m) => rotate.has(m.id))];
|
|
1444
|
+
}
|
|
1445
|
+
const selected = candidates.slice(0, maxItems);
|
|
1446
|
+
touchRecalled(selected);
|
|
1447
|
+
return selected;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
/**
|
|
1451
|
+
* Merge human edits parsed from a mirror file back into the store.
|
|
1452
|
+
* Only content/title are taken; structure fields stay machine-owned.
|
|
1453
|
+
*/
|
|
1454
|
+
function mergeHumanEdits(type, edits) {
|
|
1455
|
+
let applied = 0;
|
|
1456
|
+
for (const edit of edits) {
|
|
1457
|
+
if (!edit.id) continue; // corrupt/malformed edit: skip it, keep merging the rest
|
|
1458
|
+
const existing = store.getById(edit.id);
|
|
1459
|
+
if (!existing || existing.type !== type) continue;
|
|
1460
|
+
const patch = {};
|
|
1461
|
+
if (typeof edit.title === "string" && edit.title.trim()) patch.title = edit.title.trim();
|
|
1462
|
+
if (typeof edit.content === "string" && edit.content.trim()) patch.content = edit.content.trim();
|
|
1463
|
+
if (Object.keys(patch).length) {
|
|
1464
|
+
// 启动回灌(F-NEW-01):digest 存在且匹配 = 文件自渲染后无人触碰(旧机器
|
|
1465
|
+
// 镜像),机器 wins,DB 的 New 必须保留,静默改回 Old 是 bug。
|
|
1466
|
+
const digestMatches = typeof edit.digest === "string"
|
|
1467
|
+
&& typeof edit.title === "string"
|
|
1468
|
+
&& typeof edit.content === "string"
|
|
1469
|
+
&& createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
|
|
1470
|
+
if (digestMatches) continue;
|
|
1471
|
+
// 文件 == store(无实际变化)时不覆盖,也不计入 applied。
|
|
1472
|
+
const hasDiff = (patch.title !== undefined && existing.title !== patch.title)
|
|
1473
|
+
|| (patch.content !== undefined && existing.content !== patch.content);
|
|
1474
|
+
if (!hasDiff) continue;
|
|
1475
|
+
// 人工编辑回灌后触发 re-embed(issue #3 残留修复):向量必须与
|
|
1476
|
+
// 新 title/content 一致。scheduleEmbed 为 fire-and-forget,
|
|
1477
|
+
// 内部 try/catch 吞错,失败不影响主流程。
|
|
1478
|
+
// Bug5: human edits overwrite directly, but the machine version is
|
|
1479
|
+
// archived into content_history (source: human_override) before being
|
|
1480
|
+
// replaced, so a manual correction never silently destroys the old value.
|
|
1481
|
+
const merged = store.update(edit.id, {
|
|
1482
|
+
...patch,
|
|
1483
|
+
content_history: patch.content !== undefined && existing.content !== patch.content
|
|
1484
|
+
? pushContentHistory(existing, "human_override")
|
|
1485
|
+
: existing.content_history
|
|
1486
|
+
});
|
|
1487
|
+
applied++;
|
|
1488
|
+
scheduleEmbed(merged);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
if (applied) {
|
|
1492
|
+
afterSync("write");
|
|
1493
|
+
notifyWrite();
|
|
1494
|
+
}
|
|
1495
|
+
return applied;
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
/**
|
|
1499
|
+
* v0.8.0 冲突集中处理(issue 反馈:冻结冲突没有人工出口——store 的
|
|
1500
|
+
* resolveConflictPending 此前无任何 API/UI 调用)。人工确认一条待审冲突:
|
|
1501
|
+
* 盖章 resolved_at/resolved_winner(审计),可选按 dream 非冻结 conflict
|
|
1502
|
+
* 路径**同款**处置落地——复用 applyDecisions 的 conflict 分支,CAS 快照 +
|
|
1503
|
+
* 事务 + 胜者追加已否决注记 + 败者归档 + 幂等全部同源,不另写第二份裁决。
|
|
1504
|
+
*
|
|
1505
|
+
* @param {string} id conflict_pending 行 id
|
|
1506
|
+
* @param {{winner?: "a"|"b"|null, apply?: boolean}} opts
|
|
1507
|
+
* winner: 选哪一方保留(a = memory_a,冻结时 LLM 的建议胜者;b = memory_b);
|
|
1508
|
+
* null = 仅盖章标记已读、不落地处置。人工选择是权威裁决:传入
|
|
1509
|
+
* applyDecisions 的 config 关掉 trustEpistemicWeighting——可信度自动换位
|
|
1510
|
+
* 只应作用于 LLM 提议对,不能推翻人工选择。
|
|
1511
|
+
* @returns {object|undefined} 盖章后的冲突行 + disposition 摘要;未知 id 返回 undefined
|
|
1512
|
+
*/
|
|
1513
|
+
function resolveConflictPending(id, { winner = null, apply = true } = {}) {
|
|
1514
|
+
const rows = store.listConflictPending({ includeResolved: true, limit: 500 });
|
|
1515
|
+
const row = rows.find((r) => r.id === id);
|
|
1516
|
+
if (!row) return undefined;
|
|
1517
|
+
const winnerId = winner === "a" ? row.memory_a : winner === "b" ? row.memory_b : null;
|
|
1518
|
+
const loserId = winner === "a" ? row.memory_b : winner === "b" ? row.memory_a : null;
|
|
1519
|
+
let disposition = null;
|
|
1520
|
+
if (apply && winnerId && loserId) {
|
|
1521
|
+
const snapshot = new Map();
|
|
1522
|
+
for (const m of [store.getById(row.memory_a), store.getById(row.memory_b)]) {
|
|
1523
|
+
if (m) snapshot.set(m.id, { updated_at: m.updated_at, content: m.content, title: m.title });
|
|
1524
|
+
}
|
|
1525
|
+
// applyDecisions 需要一个 service 形状的参数(getById/update/setArchived/
|
|
1526
|
+
// transaction)——委托给闭包内的同名实现,mirror/通知/嵌入与主写路径同源。
|
|
1527
|
+
const applyService = {
|
|
1528
|
+
getById: (mid) => store.getById(mid),
|
|
1529
|
+
update: (mid, patch) => updateMemory(mid, patch),
|
|
1530
|
+
setArchived: (mid, v) => archiveMemory(mid, v),
|
|
1531
|
+
transaction: (fn) => transaction(fn)
|
|
1532
|
+
};
|
|
1533
|
+
const { committed, failures } = applyDecisions(
|
|
1534
|
+
[{ action: "conflict", winner: winnerId, loser: loserId, reason: row.reason ?? "" }],
|
|
1535
|
+
applyService,
|
|
1536
|
+
logger,
|
|
1537
|
+
snapshot,
|
|
1538
|
+
{ ...config, trustEpistemicWeighting: false }
|
|
1539
|
+
);
|
|
1540
|
+
// Review 发现:处置必须**先于**盖章。原实现先 resolveConflictPending 盖章、
|
|
1541
|
+
// 再 applyDecisions——若 CAS 拒掉(确认前双方被并发更新),行已 resolved 从
|
|
1542
|
+
// 队列消失、前端仍显示成功,审计却记了"已确认"且无法重试。现在失败时不盖章
|
|
1543
|
+
// 直接返回:行留在队列待重试,审计不被污染。
|
|
1544
|
+
if (failures.length) {
|
|
1545
|
+
return { ...row, disposition: { ok: false, failures } };
|
|
1546
|
+
}
|
|
1547
|
+
disposition = { ok: true, committed };
|
|
1548
|
+
}
|
|
1549
|
+
// 处置成功(或纯标记)后才盖章。幂等重放(败者已归档 → skipped)也走这里:
|
|
1550
|
+
// 处置本就存在,标记已审即可。
|
|
1551
|
+
const stamped = store.resolveConflictPending(id, { winner: winnerId });
|
|
1552
|
+
if (!stamped) return undefined;
|
|
1553
|
+
return { ...stamped, disposition };
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
/**
|
|
1557
|
+
* v0.8.0 冲突队列视图数据源:未解决冲突行,联表带出双方的当前状态(标题/
|
|
1558
|
+
* 内容/类型/重要性/归档标记),面板一处即可集中审阅,不必按徽章逐条找。
|
|
1559
|
+
* 参与记忆被删除/失联时该侧返回 {missing: true}(队列不因此丢行)。
|
|
1560
|
+
*/
|
|
1561
|
+
function listConflictQueue({ limit = 50, offset = 0 } = {}) {
|
|
1562
|
+
const rows = store.listConflictPending({ limit, offset, includeResolved: false });
|
|
1563
|
+
const side = (id) => {
|
|
1564
|
+
const m = store.getById(id);
|
|
1565
|
+
if (!m) return { id, missing: true };
|
|
1566
|
+
return {
|
|
1567
|
+
id,
|
|
1568
|
+
title: m.title,
|
|
1569
|
+
type: m.type,
|
|
1570
|
+
importance: m.importance,
|
|
1571
|
+
content: m.content,
|
|
1572
|
+
archived: m.archived === true,
|
|
1573
|
+
forgotten: m.forgotten === true
|
|
1574
|
+
};
|
|
1575
|
+
};
|
|
1576
|
+
return rows.map((r) => ({
|
|
1577
|
+
id: r.id,
|
|
1578
|
+
run_id: r.run_id ?? null,
|
|
1579
|
+
reason: r.reason ?? null,
|
|
1580
|
+
created_at: r.created_at,
|
|
1581
|
+
memory_a: side(r.memory_a),
|
|
1582
|
+
memory_b: side(r.memory_b)
|
|
1583
|
+
}));
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
function toApiList(rows) {
|
|
1587
|
+
return rows.map((m) => ({
|
|
1588
|
+
id: m.id,
|
|
1589
|
+
type: m.type,
|
|
1590
|
+
title: m.title,
|
|
1591
|
+
content: m.content,
|
|
1592
|
+
tags: m.tags,
|
|
1593
|
+
importance: m.importance,
|
|
1594
|
+
source: m.source,
|
|
1595
|
+
created_at: m.created_at,
|
|
1596
|
+
updated_at: m.updated_at,
|
|
1597
|
+
// v0.8.0 A2:scope 标注与事件发生时间透出——条件展开(未标注行不带键,
|
|
1598
|
+
// DTO 与 A2 前逐字节同形;带 undefined 键会被 in-process schema 校验
|
|
1599
|
+
// 判违规,JSON 序列化虽会丢弃但形状不稳定)。
|
|
1600
|
+
// v0.8.1 底座:scope 来源与决策时间随行透出(同样条件展开)。
|
|
1601
|
+
...(m.agent_scope !== undefined ? { agent_scope: m.agent_scope } : {}),
|
|
1602
|
+
...(m.workspace_scope !== undefined ? { workspace_scope: m.workspace_scope } : {}),
|
|
1603
|
+
...(m.agent_scope_source !== undefined ? { agent_scope_source: m.agent_scope_source } : {}),
|
|
1604
|
+
...(m.workspace_scope_source !== undefined ? { workspace_scope_source: m.workspace_scope_source } : {}),
|
|
1605
|
+
...(m.scope_decided_at !== undefined ? { scope_decided_at: m.scope_decided_at } : {}),
|
|
1606
|
+
...(m.sensitivity !== undefined ? { sensitivity: m.sensitivity } : {}),
|
|
1607
|
+
...(m.occurred_at !== undefined ? { occurred_at: m.occurred_at } : {})
|
|
1608
|
+
}));
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
/**
|
|
1612
|
+
* Three-way merge of in-flight human mirror edits before a re-render.
|
|
1613
|
+
* Runs on every syncMirror, so a human edit made between two store writes is
|
|
1614
|
+
* never silently overwritten by the next sync (human priority is not limited
|
|
1615
|
+
* to startup). Per edited entry:
|
|
1616
|
+
* - file changed only → human wins; the edit is merged back into the store.
|
|
1617
|
+
* - file AND store changed → real three-way conflict: keep the human edit
|
|
1618
|
+
* and append a marker preserving the store's concurrent version, so no
|
|
1619
|
+
* side is dropped.
|
|
1620
|
+
* - store changed only → store wins (the file is simply re-rendered).
|
|
1621
|
+
* Only title/content are taken (structure fields stay machine-owned, matching
|
|
1622
|
+
* mergeHumanEdits). Returns the memory list to render.
|
|
1623
|
+
*/
|
|
1624
|
+
function reconcileHumanEdits(memories) {
|
|
1625
|
+
if (!mirror) return memories;
|
|
1626
|
+
const byType = new Map();
|
|
1627
|
+
for (const m of memories) {
|
|
1628
|
+
if (!byType.has(m.type)) byType.set(m.type, []);
|
|
1629
|
+
byType.get(m.type).push(m);
|
|
1630
|
+
}
|
|
1631
|
+
const result = [];
|
|
1632
|
+
for (const type of Object.keys(TYPE_FILE)) {
|
|
1633
|
+
const list = byType.get(type) ?? [];
|
|
1634
|
+
if (list.length === 0) continue;
|
|
1635
|
+
const editsById = new Map(mirror.readHumanEdits(type).map((e) => [e.id, e]));
|
|
1636
|
+
for (const m of list) {
|
|
1637
|
+
const edit = editsById.get(m.id);
|
|
1638
|
+
if (!edit) { result.push(m); continue; }
|
|
1639
|
+
const humanChanged = (typeof edit.title === "string" && edit.title !== m.title)
|
|
1640
|
+
|| (typeof edit.content === "string" && edit.content !== m.content);
|
|
1641
|
+
if (!humanChanged) { result.push(m); continue; }
|
|
1642
|
+
// 判断文件是否被人工动过:digest 存在且匹配则无人触碰,否则视为人工动过。
|
|
1643
|
+
// digest 是渲染时对 sha256(title \x00 content) 的记录;机器 store 更新后
|
|
1644
|
+
// 镜像还没重渲染时读到旧内容,digest 仍匹配 → 机器 wins,不会误判为
|
|
1645
|
+
// 并发人工编辑导致机器写丢失 + 伪冲突标记。
|
|
1646
|
+
const digestMatches = typeof edit.digest === "string"
|
|
1647
|
+
&& typeof edit.title === "string"
|
|
1648
|
+
&& typeof edit.content === "string"
|
|
1649
|
+
&& createHash("sha256").update(`${edit.title}\x00${edit.content}`).digest("hex") === edit.digest;
|
|
1650
|
+
if (digestMatches) {
|
|
1651
|
+
// 无人触碰,机器 wins,走原样
|
|
1652
|
+
result.push(m);
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
// 人工动过(digest 不存在=老文件/手工文件保守视为人工动过),走三方合并
|
|
1656
|
+
// (保留现有 storeChanged 逻辑)
|
|
1657
|
+
const storeChanged = edit.updated_at !== undefined && m.updated_at !== edit.updated_at;
|
|
1658
|
+
if (storeChanged) {
|
|
1659
|
+
// 三方合并保留双方时的冲突批注:随实例语言,写进记忆正文。
|
|
1660
|
+
const marker = STR.serviceConflictMarker[language](m.updated_at, m.content);
|
|
1661
|
+
store.update(m.id, { title: edit.title, content: `${edit.content}${marker}` });
|
|
1662
|
+
} else {
|
|
1663
|
+
store.update(m.id, { title: edit.title, content: edit.content });
|
|
1664
|
+
}
|
|
1665
|
+
const merged = store.getById(m.id);
|
|
1666
|
+
scheduleEmbed(merged);
|
|
1667
|
+
result.push(merged);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
return result;
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
/**
|
|
1674
|
+
* Re-render the human-editable mirror after any store mutation, merging any
|
|
1675
|
+
* in-flight human edits first (never silently overwriting them). Only
|
|
1676
|
+
* non-forgotten memories are mirrored: forgotten entries must not reach the
|
|
1677
|
+
* human-editable file (a human "edit" could otherwise resurrect them).
|
|
1678
|
+
*/
|
|
1679
|
+
// syncMirror: 同步 mirror,并在失败/成功时持久记录 dirty 状态;保证自身不抛出。
|
|
1680
|
+
// v0.3.6(audit peer 4 阻断):
|
|
1681
|
+
// - 开始时 incrementGeneration 绑定本次期望轮次 gen;成功用
|
|
1682
|
+
// markMirrorCleanForGeneration(gen, now) CAS/fence 清 dirty——旧 worker
|
|
1683
|
+
// (gen 已过期)不会误清另一 worker 未恢复的故障债务;
|
|
1684
|
+
// - 失败写 markMirrorDirty(递增 desired 绑定新债务),下次 recover 恢复;
|
|
1685
|
+
// - 逐 type 用 setTypeStatus 记录部分成功/失败(type_status JSON);
|
|
1686
|
+
// - 所有 store 状态写入各自 try/catch,失败只 warn,绝不向外抛(F-NEW-03)。
|
|
1687
|
+
function syncMirror() {
|
|
1688
|
+
if (txDepth > 0 || !mirror) return { success: true, deferred: true }; // deferred to the transaction's commit
|
|
1689
|
+
const now = new Date().toISOString();
|
|
1690
|
+
let gen;
|
|
1691
|
+
try {
|
|
1692
|
+
// desired generation 已在业务写事务中原子递增(peer blocker 1);这里
|
|
1693
|
+
// 直接读当前值作为本次同步的目标轮次,不再自行 incrementGeneration。
|
|
1694
|
+
const state = store.getMirrorState();
|
|
1695
|
+
gen = state?.generation ?? 0;
|
|
1696
|
+
} catch (stateError) {
|
|
1697
|
+
logger?.warn?.("syncMirror: getMirrorState failed:", stateError);
|
|
1698
|
+
return { success: false, error: stateError?.message ?? String(stateError) };
|
|
1699
|
+
}
|
|
1700
|
+
// coveredTypes 提到 try 外初始化:即使 store.list 先抛错,catch 分支也有
|
|
1701
|
+
// 合法的空 Set 可迭代,保证 syncMirror 自身绝不抛(fail-safe)。
|
|
1702
|
+
const coveredTypes = new Set();
|
|
1703
|
+
try {
|
|
1704
|
+
// 预先获取本次要覆盖的 type 集合(只调一次 store.list)
|
|
1705
|
+
const list = store.list({ limit: 500, includeForgotten: false });
|
|
1706
|
+
for (const memory of list) {
|
|
1707
|
+
if (memory?.type && TYPE_FILE[memory.type]) {
|
|
1708
|
+
coveredTypes.add(memory.type);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
// Per-type physical outcome (audit peer D): mirror.sync writes each type
|
|
1713
|
+
// file independently and reports per-type success/failure. A type whose
|
|
1714
|
+
// file was physically committed must be marked committed even when a
|
|
1715
|
+
// sibling type errors — the old code batch-failed every type on any error,
|
|
1716
|
+
// leaving committed files mislabeled as failed and masking partial state.
|
|
1717
|
+
// Absent entries (a type with no memories) count as success: sync prunes
|
|
1718
|
+
// the stale file, which is itself a completed physical state.
|
|
1719
|
+
let allOk = true;
|
|
1720
|
+
const results = mirror.sync(reconcileHumanEdits(list)) ?? {};
|
|
1721
|
+
for (const type of Object.keys(TYPE_FILE)) {
|
|
1722
|
+
const r = results[type];
|
|
1723
|
+
const ok = !r || r.ok === true;
|
|
1724
|
+
if (!ok) allOk = false;
|
|
1725
|
+
try {
|
|
1726
|
+
if (ok) {
|
|
1727
|
+
store.setTypeStatus(type, { status: "committed", applied_gen: gen, last_error: null });
|
|
1728
|
+
} else {
|
|
1729
|
+
store.setTypeStatus(type, { status: "failed", last_error: r.error ?? "mirror sync failed" });
|
|
1730
|
+
}
|
|
1731
|
+
} catch (stateError) {
|
|
1732
|
+
logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
// 全部 type 物理收敛:CAS/fence 绑定到本地 gen,旧 worker(gen 已过期)会被
|
|
1737
|
+
// 拦截。此步失败说明核心 clean 状态没写成功,向上层报失败(不再静默)。
|
|
1738
|
+
if (allOk) {
|
|
1739
|
+
try {
|
|
1740
|
+
store.markMirrorCleanForGeneration(gen, now);
|
|
1741
|
+
} catch (stateError) {
|
|
1742
|
+
logger?.warn?.("syncMirror: markMirrorCleanForGeneration failed:", stateError);
|
|
1743
|
+
return { success: false, error: stateError?.message ?? String(stateError) };
|
|
1744
|
+
}
|
|
1745
|
+
return { success: true };
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
// 部分 type 失败:持久 dirty(债务绑定到新轮次),下次 recover 只补未收敛
|
|
1749
|
+
// 的 type。committed 的 type 已应用本轮 gen,不因兄弟失败被回滚。
|
|
1750
|
+
const failedTypes = Object.entries(results)
|
|
1751
|
+
.filter(([, r]) => r && r.ok === false)
|
|
1752
|
+
.map(([t]) => t);
|
|
1753
|
+
try {
|
|
1754
|
+
store.markMirrorDirty(`mirror sync failed for: ${failedTypes.join(", ")}`, now);
|
|
1755
|
+
} catch (stateError) {
|
|
1756
|
+
logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
|
|
1757
|
+
}
|
|
1758
|
+
return { success: false, error: `mirror sync failed for: ${failedTypes.join(", ")}` };
|
|
1759
|
+
} catch (error) {
|
|
1760
|
+
const errMsg = error?.message ?? String(error);
|
|
1761
|
+
logger?.warn?.("syncMirror failed:", error);
|
|
1762
|
+
try {
|
|
1763
|
+
// 债务绑定到新的一轮(desired generation 原子递增;即便 dirty 写失败,
|
|
1764
|
+
// generation 已推进,recoverMirror 仍能捕获,不产生 false-clean)。
|
|
1765
|
+
store.markMirrorDirty(errMsg, now);
|
|
1766
|
+
} catch (stateError) {
|
|
1767
|
+
logger?.warn?.("syncMirror: markMirrorDirty failed:", stateError);
|
|
1768
|
+
}
|
|
1769
|
+
// 逐 type 标记为 failed(applied_gen 不动)
|
|
1770
|
+
for (const type of coveredTypes) {
|
|
1771
|
+
try {
|
|
1772
|
+
store.setTypeStatus(type, { status: "failed", last_error: errMsg });
|
|
1773
|
+
} catch (stateError) {
|
|
1774
|
+
logger?.warn?.(`syncMirror: setTypeStatus(${type}) failed:`, stateError);
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return { success: false, error: errMsg };
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// afterSync: run syncMirror and surface a failure to the operator instead of
|
|
1782
|
+
// swallowing it (peer blocker 2 + audit peer B). The mirror debt has already
|
|
1783
|
+
// been persisted by markMirrorDirty inside syncMirror, so a restart recovers —
|
|
1784
|
+
// but the calling write path must not report clean while the mirror is
|
|
1785
|
+
// known-stale. Returns the sync result so the caller can attach an explicit
|
|
1786
|
+
// degraded/pending receipt to its return value instead of faking success.
|
|
1787
|
+
function afterSync(label) {
|
|
1788
|
+
const r = syncMirror();
|
|
1789
|
+
if (!r?.success && !r?.deferred) {
|
|
1790
|
+
logger?.warn?.(`${label}: mirror sync failed (will recover on restart):`, r?.error);
|
|
1791
|
+
}
|
|
1792
|
+
return r;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
// recoverMirror: 启动/手动 reconcile 时根据持久 dirty 状态决定是否恢复同步
|
|
1796
|
+
// (F-NEW-03 + v0.3.6)。触发条件不只是 dirty——还检查
|
|
1797
|
+
// generation > applied_generation(有未应用的债务),这样 COMMIT→dirty 崩溃
|
|
1798
|
+
// 窗口(DB 提交后、markMirrorDirty/clean 前进程退出 → dirty=false 但
|
|
1799
|
+
// generation 不一致)也能被捕获。有界重试(最多 3 次)重跑 syncMirror 收敛;
|
|
1800
|
+
// 某次成功后 dirty=false 且无更新债务(generation <= applied_generation)
|
|
1801
|
+
// 立即停止。返回 { recovered, error } 供 index.js 启动 / api.js health 判断。
|
|
1802
|
+
// 一切 fail-safe,绝不向外抛。
|
|
1803
|
+
function recoverMirror() {
|
|
1804
|
+
const MAX_ATTEMPTS = 3;
|
|
1805
|
+
let lastError = null;
|
|
1806
|
+
let recovered = false;
|
|
1807
|
+
|
|
1808
|
+
try {
|
|
1809
|
+
const state = store.getMirrorState();
|
|
1810
|
+
// 崩溃窗口检测:dirty 或 generation > applied_generation(COMMIT→dirty 窗口)
|
|
1811
|
+
if (!state?.dirty && !(state.generation > state.applied_generation)) {
|
|
1812
|
+
// 本来就干净:无需恢复,视为成功
|
|
1813
|
+
return { recovered: true, error: null };
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
// 有 dirty 或有未应用债务:最多尝试 3 次 sync
|
|
1817
|
+
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
1818
|
+
try {
|
|
1819
|
+
syncMirror(); // syncMirror 内部已 catch,不会向外抛
|
|
1820
|
+
const currentState = store.getMirrorState();
|
|
1821
|
+
// 成功条件:dirty 为 false 且没有更新一轮的债务
|
|
1822
|
+
// (generation <= applied_generation,恢复后由 syncMirror 里
|
|
1823
|
+
// markMirrorCleanForGeneration 自动把 applied 跟上)
|
|
1824
|
+
if (!currentState?.dirty && currentState.generation <= currentState.applied_generation) {
|
|
1825
|
+
recovered = true;
|
|
1826
|
+
lastError = null;
|
|
1827
|
+
break;
|
|
1828
|
+
}
|
|
1829
|
+
// 仍 dirty 或仍有更新债务:记录最后一次错误供重试耗尽后上报。
|
|
1830
|
+
// 注意:若别的 worker 又失败产生新债务(dirty 仍 true),这是"新债务"
|
|
1831
|
+
// 不是本次失败,继续重试直到耗尽次数。
|
|
1832
|
+
lastError = currentState.last_error || `Sync attempt ${attempt + 1} left mirror dirty or has pending debt`;
|
|
1833
|
+
} catch (syncError) {
|
|
1834
|
+
// syncMirror 理论不抛,fail-safe 兜底
|
|
1835
|
+
const errMsg = syncError?.message ?? String(syncError);
|
|
1836
|
+
logger?.warn?.("recoverMirror: sync attempt failed:", errMsg);
|
|
1837
|
+
lastError = errMsg;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
if (!recovered) {
|
|
1842
|
+
logger?.warn?.("dsh-mneme mirror: recover failed after", MAX_ATTEMPTS, "attempts");
|
|
1843
|
+
} else {
|
|
1844
|
+
logger?.warn?.("dsh-mneme mirror: recovered from dirty/pending state");
|
|
1845
|
+
}
|
|
1846
|
+
} catch (error) {
|
|
1847
|
+
// fail-safe:任何意外异常不向外抛
|
|
1848
|
+
lastError = error?.message ?? String(error);
|
|
1849
|
+
logger?.warn?.("dsh-mneme mirror: recover failed with unexpected error:", error);
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
return { recovered, error: recovered ? null : lastError };
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
// getMirrorHealth: 暴露 mirror 同步健康状态,供 api.js /health 使用
|
|
1856
|
+
// (F-NEW-03)。把 DB 的 dirty 0/1 转成 boolean;fail-safe,绝不向外抛。
|
|
1857
|
+
function getMirrorHealth() {
|
|
1858
|
+
try {
|
|
1859
|
+
const state = store.getMirrorState();
|
|
1860
|
+
if (!state) {
|
|
1861
|
+
// 无状态行:返回安全默认值
|
|
1862
|
+
return {
|
|
1863
|
+
dirty: false,
|
|
1864
|
+
last_error: null,
|
|
1865
|
+
last_attempt: null,
|
|
1866
|
+
success_at: null
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
return {
|
|
1870
|
+
dirty: Boolean(state.dirty),
|
|
1871
|
+
last_error: state.last_error ?? null,
|
|
1872
|
+
last_attempt: state.last_attempt ?? null,
|
|
1873
|
+
success_at: state.success_at ?? null
|
|
1874
|
+
};
|
|
1875
|
+
} catch (error) {
|
|
1876
|
+
// fail-safe:状态读取失败也不向外抛,但必须显式表达"未知"而非伪装成
|
|
1877
|
+
// 干净(peer blocker 5:真实读取失败要显式 unknown,不得归一为 dirty:false)。
|
|
1878
|
+
logger?.warn?.("getMirrorHealth failed:", error);
|
|
1879
|
+
return {
|
|
1880
|
+
dirty: null,
|
|
1881
|
+
last_error: error?.message ?? String(error),
|
|
1882
|
+
last_attempt: null,
|
|
1883
|
+
success_at: null
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
// 返回字面量与内部裁决器(resolveConflictPending → applyDecisions 的 conflict
|
|
1889
|
+
// 处置)共用的写路径:mirror 同步、写通知、嵌入调度全部同源,不能各写一份。
|
|
1890
|
+
function updateMemory(id, p, ctx = {}) {
|
|
1891
|
+
const old = store.getById(id);
|
|
1892
|
+
// Issue #135 附属发现 2:质量过滤器把「为什么被降权/归档」写在系统信号标签
|
|
1893
|
+
// 上(SIGNAL_TAGS,applyQualityDisposition 以并集写入),而这里整组替换
|
|
1894
|
+
// tags——任何带 tags 的更新都会抹掉这条唯一的审计线索(报告实测 150 条低分
|
|
1895
|
+
// 记忆里恰好缺的 2 条就是被 update 过的,并因此误判过归档来源)。把 existing
|
|
1896
|
+
// 的系统信号标签并集保留;用户自传的标签照常生效。
|
|
1897
|
+
let patch = (p && Array.isArray(p.tags) && old && Array.isArray(old.tags))
|
|
1898
|
+
? { ...p, tags: [...new Set([...p.tags, ...old.tags.filter((t) => SIGNAL_TAGS.includes(t))])] }
|
|
1899
|
+
: p;
|
|
1900
|
+
// v0.8.1 底座(issue #170):显式 scope 修正。patch 携带 agent_scope /
|
|
1901
|
+
// workspace_scope 键(undefined=该维不动)时归一化并盖 explicit 章 +
|
|
1902
|
+
// scope_decided_at,随后写 scope_changes 审计行(actor:tool=模型侧 /
|
|
1903
|
+
// panel=人工侧)。审计失败只 warn,不反噬主写入。
|
|
1904
|
+
const nextAgentScope = p && p.agent_scope !== undefined ? normalizeExplicitScope(p.agent_scope) : undefined;
|
|
1905
|
+
const nextWorkspaceScope = p && p.workspace_scope !== undefined ? normalizeExplicitScope(p.workspace_scope) : undefined;
|
|
1906
|
+
const scopeChanged = nextAgentScope !== undefined || nextWorkspaceScope !== undefined;
|
|
1907
|
+
if (scopeChanged) {
|
|
1908
|
+
const decidedAt = new Date().toISOString();
|
|
1909
|
+
patch = { ...patch };
|
|
1910
|
+
if (nextAgentScope !== undefined) {
|
|
1911
|
+
patch.agent_scope = nextAgentScope;
|
|
1912
|
+
patch.agent_scope_source = "explicit";
|
|
1913
|
+
}
|
|
1914
|
+
if (nextWorkspaceScope !== undefined) {
|
|
1915
|
+
patch.workspace_scope = nextWorkspaceScope;
|
|
1916
|
+
patch.workspace_scope_source = "explicit";
|
|
1917
|
+
}
|
|
1918
|
+
patch.scope_decided_at = decidedAt;
|
|
1919
|
+
}
|
|
1920
|
+
const updated = store.update(id, patch);
|
|
1921
|
+
if (scopeChanged && old && updated) {
|
|
1922
|
+
try {
|
|
1923
|
+
store.saveScopeChange({
|
|
1924
|
+
memory_id: id,
|
|
1925
|
+
actor: ctx.actor === "panel" ? "panel" : "tool",
|
|
1926
|
+
prev_agent_scope: old.agent_scope ?? null,
|
|
1927
|
+
prev_workspace_scope: old.workspace_scope ?? null,
|
|
1928
|
+
next_agent_scope: updated.agent_scope ?? null,
|
|
1929
|
+
next_workspace_scope: updated.workspace_scope ?? null,
|
|
1930
|
+
agent_scope_source: updated.agent_scope_source ?? null,
|
|
1931
|
+
workspace_scope_source: updated.workspace_scope_source ?? null,
|
|
1932
|
+
decided_at: patch.scope_decided_at
|
|
1933
|
+
});
|
|
1934
|
+
} catch (e) {
|
|
1935
|
+
try { ctx.logger?.warn?.(`[dsh-mneme] scope change audit failed: ${String(e)}`); } catch { /* 同样不反噬 */ }
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
// Record a user correction when any meaningful field changed and the
|
|
1939
|
+
// reflection failure tracker is enabled. expected = what it became,
|
|
1940
|
+
// actual = what it was before; query (when provided) captures the
|
|
1941
|
+
// user's original intent so later reflection can reason about recall.
|
|
1942
|
+
const hasMeaningfulChange = old && updated && (
|
|
1943
|
+
old.content !== updated.content ||
|
|
1944
|
+
old.title !== updated.title ||
|
|
1945
|
+
old.importance !== updated.importance
|
|
1946
|
+
);
|
|
1947
|
+
if (hasMeaningfulChange && config.reflectionFailureTracking) {
|
|
1948
|
+
store.saveFailure({
|
|
1949
|
+
id: randomUUID(),
|
|
1950
|
+
query: ctx.query ?? null,
|
|
1951
|
+
expected: updated.content,
|
|
1952
|
+
actual: old.content,
|
|
1953
|
+
before: { title: old.title, content: old.content, importance: old.importance },
|
|
1954
|
+
failure_type: "user_correction",
|
|
1955
|
+
memory_id: id
|
|
1956
|
+
});
|
|
1957
|
+
}
|
|
1958
|
+
const sync = afterSync("write");
|
|
1959
|
+
notifyWrite();
|
|
1960
|
+
scheduleEmbed(updated);
|
|
1961
|
+
// Audit peer B: when the mirror sync failed, the store write landed but
|
|
1962
|
+
// the mirror did not converge — return an explicit degraded receipt rather
|
|
1963
|
+
// than a plain success. Non-enumerable so existing deepEqual assertions on
|
|
1964
|
+
// the memory shape keep passing.
|
|
1965
|
+
if (!sync?.success && !sync?.deferred) {
|
|
1966
|
+
Object.defineProperty(updated, "_mirror", {
|
|
1967
|
+
value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
|
|
1968
|
+
enumerable: false,
|
|
1969
|
+
configurable: true
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
return updated;
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
function archiveMemory(id, f) {
|
|
1976
|
+
const updated = store.setArchived(id, f);
|
|
1977
|
+
afterSync("write");
|
|
1978
|
+
return updated;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
return {
|
|
1982
|
+
saveWithDedupe,
|
|
1983
|
+
recoverMirror,
|
|
1984
|
+
getMirrorHealth,
|
|
1985
|
+
getMirrorState: () => store.getMirrorState(),
|
|
1986
|
+
injectCandidates,
|
|
1987
|
+
mergeHumanEdits,
|
|
1988
|
+
toApiList,
|
|
1989
|
+
isVisibleInScope,
|
|
1990
|
+
transaction,
|
|
1991
|
+
enqueue,
|
|
1992
|
+
setDreamHook(fn) { dreamHook = fn; },
|
|
1993
|
+
setSleepHook(fn) { sleepHook = fn; },
|
|
1994
|
+
setEmbedder(emb) {
|
|
1995
|
+
embedder = emb;
|
|
1996
|
+
if (!emb) {
|
|
1997
|
+
// embedder removed (init failed in index.js): stop polling and drop
|
|
1998
|
+
// queued re-embeds — search just degrades to keyword.
|
|
1999
|
+
stopEmbedReadyPolling();
|
|
2000
|
+
embedPending = [];
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
if (emb.ready === true) {
|
|
2004
|
+
flushEmbedPending();
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
// Async-initializing embedder: poll `ready` until it flips, then flush.
|
|
2008
|
+
if ("ready" in emb && embedReadyTimer === null) {
|
|
2009
|
+
let attempts = 0;
|
|
2010
|
+
embedReadyTimer = setInterval(() => {
|
|
2011
|
+
attempts++;
|
|
2012
|
+
if (emb.ready === true || attempts >= EMBED_READY_POLL_LIMIT) {
|
|
2013
|
+
stopEmbedReadyPolling();
|
|
2014
|
+
if (emb.ready === true) flushEmbedPending();
|
|
2015
|
+
else embedPending = []; // init never landed: drop the queue
|
|
2016
|
+
}
|
|
2017
|
+
}, EMBED_READY_POLL_MS);
|
|
2018
|
+
}
|
|
2019
|
+
},
|
|
2020
|
+
setEntityExtractor(fn) { entityExtractor = fn; },
|
|
2021
|
+
setVectorIndex(vi) { vectorIndex = vi; },
|
|
2022
|
+
setReranker(rn) { reranker = rn; },
|
|
2023
|
+
setRecallRecorder(fn) { recallRecorder = fn; },
|
|
2024
|
+
searchMemories,
|
|
2025
|
+
// recallStats(#217)实现在 src/recall-stats.js:service.js 过 2000 行参考线,
|
|
2026
|
+
// 新内聚块独立成模块(AGENTS.md 尺寸约定);这里只留 barrel 出口,调用方
|
|
2027
|
+
// (api 层)零改动。纯读聚合,见模块注释的口径说明。
|
|
2028
|
+
recallStats: (options) => recallStats(store, options),
|
|
2029
|
+
embedQuery,
|
|
2030
|
+
findSessionDuplicate,
|
|
2031
|
+
evaluateRetrieval,
|
|
2032
|
+
computeRetrievalMetrics,
|
|
2033
|
+
// passthroughs used by tools and api layers; mutations keep the mirror in sync
|
|
2034
|
+
search: (q, o) => store.search(q, o),
|
|
2035
|
+
searchVector: (v, o) => store.searchVector(v, o),
|
|
2036
|
+
embeddedCount: () => store.embeddedCount(),
|
|
2037
|
+
list: (o) => store.list(o),
|
|
2038
|
+
all: () => store.all(),
|
|
2039
|
+
count: (type, opts) => store.count(type, opts),
|
|
2040
|
+
getById: (id) => store.getById(id),
|
|
2041
|
+
remove: (id) => {
|
|
2042
|
+
store.remove(id);
|
|
2043
|
+
afterSync("write");
|
|
2044
|
+
notifyWrite();
|
|
2045
|
+
},
|
|
2046
|
+
update: updateMemory,
|
|
2047
|
+
// v0.8.1 底座:scope 归属修正审计(单条记忆,新→旧)。
|
|
2048
|
+
listScopeChanges: (memoryId, opts) => store.listScopeChanges(memoryId, opts),
|
|
2049
|
+
// Compare-and-set update: applies the patch only when the row still carries
|
|
2050
|
+
// `expectedUpdatedAt`. Returns undefined on a miss (no write) so the caller
|
|
2051
|
+
// can re-read and retry — the primitive that prevents lost updates across
|
|
2052
|
+
// concurrent read-modify-write (see scripts/stress-dsh.js axis 3).
|
|
2053
|
+
compareAndUpdate: (id, expectedUpdatedAt, patch, ctx = {}) => {
|
|
2054
|
+
const old = store.getById(id);
|
|
2055
|
+
const updated = store.compareAndUpdate(id, expectedUpdatedAt, patch);
|
|
2056
|
+
if (updated === undefined) return undefined; // CAS miss: no write, no side effects
|
|
2057
|
+
const hasMeaningfulChange = old && updated && (
|
|
2058
|
+
old.content !== updated.content ||
|
|
2059
|
+
old.title !== updated.title ||
|
|
2060
|
+
old.importance !== updated.importance
|
|
2061
|
+
);
|
|
2062
|
+
if (hasMeaningfulChange && config.reflectionFailureTracking) {
|
|
2063
|
+
store.saveFailure({
|
|
2064
|
+
id: randomUUID(),
|
|
2065
|
+
query: ctx.query ?? null,
|
|
2066
|
+
expected: updated.content,
|
|
2067
|
+
actual: old.content,
|
|
2068
|
+
before: { title: old.title, content: old.content, importance: old.importance },
|
|
2069
|
+
failure_type: "user_correction",
|
|
2070
|
+
memory_id: id
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
const sync = afterSync("write");
|
|
2074
|
+
notifyWrite();
|
|
2075
|
+
scheduleEmbed(updated);
|
|
2076
|
+
// Audit peer B: mirror sync failure on a CAS write must surface too.
|
|
2077
|
+
if (!sync?.success && !sync?.deferred) {
|
|
2078
|
+
Object.defineProperty(updated, "_mirror", {
|
|
2079
|
+
value: { status: "degraded", error: sync?.error ?? "mirror sync failed" },
|
|
2080
|
+
enumerable: false,
|
|
2081
|
+
configurable: true
|
|
2082
|
+
});
|
|
2083
|
+
}
|
|
2084
|
+
return updated;
|
|
2085
|
+
},
|
|
2086
|
+
setForget: (id, f) => {
|
|
2087
|
+
const updated = store.setForget(id, f);
|
|
2088
|
+
afterSync("write");
|
|
2089
|
+
return updated;
|
|
2090
|
+
},
|
|
2091
|
+
setArchived: archiveMemory,
|
|
2092
|
+
// sleep-mode storage (v0.4.0). demoteToSummary / restoreContent mutate
|
|
2093
|
+
// content so they ride the normal write-hook path (mirror re-renders).
|
|
2094
|
+
// touchLastAccess is a read-stamp — deliberately NO write hook (a recall
|
|
2095
|
+
// must not dirty the mirror). getUnrecalledSince is a pure read.
|
|
2096
|
+
demoteToSummary: (id, summary, opts) => {
|
|
2097
|
+
const updated = store.demoteToSummary(id, summary, opts);
|
|
2098
|
+
afterSync("write");
|
|
2099
|
+
return updated;
|
|
2100
|
+
},
|
|
2101
|
+
restoreContent: (id) => {
|
|
2102
|
+
const updated = store.restoreContent(id);
|
|
2103
|
+
afterSync("write");
|
|
2104
|
+
return updated;
|
|
2105
|
+
},
|
|
2106
|
+
touchLastAccess: (id, at) => store.touchLastAccess(id, at),
|
|
2107
|
+
getUnrecalledSince: (cutMs, opts) => store.getUnrecalledSince(cutMs, opts),
|
|
2108
|
+
// autoDream audit trail: passthroughs deliberately bypass write hooks —
|
|
2109
|
+
// an audit write is bookkeeping, and notifyWrite would loop back into the
|
|
2110
|
+
// dream scheduler that just recorded the run.
|
|
2111
|
+
saveDreamRun: (run) => store.saveDreamRun(run),
|
|
2112
|
+
getDreamRun: (id) => store.getDreamRun(id),
|
|
2113
|
+
listDreamRuns: (opts) => store.listDreamRuns(opts),
|
|
2114
|
+
// Per-record receipt chain (same bookkeeping semantics as saveDreamRun: an
|
|
2115
|
+
// audit write, never a write-hook-triggering memory mutation).
|
|
2116
|
+
saveReceipt: (r) => store.saveReceipt(r),
|
|
2117
|
+
getReceipt: (id) => store.getReceipt(id),
|
|
2118
|
+
listReceipts: (opts) => store.listReceipts(opts),
|
|
2119
|
+
// Conflict freeze bookkeeping (same semantics as the audit passthroughs
|
|
2120
|
+
// above: an audit write, never a write-hook-triggering memory mutation).
|
|
2121
|
+
saveConflictPending: (r) => store.saveConflictPending(r),
|
|
2122
|
+
listConflictPending: (opts) => store.listConflictPending(opts),
|
|
2123
|
+
listConflictQueue,
|
|
2124
|
+
resolveConflictPending,
|
|
2125
|
+
countConflictPending: () => store.countConflictPending(),
|
|
2126
|
+
// Recall evaluation trail (方案 B): audit-bookkeeping semantics like the
|
|
2127
|
+
// dream/recall passthroughs above — a recall_evals write is a snapshot, not
|
|
2128
|
+
// a memory mutation, so it never triggers write hooks.
|
|
2129
|
+
saveRecallEval: (r) => store.saveRecallEval(r),
|
|
2130
|
+
getRecallEval: (id) => store.getRecallEval(id),
|
|
2131
|
+
listRecallEvals: (opts) => store.listRecallEvals(opts),
|
|
2132
|
+
// LLM audit trail (Bug8): bookkeeping semantics like the recall/dream
|
|
2133
|
+
// passthroughs — a saveLlmAudit write never triggers write hooks.
|
|
2134
|
+
saveLlmAudit: (entry) => store.saveLlmAudit(entry),
|
|
2135
|
+
listLlmAudits: (opts) => store.listLlmAudits(opts),
|
|
2136
|
+
countLlmAudits: (opts) => store.countLlmAudits(opts),
|
|
2137
|
+
getLlmAuditStats: (opts) => store.getLlmAuditStats(opts),
|
|
2138
|
+
deleteOldLlmAudits: (before) => store.deleteOldLlmAudits(before),
|
|
2139
|
+
// Entity gene (v0.3.0) passthroughs for the autoDream apply path
|
|
2140
|
+
// (applyDecisions): records supersedes relations after an update and
|
|
2141
|
+
// migrates entity_attrs on merge. Bookkeeping writes like the audit
|
|
2142
|
+
// passthroughs above — never write-hook-triggering memory mutations.
|
|
2143
|
+
saveRelation: (r) => store.saveRelation(r),
|
|
2144
|
+
listEntities: (o) => store.listEntities(o),
|
|
2145
|
+
getRelations: (id) => store.getRelations(id),
|
|
2146
|
+
// v0.7.0 实体热投影:实体热 = 关联记忆 heat 聚合(取 max)。无关联记忆
|
|
2147
|
+
// 或 heatEnabled=false 时返回 null;前端据此决定图谱节点大小/明暗。
|
|
2148
|
+
entityHeat: (entityId) => {
|
|
2149
|
+
if (config.heatEnabled === false) return null;
|
|
2150
|
+
const rels = store.getRelations(entityId) ?? [];
|
|
2151
|
+
let max = -Infinity;
|
|
2152
|
+
for (const rel of rels) {
|
|
2153
|
+
if (!rel.memory_id) continue;
|
|
2154
|
+
const mem = store.getById(rel.memory_id);
|
|
2155
|
+
if (!mem) continue;
|
|
2156
|
+
const h = computeHeat(mem, Date.now(), config);
|
|
2157
|
+
if (h > max) max = h;
|
|
2158
|
+
}
|
|
2159
|
+
return max === -Infinity ? null : max;
|
|
2160
|
+
},
|
|
2161
|
+
saveAttr: (r) => store.saveAttr(r),
|
|
2162
|
+
createEntity: (r) => store.createEntity(r),
|
|
2163
|
+
findEntityByName: (n) => store.findEntityByName(n),
|
|
2164
|
+
findEntityById: (id) => store.findEntityById(id),
|
|
2165
|
+
getAttrsByMemory: (id) => store.getAttrsByMemory(id),
|
|
2166
|
+
// 记忆详情侧栏:一条记忆关联到的实体(entity_attrs.memory_id 反查,纯读)。
|
|
2167
|
+
entitiesForMemory: (id) => store.entitiesForMemory(id),
|
|
2168
|
+
getCurrentAttrs: (id) => store.getCurrentAttrs(id),
|
|
2169
|
+
migrateAttrsToMemory: (fromId, toId, now) => store.migrateAttrsToMemory(fromId, toId, now)
|
|
2170
|
+
};
|
|
2171
|
+
}
|