dsh-agent-soul 0.2.0 → 0.4.2
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/README.md +236 -125
- package/docs/preview.html +8 -8
- package/lib/api.js +304 -30
- package/lib/client/api.js +39 -0
- package/lib/client/app.js +3 -1
- package/lib/client/diary-tab.js +347 -0
- package/lib/client/memory-tab.js +26 -4
- package/lib/client/mood-tab.js +12 -10
- package/lib/client/overview-tab.js +33 -0
- package/lib/client/persona-tab.js +1 -0
- package/lib/client/settings-tab.js +1 -1
- package/lib/client.js +464 -16
- package/lib/diary.js +1265 -0
- package/lib/env.js +57 -9
- package/lib/extract.js +323 -9
- package/lib/index.js +498 -67
- package/lib/memory.js +1377 -807
- package/lib/mood.js +270 -23
- package/lib/paths.js +196 -168
- package/lib/purpose.js +195 -1
- package/lib/refine.js +221 -0
- package/lib/registry.js +236 -236
- package/lib/store.js +697 -383
- package/lib/tool.js +27 -8
- package/package.json +84 -71
- package/tools/build-client.mjs +1 -0
- package/tools/sync.mjs +131 -0
package/lib/memory.js
CHANGED
|
@@ -1,807 +1,1377 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* memory.js —— 记忆卡引擎(纯 node: 内置模块,可单测,不依赖 DSH 也不依赖模型)。
|
|
3
|
-
*
|
|
4
|
-
* 设计目标:让「记忆」像人的记忆,而不是一张越攒越大的表。
|
|
5
|
-
*
|
|
6
|
-
* · 重要度决定降多快:和主人相关、有情绪、约定、第一次 → 降得慢
|
|
7
|
-
* · 遗忘不是删除:先变短、再变含糊、最后只剩「好像有这么件事」
|
|
8
|
-
* · 永久锚点:pinned / 初次相遇 → 永远清晰,容量压缩时也不淘汰
|
|
9
|
-
* · 复习效应:被再次提起 → 召回次数 +1、可能回升一档
|
|
10
|
-
* · 一次只动一格:每天最多降一档,所以是「慢慢模糊」而不是某天突然想不起来
|
|
11
|
-
* · 容量有上限:超了从最不重要的开始压,不粗暴截断字符串
|
|
12
|
-
*
|
|
13
|
-
* 为什么规则全是纯函数:
|
|
14
|
-
* 记忆整理每回合都可能跑。要是靠模型判断「这条重不重要」,
|
|
15
|
-
* 一天几十个回合就是几十次额外调用 —— 又慢又烧钱,还没法写测试。
|
|
16
|
-
* 这里全部用正则 + 数值,输入确定输出就确定。
|
|
17
|
-
*
|
|
18
|
-
* 数据形状(一条记录):
|
|
19
|
-
* {
|
|
20
|
-
* id, text, title, importance, clarity, tags,
|
|
21
|
-
* createdAt, lastSeenAt, recallCount,
|
|
22
|
-
* pinned, isInitial, source, scope
|
|
23
|
-
* }
|
|
24
|
-
*/
|
|
25
|
-
import { existsSync, appendFileSync, readFileSync } from 'node:fs'
|
|
26
|
-
import { shortHash, atomicWrite } from './paths.js'
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
export const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
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
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
.
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
importance
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
if (
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
if (
|
|
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
|
-
|
|
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
|
-
return {
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
const
|
|
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
|
-
const
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
1
|
+
/**
|
|
2
|
+
* memory.js —— 记忆卡引擎(纯 node: 内置模块,可单测,不依赖 DSH 也不依赖模型)。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标:让「记忆」像人的记忆,而不是一张越攒越大的表。
|
|
5
|
+
*
|
|
6
|
+
* · 重要度决定降多快:和主人相关、有情绪、约定、第一次 → 降得慢
|
|
7
|
+
* · 遗忘不是删除:先变短、再变含糊、最后只剩「好像有这么件事」
|
|
8
|
+
* · 永久锚点:pinned / 初次相遇 → 永远清晰,容量压缩时也不淘汰
|
|
9
|
+
* · 复习效应:被再次提起 → 召回次数 +1、可能回升一档
|
|
10
|
+
* · 一次只动一格:每天最多降一档,所以是「慢慢模糊」而不是某天突然想不起来
|
|
11
|
+
* · 容量有上限:超了从最不重要的开始压,不粗暴截断字符串
|
|
12
|
+
*
|
|
13
|
+
* 为什么规则全是纯函数:
|
|
14
|
+
* 记忆整理每回合都可能跑。要是靠模型判断「这条重不重要」,
|
|
15
|
+
* 一天几十个回合就是几十次额外调用 —— 又慢又烧钱,还没法写测试。
|
|
16
|
+
* 这里全部用正则 + 数值,输入确定输出就确定。
|
|
17
|
+
*
|
|
18
|
+
* 数据形状(一条记录):
|
|
19
|
+
* {
|
|
20
|
+
* id, text, title, importance, kind, clarity, tags,
|
|
21
|
+
* createdAt, lastSeenAt, recallCount,
|
|
22
|
+
* pinned, isInitial, source, scope
|
|
23
|
+
* }
|
|
24
|
+
*/
|
|
25
|
+
import { existsSync, appendFileSync, readFileSync } from 'node:fs'
|
|
26
|
+
import { shortHash, atomicWrite, archivePath } from './paths.js'
|
|
27
|
+
// 2026-10-31:addRecord 里要记「近似重复」的日志。第一次写忘了 import,
|
|
28
|
+
// 运行时会 "note is not defined" —— 和今天上午 atomicWrite 那次一个毛病。
|
|
29
|
+
import { note } from './env.js'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 卡片结构版本。
|
|
33
|
+
*
|
|
34
|
+
* v1 → v2(2026-10-30):老记录补 kind 字段(见 legacyKindOf)。
|
|
35
|
+
* 版本号存在的意义就是让「一次性迁移」只跑一次 —— 迁移过的卡写回 version: 2,
|
|
36
|
+
* 之后每次加载都直接跳过,不会反复改写用户的文件。
|
|
37
|
+
*/
|
|
38
|
+
export const MEMORY_VERSION = 2
|
|
39
|
+
export const DAY_MS = 24 * 60 * 60 * 1000
|
|
40
|
+
|
|
41
|
+
/** 清晰度阶梯:只允许相邻移动,不能跳档。 */
|
|
42
|
+
export const CLARITY_ORDER = Object.freeze(['vivid', 'clear', 'fuzzy', 'trace', 'forgotten'])
|
|
43
|
+
export const CLARITY_LABEL = Object.freeze({
|
|
44
|
+
vivid: '清晰',
|
|
45
|
+
clear: '清楚',
|
|
46
|
+
fuzzy: '模糊',
|
|
47
|
+
trace: '只剩印象',
|
|
48
|
+
forgotten: '已遗忘'
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 记忆类型:提炼阶段(refine.js)给出的五类。2026-10-30 起真正落库。
|
|
53
|
+
*
|
|
54
|
+
* 为什么缺省是 'event' 而不是 'fact':'fact' 在双写判据里享受「无条件进全局卡」
|
|
55
|
+
* 的待遇(见 store.js 的 writeAutoMemories),把不确定的值默认成事实等于放行污染。
|
|
56
|
+
* 'event' 是最中性的说法——「发生过/说过这件事」,错了也不额外赋予它权威。
|
|
57
|
+
*/
|
|
58
|
+
export const MEMORY_KINDS = Object.freeze(['fact', 'preference', 'promise', 'event', 'feeling'])
|
|
59
|
+
|
|
60
|
+
/** 类型标记的中文名(相关区每行前面那个〔〕)。2026-10-30 与 kind 一起落库。 */
|
|
61
|
+
export const KIND_LABEL = Object.freeze({
|
|
62
|
+
fact: '事实',
|
|
63
|
+
preference: '偏好',
|
|
64
|
+
promise: '约定',
|
|
65
|
+
event: '事件',
|
|
66
|
+
feeling: '感受'
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
/** 归一 kind:认不出的值(含旧记录、undefined、乱写)一律落到 'event'。 */
|
|
70
|
+
export function normalizeKind(value) {
|
|
71
|
+
const kind = String(value ?? '')
|
|
72
|
+
return MEMORY_KINDS.includes(kind) ? kind : 'event'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 默认参数。全部可通过配置覆盖,坏值一律回默认(见 normalizeConfig)。 */
|
|
76
|
+
export const DEFAULTS = Object.freeze({
|
|
77
|
+
enabled: true,
|
|
78
|
+
/** 最近 N 天的事至少保持「清楚」。 */
|
|
79
|
+
recentDays: 7,
|
|
80
|
+
/** 新记忆前 N 天不降档(给它一个「刚发生所以还新鲜」的窗口)。 */
|
|
81
|
+
fuzzyAfterDays: 7,
|
|
82
|
+
/** 超过 N 天且重要度 < 50 且不是主人相关 / 初次相遇 → 可以彻底遗忘。 */
|
|
83
|
+
forgetAfterDays: 60,
|
|
84
|
+
/** 和主人相关且重要度达到这个值 → 最差也保持「清楚」。 */
|
|
85
|
+
minOwnerImportance: 65,
|
|
86
|
+
/** 单张卡最多留多少条(超出时压缩会开始降档)。 */
|
|
87
|
+
maxRecords: 600,
|
|
88
|
+
/** 渲染后的告警字数(不自动删,只提醒)。 */
|
|
89
|
+
warnChars: 24000,
|
|
90
|
+
/**
|
|
91
|
+
* 注入提示词的预算字数。
|
|
92
|
+
*
|
|
93
|
+
* 2026-10-30:1600 → 3200,并为「固定区 + 相关区」拆分后的正文留余量。
|
|
94
|
+
* 这个字面量是**唯一**的默认值来源 —— store.js 的 DEFAULT_CONFIG 直接引用它。
|
|
95
|
+
* 旧实现两处各写一份(这里 2400、store.js 1600),实际生效 1600、
|
|
96
|
+
* 告警却按 2400 算,改预算时两边容易只改一半。
|
|
97
|
+
*/
|
|
98
|
+
injectMaxChars: 3200,
|
|
99
|
+
/**
|
|
100
|
+
* 注入时按「当前这句用户消息」召回相关记忆(2026-10-30)。
|
|
101
|
+
* false = 完全退回整卡渲染,输出与改动前逐字节一致(老路是 renderMemoryBlock)。
|
|
102
|
+
*/
|
|
103
|
+
memoryRecall: true,
|
|
104
|
+
/**
|
|
105
|
+
* 相关区最多召回几条(项目卡 + 全局卡一起打分后再截)。
|
|
106
|
+
*
|
|
107
|
+
* 2026-10-30:6 → 3。相关区的定位是「勾一下让你想起来」,不是把卡念一遍;
|
|
108
|
+
* 全文留给 soul_memory 工具按需去取。条数和下面 RELATED_LINE_MAX 一起收,
|
|
109
|
+
* 是为了让这段文本短到「同样的内容每轮字节一致」—— 粘性召回靠的就是这个。
|
|
110
|
+
*/
|
|
111
|
+
memoryRecallTopK: 3,
|
|
112
|
+
/** 每天几点之后执行一次遗忘整理(0-23 本地时间)。 */
|
|
113
|
+
dailyHour: 4,
|
|
114
|
+
/** 达告警线时自动压缩。 */
|
|
115
|
+
autoCompact: true,
|
|
116
|
+
/** 单个回合最多自动写入几条(防止一次对话灌满一张卡)。 */
|
|
117
|
+
maxPerTick: 12,
|
|
118
|
+
/**
|
|
119
|
+
* 自动记忆的最低重要度,按 kind 分档(2026-10-30)。
|
|
120
|
+
*
|
|
121
|
+
* 为什么 event 要单独提到 70:用户当场在项目卡里抓到三条"记忆",
|
|
122
|
+
* 全是一次性任务/进度(「帮我改插件」「对桥接代码做最后一次检测」),
|
|
123
|
+
* 重要度 44~52 —— 旧阈值 42 等于「只要是主人说的就收」。
|
|
124
|
+
* fact / preference / promise 是换一天还成立的画像,保持 42 的宽口径。
|
|
125
|
+
*
|
|
126
|
+
* 这里是**唯一**的默认值来源:store.js 的 DEFAULT_CONFIG 直接引用它,
|
|
127
|
+
* 落库判断统一走 extract.js 的 minImportanceForKind,别在调用方散写 42/70。
|
|
128
|
+
*/
|
|
129
|
+
autoImportanceEvent: 70,
|
|
130
|
+
autoImportanceDefault: 42,
|
|
131
|
+
/**
|
|
132
|
+
* 绑定的日记会话 id(2026-10-31)。
|
|
133
|
+
* 空串 = 还没绑定,日记到点直接跳过并在日志里提示去设置页绑定。
|
|
134
|
+
* 为什么要绑而不是自建:ctx.agents.create 造出来的会话拿不到宿主的
|
|
135
|
+
* setup / installSelection,agent 没有标准工具集,永远写不出日记文件。
|
|
136
|
+
*/
|
|
137
|
+
diarySessionId: '',
|
|
138
|
+
/**
|
|
139
|
+
* 是否允许在本地设置页查看私密日记正文(2026-10-31,默认 false)。
|
|
140
|
+
* false = 行为完全不变,接口只报「私密存在」;true = 新增只读端点回正文,
|
|
141
|
+
* 但那个端点只接受本机回环请求。私密日记默认永不出服务器。
|
|
142
|
+
*/
|
|
143
|
+
diaryPrivateVisible: false
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// ---- 语义信号(全部是正则,不调模型) ----
|
|
147
|
+
|
|
148
|
+
/** 情绪浓度:强信号 3 分/词,中信号 2 分/词,上限 24。 */
|
|
149
|
+
const EMOTION_STRONG_RE = /喜欢|想念|想你|舍不得|难过|委屈|哭|心疼|感动|害怕|孤单|抱歉|对不起|谢谢|抱抱|亲亲|陪伴|永远|最爱|在乎|重要|开心|太好了/g
|
|
150
|
+
const EMOTION_MEDIUM_RE = /有点|挺|蛮|累了|困|饿|烦|郁闷|害羞|生气|讨厌|紧张|激动|惊讶|意外|终于|还好/g
|
|
151
|
+
// ↑ 这两个是数出现次数(match),必须要 g;下面三个只判断「有没有」(test),绝不能带 g。
|
|
152
|
+
/** 约定 / 承诺:这类事忘了会出问题,所以加权。 */
|
|
153
|
+
const PROMISE_RE = /答应|约定|说好|以后|下次|记得|不要忘|别忘了|发誓|保证|我会|明天|后天|下周/
|
|
154
|
+
/** 矛盾 / 道歉 / 和好:情绪浓度高,值得记住。 */
|
|
155
|
+
const CONFLICT_RE = /吵架|生气|道歉|对不起|和好|误会|不理你|冷战|凶你|原谅|抱歉/
|
|
156
|
+
/**
|
|
157
|
+
* 关于「我」的偏好与长期事实:这是长期有用的画像,才值得留几十年。
|
|
158
|
+
*
|
|
159
|
+
* 为什么要区分「寒暄」和「长期事实」:
|
|
160
|
+
* 「今天问了句编译器怎么配」是寒暄,忘了无所谓;
|
|
161
|
+
* 「目标是嵌入式工程师」「喜欢喝冰美式」是画像,忘了就是失忆。
|
|
162
|
+
* 光靠重要度分不开这两者(都是主人随口说的),所以单独识别。
|
|
163
|
+
*/
|
|
164
|
+
/**
|
|
165
|
+
* ⚠️ 下面这两个正则**不能带 g 标志**。
|
|
166
|
+
* `g` 让 RegExp 变成有状态的(每次 test/exec 推进 lastIndex),
|
|
167
|
+
* 连续判断多条记忆时会「漏一条、中一条」地跳着匹配 ——
|
|
168
|
+
* 症状是「同样的句子,第一次认得出,第二次认不出」,极难排查。
|
|
169
|
+
* 要数出现次数的地方(情绪强度)才用 g + match。
|
|
170
|
+
*/
|
|
171
|
+
const SELF_RE = /我(?:喜欢|讨厌|想要|是|会|在|叫|住|学|做|用|习惯|觉得|认为)|我的|我不|我觉|我准备|我打算|我计划|目标是|专业是|想当|在做|正在做|习惯用|平时用|常用/i
|
|
172
|
+
/** 长期事实类信号:命中就进 self 标签,享受「永不遗忘」保护。 */
|
|
173
|
+
const FACT_RE = /目标是|专业是|想当|在做|正在做|习惯用|平时用|常用|我(?:喜欢|讨厌|习惯|住|学|专业)|我的(?:目标|专业|习惯|电脑)|大学|学院|专业|年级|大[一二三四]|研究生|在读|就读/i
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 一次性流水账:吃了什么、穿了几件、几点到哪、天气冷热……
|
|
177
|
+
*
|
|
178
|
+
* 为什么要单独拦它(2026-10-29 实测发现的坑):
|
|
179
|
+
* 「主人私下说的」原本直接 +42,而入选阈值就是 42 —— 等于只要是主人说的、
|
|
180
|
+
* 超过 8 个字就必定入库。结果是记忆卡里躺着的五条全是「晚饭是牛肉丸子汤」
|
|
181
|
+
* 「多穿了点衣服」,真正该留的画像反而被挤在后面。
|
|
182
|
+
* 这类话每一天都在发生,记下来没有复用的价值。
|
|
183
|
+
*/
|
|
184
|
+
const EPHEMERAL_RE = /吃(?:了|饭|完|过)|(?:早|午|晚|夜)饭|喝(?:了|完)|(?:多|少)穿|穿(?:了|上|着)|天气|气温|(?:不|很|挺|有点)(?:冷|热)|宿舍|寝室|起床|睡了|睡觉|出门|在路上|下课|放学|洗澡|洗漱|刷牙|几点了/
|
|
185
|
+
|
|
186
|
+
/** 「第一次」类事件:天然是锚点。 */
|
|
187
|
+
const FIRST_RE = /第一次|初次|头一次|最开始|刚认识|认识你|纪念日|第一天|从来没有过/
|
|
188
|
+
|
|
189
|
+
/** 脱敏规则:入库前把明显的敏感信息抹掉。 */
|
|
190
|
+
const REDACT_RULES = [
|
|
191
|
+
[/\b(sk-[A-Za-z0-9_-]{8,})/g, '[密钥]'],
|
|
192
|
+
[/\b([A-Za-z0-9_-]{24,})\b(?=[^\n]{0,20}(?:token|key|secret))/gi, '[令牌]'],
|
|
193
|
+
[/\b1[3-9]\d{9}\b/g, '[手机号]'],
|
|
194
|
+
[/\b\d{17}[\dXx]\b/g, '[身份证]'],
|
|
195
|
+
[/\b\d{16,19}\b/g, '[卡号]'],
|
|
196
|
+
// QQ 号:桥接消息的前缀里带(「(QQ 私聊·用户本人 QQ 3472302240)」),
|
|
197
|
+
// 不脱敏的话账号会原样写进记忆卡,再随注入发出去。
|
|
198
|
+
[/QQ[::\s]*(\d{5,12})/gi, '[QQ号]'],
|
|
199
|
+
[/https?:\/\/[^\s,。;、))]+/g, '[链接]']
|
|
200
|
+
]
|
|
201
|
+
|
|
202
|
+
const clamp = (value, min, max) => {
|
|
203
|
+
const num = Number(value)
|
|
204
|
+
if (!Number.isFinite(num)) return min
|
|
205
|
+
return Math.min(max, Math.max(min, num))
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function iso(now = Date.now()) {
|
|
209
|
+
return new Date(now).toISOString()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function timeOf(value, fallback = 0) {
|
|
213
|
+
const num = typeof value === 'number' ? value : Date.parse(String(value ?? ''))
|
|
214
|
+
return Number.isFinite(num) ? num : fallback
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function dateKey(now = Date.now()) {
|
|
218
|
+
const d = new Date(now)
|
|
219
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 配置收敛:坏值一律回默认,不把 NaN / 0 写进引擎。 */
|
|
223
|
+
export function normalizeConfig(input = {}) {
|
|
224
|
+
const src = input !== null && typeof input === 'object' ? input : {}
|
|
225
|
+
const out = { ...DEFAULTS }
|
|
226
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
227
|
+
const value = src[key]
|
|
228
|
+
if (value === undefined || value === null) continue
|
|
229
|
+
if (typeof DEFAULTS[key] === 'boolean') {
|
|
230
|
+
out[key] = value === true
|
|
231
|
+
continue
|
|
232
|
+
}
|
|
233
|
+
// 字符串项(diarySessionId 等):只收字符串,其余类型回默认(空串)
|
|
234
|
+
if (typeof DEFAULTS[key] === 'string') {
|
|
235
|
+
if (typeof value === 'string') out[key] = value.trim()
|
|
236
|
+
continue
|
|
237
|
+
}
|
|
238
|
+
const num = Number(value)
|
|
239
|
+
if (Number.isFinite(num) && num >= 0) out[key] = num
|
|
240
|
+
}
|
|
241
|
+
out.dailyHour = clamp(out.dailyHour, 0, 23)
|
|
242
|
+
out.injectMaxChars = clamp(out.injectMaxChars, 400, 20000)
|
|
243
|
+
out.maxRecords = clamp(out.maxRecords, 20, 5000)
|
|
244
|
+
// 相关区条数:0 会让「召回开、但永远召回不到东西」看起来像坏了,所以下限给 1。
|
|
245
|
+
out.memoryRecallTopK = clamp(out.memoryRecallTopK, 1, 50)
|
|
246
|
+
// 自动记忆的两个重要度门槛(2026-10-30):越界值一律夹回 0~100,
|
|
247
|
+
// 免得配置里写个 999 让所有自动记忆静默消失、还查不出原因。
|
|
248
|
+
out.autoImportanceEvent = clamp(out.autoImportanceEvent, 0, 100)
|
|
249
|
+
out.autoImportanceDefault = clamp(out.autoImportanceDefault, 0, 100)
|
|
250
|
+
return out
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** 入库前脱敏。宁可少记一条细节,也不要把密钥写进长期记忆。 */
|
|
254
|
+
export function redact(text, maxChars = 600) {
|
|
255
|
+
let out = String(text ?? '')
|
|
256
|
+
for (const [re, label] of REDACT_RULES) out = out.replace(re, label)
|
|
257
|
+
out = out.replace(/\s+/g, ' ').trim()
|
|
258
|
+
if (out.length > maxChars) out = `${out.slice(0, maxChars - 1)}…`
|
|
259
|
+
return out
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 情绪浓度 0-24:强信号权重高,中信号低一些。 */
|
|
263
|
+
export function emotionScore(text) {
|
|
264
|
+
const body = String(text ?? '')
|
|
265
|
+
const strong = (body.match(EMOTION_STRONG_RE) ?? []).length
|
|
266
|
+
const medium = (body.match(EMOTION_MEDIUM_RE) ?? []).length
|
|
267
|
+
return clamp(strong * 3 + medium * 2, 0, 24)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* 给一条候选记忆打分(0-100)。
|
|
272
|
+
*
|
|
273
|
+
* 打分是「值不值得记 + 该记多久」的唯一依据,所以每条加分都写了理由,
|
|
274
|
+
* 并且原样返回 reasons —— 设置页要能解释「为什么这条这么重要」,
|
|
275
|
+
* 否则调参数就是摸黑。
|
|
276
|
+
*/
|
|
277
|
+
export function scoreRecord(input = {}) {
|
|
278
|
+
const text = String(input.text ?? '')
|
|
279
|
+
const isOwner = input.isOwner === true
|
|
280
|
+
const isPrivate = input.isPrivate === true
|
|
281
|
+
const direct = input.direct === true
|
|
282
|
+
const reasons = []
|
|
283
|
+
let importance = 8
|
|
284
|
+
|
|
285
|
+
if (isOwner) {
|
|
286
|
+
// 2026-10-29 从 42/32 降到 36/26:原来私聊直接 +42,而入选阈值就是 42,
|
|
287
|
+
// 等于「只要是主人私下说的」就免检入库 —— 判据失去了区分度,流水账和画像分不出高低。
|
|
288
|
+
// 降到这里仍然过线(8 + 36 = 44 > 42),普通的话照样记得下,
|
|
289
|
+
// 但 differentiation 交给下面的内容信号:有价值的话分数明显更高。
|
|
290
|
+
importance += isPrivate ? 36 : 26
|
|
291
|
+
reasons.push(isPrivate ? '主人私下说的' : '主人在群里说的')
|
|
292
|
+
}
|
|
293
|
+
if (direct) {
|
|
294
|
+
importance += 8
|
|
295
|
+
reasons.push('直接对你说的')
|
|
296
|
+
}
|
|
297
|
+
const emotion = emotionScore(text)
|
|
298
|
+
if (emotion > 0) {
|
|
299
|
+
// +6 保底:情绪发生了就值得留个印象,哪怕浓度不高
|
|
300
|
+
importance += emotion + 6
|
|
301
|
+
reasons.push(`情绪浓度 ${emotion}`)
|
|
302
|
+
}
|
|
303
|
+
if (input.isFirst === true || FIRST_RE.test(text)) {
|
|
304
|
+
importance += 30
|
|
305
|
+
reasons.push('第一次 / 第一次被提到')
|
|
306
|
+
}
|
|
307
|
+
if (PROMISE_RE.test(text)) {
|
|
308
|
+
importance += 16
|
|
309
|
+
reasons.push('约定 / 将来要做的事')
|
|
310
|
+
}
|
|
311
|
+
if (CONFLICT_RE.test(text)) {
|
|
312
|
+
importance += 14
|
|
313
|
+
reasons.push('矛盾 / 道歉 / 和好')
|
|
314
|
+
}
|
|
315
|
+
if (SELF_RE.test(text)) {
|
|
316
|
+
importance += 8
|
|
317
|
+
reasons.push('关于你自己的偏好或情况')
|
|
318
|
+
}
|
|
319
|
+
// 长期事实(目标 / 专业 / 习惯 / 身份)。
|
|
320
|
+
// FACT_RE 原来只加 tag 不加分 —— 「永不遗忘」的承诺挂在打分之外,
|
|
321
|
+
// 结果「我目标是当嵌入式工程师」和「今天晚饭吃了什么」分数只差 5 分。
|
|
322
|
+
if (FACT_RE.test(text)) {
|
|
323
|
+
importance += 18
|
|
324
|
+
reasons.push('长期事实(目标 / 专业 / 习惯 / 身份)')
|
|
325
|
+
}
|
|
326
|
+
if (EPHEMERAL_RE.test(text)) {
|
|
327
|
+
importance -= 20
|
|
328
|
+
reasons.push('一次性日常,不值得长期占着')
|
|
329
|
+
}
|
|
330
|
+
if (text.length < 6) {
|
|
331
|
+
importance -= 12
|
|
332
|
+
reasons.push('太短,信息量低')
|
|
333
|
+
}
|
|
334
|
+
if (Number.isFinite(Number(input.importance))) {
|
|
335
|
+
importance = Number(input.importance)
|
|
336
|
+
reasons.push('手动指定')
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const tags = []
|
|
340
|
+
if (isOwner) tags.push('owner')
|
|
341
|
+
if (input.isFirst === true || FIRST_RE.test(text)) tags.push('first')
|
|
342
|
+
if (PROMISE_RE.test(text)) tags.push('promise')
|
|
343
|
+
if (CONFLICT_RE.test(text)) tags.push('conflict')
|
|
344
|
+
if (SELF_RE.test(text)) tags.push('self')
|
|
345
|
+
// fact 才是「永不遗忘」的判据(见 ownerImportant)。
|
|
346
|
+
// 为什么不用 self:SELF_RE 宽到「我觉得 / 我在 / 我会」都算,拿它当长期事实
|
|
347
|
+
// 会让「我觉得有点累」这种一次性的感受永久占位,压缩时还删不掉,卡很快被撑满。
|
|
348
|
+
if (FACT_RE.test(text)) tags.push('fact')
|
|
349
|
+
if (emotion >= 9) tags.push('emotional')
|
|
350
|
+
|
|
351
|
+
return { importance: clamp(Math.round(importance), 0, 100), reasons, tags }
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* 这条记忆算不算「必须长期保护」(决定衰减速率与淘汰豁免)。
|
|
356
|
+
*
|
|
357
|
+
* ① 标记为「第一次」的事 → 保护(不管谁说的,锚点就是锚点)
|
|
358
|
+
* ② 关于主人的长期事实(偏好 / 目标 / 专业 / 习惯)→ 保护。
|
|
359
|
+
* 这类往往是随口一提,重要度分数不高,但忘掉等于失忆,所以不看分数。
|
|
360
|
+
* ⚠️ 必须**同时**是 owner:群友说「我喜欢吃西瓜」不该进永久记忆
|
|
361
|
+
* ③ 和主人相关且重要度够高 → 保护
|
|
362
|
+
*/
|
|
363
|
+
function ownerImportant(record, cfg) {
|
|
364
|
+
const tags = Array.isArray(record.tags) ? record.tags : []
|
|
365
|
+
if (tags.includes('first')) return true
|
|
366
|
+
const isOwner = tags.includes('owner')
|
|
367
|
+
if (!isOwner) return false
|
|
368
|
+
// 用 fact(FACT_RE 窄判据:目标是 / 专业是 / 想当 / 习惯用…)而不是 self。
|
|
369
|
+
// self 来自宽得多的 SELF_RE,「我觉得有点累」也会命中 —— 那种一次性的感受不该
|
|
370
|
+
// 拿到永久保护,否则压缩先跳过它们,卡会被琐事撑满,真正该留的反而被挤掉。
|
|
371
|
+
if (tags.includes('fact')) return true
|
|
372
|
+
return Number(record.importance) >= cfg.minOwnerImportance
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* 这条记忆现在**应该**处于哪一档。
|
|
377
|
+
*
|
|
378
|
+
* retention(留存值)是核心:重要度高、刚发生过、被反复提起 → 高留存;
|
|
379
|
+
* 时间越久扣得越多。主人相关 / 初次相遇的扣分速率只有普通记忆的三分之一。
|
|
380
|
+
*/
|
|
381
|
+
export function targetClarity(record, config = {}, now = Date.now()) {
|
|
382
|
+
const cfg = normalizeConfig(config)
|
|
383
|
+
if (record.pinned === true) return 'vivid'
|
|
384
|
+
|
|
385
|
+
const created = timeOf(record.createdAt, now)
|
|
386
|
+
const seen = timeOf(record.lastSeenAt, created)
|
|
387
|
+
const ageDays = Math.max(0, (now - created) / DAY_MS)
|
|
388
|
+
const sinceSeenDays = Math.max(0, (now - seen) / DAY_MS)
|
|
389
|
+
const protectedInitial = record.isInitial === true
|
|
390
|
+
const important = ownerImportant(record, cfg) || protectedInitial
|
|
391
|
+
|
|
392
|
+
if (ageDays > cfg.forgetAfterDays && Number(record.importance) < 50 && !important) {
|
|
393
|
+
return 'forgotten'
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
let retention = Number(record.importance) || 0
|
|
397
|
+
retention += Math.min(12, (Number(record.recallCount) || 0) * 2)
|
|
398
|
+
if (ageDays <= cfg.recentDays) retention += 18
|
|
399
|
+
if (sinceSeenDays <= 2) retention += 8
|
|
400
|
+
retention -= Math.min(80, Math.max(0, ageDays - cfg.fuzzyAfterDays) * (important ? 0.12 : 0.35))
|
|
401
|
+
if (important) retention = Math.max(retention, 55)
|
|
402
|
+
if (ageDays <= cfg.recentDays) retention = Math.max(retention, 50)
|
|
403
|
+
|
|
404
|
+
if (retention >= 68) return 'vivid'
|
|
405
|
+
if (retention >= 46) return 'clear'
|
|
406
|
+
if (retention >= 24) return 'fuzzy'
|
|
407
|
+
if (retention >= 12) return 'trace'
|
|
408
|
+
return 'forgotten'
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ---- 卡的读写 ----
|
|
412
|
+
|
|
413
|
+
export function createCard(scope = 'global', now = Date.now()) {
|
|
414
|
+
return {
|
|
415
|
+
version: MEMORY_VERSION,
|
|
416
|
+
scope,
|
|
417
|
+
records: [],
|
|
418
|
+
stats: { added: 0, decayed: 0, forgotten: 0, compacted: 0, lastDecayAt: null },
|
|
419
|
+
lastDecayDate: null,
|
|
420
|
+
createdAt: iso(now),
|
|
421
|
+
updatedAt: iso(now)
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** 读盘 + 结构收敛。坏文件返回 null(调用方新建,**不覆盖原文件**)。 */
|
|
426
|
+
export function loadCard(file) {
|
|
427
|
+
try {
|
|
428
|
+
if (!existsSync(file)) return null
|
|
429
|
+
// 2026-10-30:去掉 UTF-8 BOM 再解析。
|
|
430
|
+
// 实测 ~/.dsh/agents/memory/projects/work-*.json 被 PowerShell 的 ConvertTo-Json
|
|
431
|
+
// 手工改过,文件头带 BOM —— JSON.parse 直接抛,loadCard 返回 null,
|
|
432
|
+
// 注入把卡当空卡、下一次维护再存盘就把用户的记录整份抹了。
|
|
433
|
+
// 迁移(kind)也走这里,读不进老卡等于迁移没发生。
|
|
434
|
+
const raw = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
435
|
+
const card = normalizeCard(raw)
|
|
436
|
+
// 一次性迁移(2026-10-30,v1 → v2):老记录补 kind 后写回。
|
|
437
|
+
// 只补 kind,其它字段原样保留 —— 迁移不该让一条记忆"变新"或换 id。
|
|
438
|
+
// 失败(只读目录 / 文件被占用)就跳过:内存里的卡已经是对的,不影响这次读取。
|
|
439
|
+
if (raw !== null && typeof raw === 'object' && (Number(raw.version) || 1) < MEMORY_VERSION) {
|
|
440
|
+
try {
|
|
441
|
+
const patched = { ...raw, version: MEMORY_VERSION }
|
|
442
|
+
patched.records = (Array.isArray(raw.records) ? raw.records : []).map((item) => (
|
|
443
|
+
// v1 卡上的 kind 一律重新过一遍 legacyKindOf(含旧的 'event' 默认值),
|
|
444
|
+
// 不然写回文件的和内存里的会不一致,下次加载(v2)又翻回 event。
|
|
445
|
+
item !== null && typeof item === 'object' ? { ...item, kind: legacyKindOf(item) } : item
|
|
446
|
+
))
|
|
447
|
+
atomicWrite(file, `${JSON.stringify(patched, null, 2)}\n`)
|
|
448
|
+
} catch {
|
|
449
|
+
/* 写不进去就算了,下次加载还会再试一次(迁移本身是幂等的) */
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return card
|
|
453
|
+
} catch {
|
|
454
|
+
return null
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* 老记录的 kind 补全(2026-10-30,卡片 v1 → v2)。
|
|
460
|
+
*
|
|
461
|
+
* 判据只用当时已经存在的字段,不猜、不调模型:
|
|
462
|
+
* · 已经是合法 kind(手工写的、新卡里的)→ 原样不动,迁移只补空的
|
|
463
|
+
* · tags 含 fact,或正文命中 FACT_RE → 'fact'(FACT_RE 是旧版唯一的「长期事实」判据)
|
|
464
|
+
* · tags 含 first → 'event'(保持原判:一次性的锚点)
|
|
465
|
+
* · 其余 → 'event'
|
|
466
|
+
*
|
|
467
|
+
* 为什么必须迁移:kind 缺省被归一成 event,于是注入里每条老记录都顶着〔事件〕,
|
|
468
|
+
* 连「树树是烟台大学…」这种事实也不例外 —— 标签变成噪音,反而看不出哪条是事实。
|
|
469
|
+
*/
|
|
470
|
+
function legacyKindOf(raw) {
|
|
471
|
+
const kind = String(raw?.kind ?? '')
|
|
472
|
+
// ⚠️ 2026-10-30 实测发现的坑:老卡里的 kind 不是"缺字段",而是上一版回读时
|
|
473
|
+
// 已经被归一成 'event' 存进去了(global.json 14 条全是 event)。
|
|
474
|
+
// 所以 v1 卡上的 'event' 必须**重新判一次**,否则迁移等于没做。
|
|
475
|
+
// 只有 non-event 的明确值(fact/preference/promise/feeling)才原样保留。
|
|
476
|
+
if (MEMORY_KINDS.includes(kind) && kind !== 'event') return kind
|
|
477
|
+
const tags = Array.isArray(raw?.tags) ? raw.tags.map((t) => String(t)) : []
|
|
478
|
+
if (tags.includes('fact')) return 'fact'
|
|
479
|
+
if (tags.includes('first')) return 'event'
|
|
480
|
+
if (FACT_RE.test(String(raw?.text ?? ''))) return 'fact'
|
|
481
|
+
return 'event'
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** 结构收敛:外部传进来的卡(含旧版本)一律补齐必需字段。 */
|
|
485
|
+
export function normalizeCard(raw) {
|
|
486
|
+
const card = createCard(String(raw?.scope ?? 'global'))
|
|
487
|
+
const source = raw !== null && typeof raw === 'object' ? raw : {}
|
|
488
|
+
// 旧卡(v1)在加载时就地迁移 kind,新卡/Card 已迁移的走同一套 normalizeRecord。
|
|
489
|
+
const legacy = (Number(source.version) || 1) < MEMORY_VERSION
|
|
490
|
+
card.records = (Array.isArray(source.records) ? source.records : [])
|
|
491
|
+
.map((item) => normalizeRecord(item, { migrateKind: legacy }))
|
|
492
|
+
.filter((item) => item !== null)
|
|
493
|
+
card.stats = { ...card.stats, ...(typeof source.stats === 'object' && source.stats !== null ? source.stats : {}) }
|
|
494
|
+
card.lastDecayDate = typeof source.lastDecayDate === 'string' ? source.lastDecayDate : null
|
|
495
|
+
card.createdAt = typeof source.createdAt === 'string' ? source.createdAt : card.createdAt
|
|
496
|
+
card.updatedAt = typeof source.updatedAt === 'string' ? source.updatedAt : card.updatedAt
|
|
497
|
+
return card
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function normalizeRecord(raw, { migrateKind = false } = {}) {
|
|
501
|
+
if (raw === null || typeof raw !== 'object') return null
|
|
502
|
+
const text = String(raw.text ?? '').trim()
|
|
503
|
+
if (text === '') return null
|
|
504
|
+
const clarity = CLARITY_ORDER.includes(raw.clarity) ? raw.clarity : 'clear'
|
|
505
|
+
return {
|
|
506
|
+
id: typeof raw.id === 'string' && raw.id !== '' ? raw.id : shortHash(`${text}|${String(raw.createdAt ?? '')}`),
|
|
507
|
+
text,
|
|
508
|
+
title: String(raw.title ?? '').trim(),
|
|
509
|
+
importance: clamp(Number(raw.importance) || 0, 0, 100),
|
|
510
|
+
kind: migrateKind === true ? legacyKindOf(raw) : normalizeKind(raw.kind),
|
|
511
|
+
clarity,
|
|
512
|
+
tags: Array.isArray(raw.tags) ? raw.tags.map((t) => String(t)) : [],
|
|
513
|
+
createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : iso(),
|
|
514
|
+
lastSeenAt: typeof raw.lastSeenAt === 'string' ? raw.lastSeenAt : iso(),
|
|
515
|
+
recallCount: Math.max(0, Math.trunc(Number(raw.recallCount) || 0)),
|
|
516
|
+
pinned: raw.pinned === true,
|
|
517
|
+
isInitial: raw.isInitial === true,
|
|
518
|
+
source: String(raw.source ?? 'manual'),
|
|
519
|
+
scope: raw.scope === 'project' ? 'project' : 'global'
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export function saveCard(file, card) {
|
|
524
|
+
card.updatedAt = iso()
|
|
525
|
+
atomicWrite(file, `${JSON.stringify(card, null, 2)}\n`)
|
|
526
|
+
return card
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ---- 增 / 改 / 删 ----
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* 写入一条记忆。
|
|
533
|
+
*
|
|
534
|
+
* 去重策略:同一条文本(归一后)已存在 → 不新增,改为「复习」这条老记忆
|
|
535
|
+
* (recallCount+1、lastSeenAt 刷新)。理由:同一件事反复记一遍会让卡里
|
|
536
|
+
* 塞满重复内容,而人不会因为「今天又提了一次」就多记一条。
|
|
537
|
+
*
|
|
538
|
+
* 2026-10-31 补:**近似重复要留痕**。
|
|
539
|
+
* 原来只有「一字不差」才会被拦下,像
|
|
540
|
+
* 「电脑不能保证24小时开机」和「电脑经常不关机」
|
|
541
|
+
* 这种意思相近但字面不同的,两条都会进卡。
|
|
542
|
+
* 单看没毛病,可万一写进两条互相矛盾的说法(比如「每天22点写日记」和
|
|
543
|
+
* 「第二天写前一天的」),她不知道该信哪个,而**日志里什么都不会说**。
|
|
544
|
+
*
|
|
545
|
+
* 所以这里加一道相似度检查:命中就跟已有的那条比一比,
|
|
546
|
+
* **记一行日志提醒,但绝不自动替换** —— 让一个字符串算法替她决定
|
|
547
|
+
* 「哪句是真的」太危险了。留痕,让人(和她自己)事后判断。
|
|
548
|
+
*/
|
|
549
|
+
export function addRecord(card, input = {}, config = {}, now = Date.now()) {
|
|
550
|
+
const cfg = normalizeConfig(config)
|
|
551
|
+
const raw = String(input.text ?? '').trim()
|
|
552
|
+
if (raw === '') return { ok: false, reason: '空文本' }
|
|
553
|
+
|
|
554
|
+
const text = redact(raw, 600)
|
|
555
|
+
const key = text.replace(/\s+/g, '')
|
|
556
|
+
const existing = card.records.find((record) => record.text.replace(/\s+/g, '') === key)
|
|
557
|
+
if (existing !== undefined && existing !== null) {
|
|
558
|
+
existing.lastSeenAt = iso(now)
|
|
559
|
+
existing.recallCount = (Number(existing.recallCount) || 0) + 1
|
|
560
|
+
stepUp(existing)
|
|
561
|
+
card.updatedAt = iso(now)
|
|
562
|
+
return { ok: true, deduped: true, record: existing }
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// 近似重复:只提醒,不拦截、不改写。
|
|
566
|
+
const nearDupe = findNearDuplicate(card, text)
|
|
567
|
+
if (nearDupe !== null) {
|
|
568
|
+
note('memory', `新记忆与已有条目相近,请留意是否矛盾:新增「${text.slice(0, 40)}」≈ 已有「${nearDupe.record.text.slice(0, 40)}」(相似度 ${Math.round(nearDupe.score * 100)}%)`)
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// 容量到顶就先腾地方。2026-10-30:这条路径原来没传 archive,压缩掉的记录
|
|
572
|
+
// 不进 archive.jsonl(maintain 那条传了),于是「自动写入把老记忆挤没了」
|
|
573
|
+
// 在档案件里查不到。这里补上,格式与 maintain 完全一致({archivedAt, reason, record})。
|
|
574
|
+
if (card.records.length >= cfg.maxRecords) {
|
|
575
|
+
compactCard(card, cfg, { now, archive: makeArchiver(archivePath()) })
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const scored = scoreRecord({ ...input, text })
|
|
579
|
+
const record = {
|
|
580
|
+
id: shortHash(`${text}|${now}|${card.records.length}`),
|
|
581
|
+
text,
|
|
582
|
+
title: String(input.title ?? '').trim() || text.slice(0, 24),
|
|
583
|
+
importance: scored.importance,
|
|
584
|
+
kind: normalizeKind(input.kind),
|
|
585
|
+
clarity: 'vivid',
|
|
586
|
+
tags: scored.tags,
|
|
587
|
+
createdAt: iso(now),
|
|
588
|
+
lastSeenAt: iso(now),
|
|
589
|
+
recallCount: 0,
|
|
590
|
+
pinned: input.pinned === true,
|
|
591
|
+
isInitial: input.isInitial === true,
|
|
592
|
+
source: String(input.source ?? 'manual'),
|
|
593
|
+
scope: card.scope === 'project' ? 'project' : 'global'
|
|
594
|
+
}
|
|
595
|
+
card.records.push(record)
|
|
596
|
+
card.stats.added = (Number(card.stats.added) || 0) + 1
|
|
597
|
+
card.updatedAt = iso(now)
|
|
598
|
+
return { ok: true, record, reasons: scored.reasons }
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* 找出与新文本最相近的一条已有记忆(仅用于提示,不做任何替换)。
|
|
603
|
+
*
|
|
604
|
+
* 算法:字符二元组(bigram)的 Jaccard 重合度。
|
|
605
|
+
* 为什么不用分词:中文没有空格,引入分词库会让插件多一个依赖;
|
|
606
|
+
* 二元组对「电脑不保证24小时开机」/「电脑经常不关机」这类改写足够敏感,
|
|
607
|
+
* 而且中英文都能跑。
|
|
608
|
+
*
|
|
609
|
+
* 阈值 0.55:太低会把「今天心情不错」和「今天写完了代码」也报成相近,
|
|
610
|
+
* 日志会被噪音淹掉。这个值宁可漏报也不要天天报假警。
|
|
611
|
+
*
|
|
612
|
+
* @returns {{record: object, score: number}|null}
|
|
613
|
+
*/
|
|
614
|
+
function findNearDuplicate(card, text) {
|
|
615
|
+
if (!Array.isArray(card?.records) || card.records.length === 0) return null
|
|
616
|
+
|
|
617
|
+
const grams = (s) => {
|
|
618
|
+
const clean = String(s ?? '').replace(/\s+/g, '').toLowerCase()
|
|
619
|
+
if (clean.length < 2) return clean === '' ? new Set() : new Set([clean])
|
|
620
|
+
const out = new Set()
|
|
621
|
+
for (let i = 0; i < clean.length - 1; i += 1) out.add(clean.slice(i, i + 2))
|
|
622
|
+
return out
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const a = grams(text)
|
|
626
|
+
if (a.size === 0) return null
|
|
627
|
+
|
|
628
|
+
let best = null
|
|
629
|
+
for (const record of card.records) {
|
|
630
|
+
const b = grams(record?.text)
|
|
631
|
+
if (b.size === 0) continue
|
|
632
|
+
// 只对长度接近的做比较,省掉大部分无意义的计算
|
|
633
|
+
if (Math.min(a.size, b.size) / Math.max(a.size, b.size) < 0.4) continue
|
|
634
|
+
let inter = 0
|
|
635
|
+
for (const g of a) if (b.has(g)) inter += 1
|
|
636
|
+
const score = inter / (a.size + b.size - inter)
|
|
637
|
+
if (score >= 0.55 && (best === null || score > best.score)) best = { record, score }
|
|
638
|
+
}
|
|
639
|
+
return best
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** 往上升一档(不越过 vivid)。 */
|
|
643
|
+
function stepUp(record) { const index = CLARITY_ORDER.indexOf(record.clarity)
|
|
644
|
+
if (index > 0) record.clarity = CLARITY_ORDER[index - 1]
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** 往下降一档;降到 forgotten 返回 true(调用方负责移出)。 */
|
|
648
|
+
function stepDown(record) {
|
|
649
|
+
const index = CLARITY_ORDER.indexOf(record.clarity)
|
|
650
|
+
if (index < 0 || index >= CLARITY_ORDER.length - 1) return record.clarity === 'forgotten'
|
|
651
|
+
record.clarity = CLARITY_ORDER[index + 1]
|
|
652
|
+
return record.clarity === 'forgotten'
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* 复习:被再次提及时刷新。
|
|
657
|
+
* @param {string[]} ids 命中的记录 id
|
|
658
|
+
*/
|
|
659
|
+
export function touchRecords(card, ids, now = Date.now()) {
|
|
660
|
+
const set = new Set(ids)
|
|
661
|
+
let touched = 0
|
|
662
|
+
for (const record of card.records) {
|
|
663
|
+
if (!set.has(record.id)) continue
|
|
664
|
+
record.lastSeenAt = iso(now)
|
|
665
|
+
record.recallCount = (Number(record.recallCount) || 0) + 1
|
|
666
|
+
stepUp(record)
|
|
667
|
+
touched += 1
|
|
668
|
+
}
|
|
669
|
+
if (touched > 0) card.updatedAt = iso(now)
|
|
670
|
+
return touched
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** 固定 / 取消固定(永久锚点)。 */
|
|
674
|
+
export function setPinned(card, id, pinned = true) {
|
|
675
|
+
const record = card.records.find((item) => item.id === id)
|
|
676
|
+
if (record === undefined || record === null) return false
|
|
677
|
+
record.pinned = pinned === true
|
|
678
|
+
if (record.pinned) record.clarity = 'vivid'
|
|
679
|
+
return true
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** 忘记某条(真的删,同时进档案件)。返回被删的记录或 null。 */
|
|
683
|
+
export function forgetRecord(card, id, archive, now = Date.now()) {
|
|
684
|
+
const index = card.records.findIndex((item) => item.id === id)
|
|
685
|
+
if (index < 0) return null
|
|
686
|
+
const [record] = card.records.splice(index, 1)
|
|
687
|
+
if (typeof archive === 'function') archive(record, 'manual-forget', now)
|
|
688
|
+
card.updatedAt = iso(now)
|
|
689
|
+
return record
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// ---- 衰减与压缩 ----
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* 每日遗忘整理。
|
|
696
|
+
*
|
|
697
|
+
* 三个关键点:
|
|
698
|
+
* ① 一天只跑一次(lastDecayDate 挡着),反复跑会把记忆加速抹掉;
|
|
699
|
+
* ② 一次只动一格,所以是「慢慢模糊」;
|
|
700
|
+
* ③ 支持 steps(补跑):DSH 关了一周,回来最多补 30 天,而不是从原处慢慢爬。
|
|
701
|
+
*/
|
|
702
|
+
export function applyDecay(card, config = {}, now = Date.now(), { force = false, steps = 1 } = {}) {
|
|
703
|
+
const cfg = normalizeConfig(config)
|
|
704
|
+
const today = dateKey(now)
|
|
705
|
+
if (!force && card.lastDecayDate === today) return { changed: false, forgotten: [] }
|
|
706
|
+
|
|
707
|
+
const passes = clamp(Math.round(Number(steps) || 1), 1, 30)
|
|
708
|
+
const forgotten = []
|
|
709
|
+
let changed = false
|
|
710
|
+
|
|
711
|
+
for (let pass = 0; pass < passes; pass += 1) {
|
|
712
|
+
let passChanged = false
|
|
713
|
+
const keep = []
|
|
714
|
+
for (const record of card.records) {
|
|
715
|
+
const current = CLARITY_ORDER.includes(record.clarity) ? record.clarity : 'clear'
|
|
716
|
+
const currentIndex = CLARITY_ORDER.indexOf(current)
|
|
717
|
+
const target = targetClarity(record, cfg, now)
|
|
718
|
+
const targetIndex = CLARITY_ORDER.indexOf(target)
|
|
719
|
+
if (targetIndex > currentIndex) {
|
|
720
|
+
const next = CLARITY_ORDER[currentIndex + 1]
|
|
721
|
+
if (next === 'forgotten') {
|
|
722
|
+
forgotten.push(record)
|
|
723
|
+
passChanged = true
|
|
724
|
+
continue
|
|
725
|
+
}
|
|
726
|
+
record.clarity = next
|
|
727
|
+
passChanged = true
|
|
728
|
+
} else if (targetIndex < currentIndex) {
|
|
729
|
+
// 最近被提起 / 重要记忆:一天也只恢复一档
|
|
730
|
+
record.clarity = CLARITY_ORDER[currentIndex - 1]
|
|
731
|
+
passChanged = true
|
|
732
|
+
}
|
|
733
|
+
keep.push(record)
|
|
734
|
+
}
|
|
735
|
+
card.records = keep
|
|
736
|
+
if (!passChanged) break
|
|
737
|
+
changed = true
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
card.lastDecayDate = today
|
|
741
|
+
if (changed) {
|
|
742
|
+
card.stats.decayed = (Number(card.stats.decayed) || 0) + 1
|
|
743
|
+
card.stats.lastDecayAt = iso(now)
|
|
744
|
+
card.stats.forgotten = (Number(card.stats.forgotten) || 0) + forgotten.length
|
|
745
|
+
card.updatedAt = iso(now)
|
|
746
|
+
}
|
|
747
|
+
return { changed, forgotten }
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** 上次整理到现在过了几天(用于补跑;最多 30 天)。 */
|
|
751
|
+
export function daysSince(lastDate, now = Date.now()) {
|
|
752
|
+
if (typeof lastDate !== 'string' || lastDate === '') return 1
|
|
753
|
+
const from = Date.parse(`${lastDate}T00:00:00`)
|
|
754
|
+
if (!Number.isFinite(from)) return 1
|
|
755
|
+
return clamp(Math.floor((now - from) / DAY_MS), 1, 30)
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* 容量压缩:从最不重要、最老、最模糊的开始降档,降到 trace 的才真删。
|
|
760
|
+
* pinned / isInitial / 高重要度主人记忆永不淘汰。
|
|
761
|
+
*
|
|
762
|
+
* @param archive 可选,`(record, reason, now) => void`。传了就把真删掉的记录写进遗忘档案。
|
|
763
|
+
* 这一步是**程序自己腾空间**删的,用户根本没动手 —— 不记档的话
|
|
764
|
+
* 「她怎么把这件事忘了」永远查不出来。
|
|
765
|
+
*/
|
|
766
|
+
export function compactCard(card, config = {}, { targetRatio = 0.85, now = Date.now(), archive = null } = {}) {
|
|
767
|
+
const cfg = normalizeConfig(config)
|
|
768
|
+
const budget = cfg.warnChars > 0 ? cfg.warnChars : Math.max(2000, cfg.injectMaxChars * 6)
|
|
769
|
+
const targetChars = Math.max(600, Math.floor(budget * clamp(targetRatio, 0.3, 0.95)))
|
|
770
|
+
let steps = 0
|
|
771
|
+
|
|
772
|
+
// 上限 500:正常一张卡几百条,几十次就收敛。留这个护栏是防 stepDown 被改坏后
|
|
773
|
+
// 单向不收敛,在注入路径里把一个回合卡成死循环;500 足够覆盖极端容量。
|
|
774
|
+
while (steps < 500) {
|
|
775
|
+
const chars = renderCard(card, { config: cfg, now, full: true }).length
|
|
776
|
+
if (chars <= targetChars) break
|
|
777
|
+
const candidates = card.records.filter((record) => record.pinned !== true
|
|
778
|
+
&& record.isInitial !== true
|
|
779
|
+
&& !ownerImportant(record, cfg))
|
|
780
|
+
if (candidates.length === 0) break
|
|
781
|
+
candidates.sort((a, b) => {
|
|
782
|
+
const byImportance = (Number(a.importance) || 0) - (Number(b.importance) || 0)
|
|
783
|
+
if (byImportance !== 0) return byImportance
|
|
784
|
+
const byAge = timeOf(a.createdAt, 0) - timeOf(b.createdAt, 0)
|
|
785
|
+
if (byAge !== 0) return byAge
|
|
786
|
+
return CLARITY_ORDER.indexOf(a.clarity) - CLARITY_ORDER.indexOf(b.clarity)
|
|
787
|
+
})
|
|
788
|
+
const victim = candidates[0]
|
|
789
|
+
if (victim.clarity === 'trace' || stepDown(victim)) {
|
|
790
|
+
card.records = card.records.filter((record) => record.id !== victim.id)
|
|
791
|
+
// 挤掉的进档案(reason='compact'):用户没动手,程序替他删的,必须留痕
|
|
792
|
+
if (typeof archive === 'function') archive(victim, 'compact', now)
|
|
793
|
+
steps += 1
|
|
794
|
+
continue
|
|
795
|
+
}
|
|
796
|
+
steps += 1
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
if (steps > 0) {
|
|
800
|
+
card.stats.compacted = (Number(card.stats.compacted) || 0) + 1
|
|
801
|
+
card.stats.forgotten = (Number(card.stats.forgotten) || 0) + steps
|
|
802
|
+
card.updatedAt = iso(now)
|
|
803
|
+
}
|
|
804
|
+
return steps
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// ---- 渲染 ----
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* 按清晰度决定「这条在提示词里长什么样」。
|
|
811
|
+
*
|
|
812
|
+
* 这是整个设计最像人的地方:清晰 → 完整讲;模糊 → 只讲个大概 + 明说记不清;
|
|
813
|
+
* 只剩印象 → 只剩一句「好像有这回事」。模型看到的是「我隐约记得」,
|
|
814
|
+
* 而不是「查无此事」或者「细节完备但其实已经不可靠」。
|
|
815
|
+
*/
|
|
816
|
+
function recordLine(record, { full = false } = {}) {
|
|
817
|
+
const text = redact(record.text, 300)
|
|
818
|
+
const title = record.title !== '' ? record.title : text.slice(0, 20)
|
|
819
|
+
if (record.clarity === 'fuzzy') {
|
|
820
|
+
return `- ${text.slice(0, 42)}…(细节记不清了)`
|
|
821
|
+
}
|
|
822
|
+
if (record.clarity === 'trace') {
|
|
823
|
+
return `- 好像有「${title.slice(0, 22)}」这件事…(想不起来了)`
|
|
824
|
+
}
|
|
825
|
+
const limit = record.clarity === 'vivid' ? (full ? 300 : 200) : (full ? 200 : 130)
|
|
826
|
+
return `- ${text.length > limit ? `${text.slice(0, limit)}…` : text}`
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** 分区规则:priority 越高越不该被裁掉。 */
|
|
830
|
+
function sectionize(card, now) {
|
|
831
|
+
const buckets = {
|
|
832
|
+
initial: [],
|
|
833
|
+
anchors: [],
|
|
834
|
+
owner: [],
|
|
835
|
+
recent: [],
|
|
836
|
+
fuzzy: []
|
|
837
|
+
}
|
|
838
|
+
for (const record of card.records) {
|
|
839
|
+
if (record.clarity === 'forgotten') continue
|
|
840
|
+
if (record.isInitial === true) {
|
|
841
|
+
buckets.initial.push(record)
|
|
842
|
+
continue
|
|
843
|
+
}
|
|
844
|
+
if (record.pinned === true) {
|
|
845
|
+
buckets.anchors.push(record)
|
|
846
|
+
continue
|
|
847
|
+
}
|
|
848
|
+
if (record.clarity === 'fuzzy' || record.clarity === 'trace') {
|
|
849
|
+
buckets.fuzzy.push(record)
|
|
850
|
+
continue
|
|
851
|
+
}
|
|
852
|
+
const tags = Array.isArray(record.tags) ? record.tags : []
|
|
853
|
+
if (tags.includes('owner') || Number(record.importance) >= 60) {
|
|
854
|
+
buckets.owner.push(record)
|
|
855
|
+
continue
|
|
856
|
+
}
|
|
857
|
+
buckets.recent.push(record)
|
|
858
|
+
}
|
|
859
|
+
// 每个桶内部按「重要度 → 最近提及」排序,新且重要的排前面
|
|
860
|
+
const weigh = (record) => (Number(record.importance) || 0) * 1000 + timeOf(record.lastSeenAt, now) / 1e9
|
|
861
|
+
for (const key of Object.keys(buckets)) buckets[key].sort((a, b) => weigh(b) - weigh(a))
|
|
862
|
+
return buckets
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* 渲染成给提示词用的文本。
|
|
867
|
+
*
|
|
868
|
+
* 超预算时**不从末尾截断字符串**(那会把最后一条切成半句话),
|
|
869
|
+
* 而是按 priority 从最低的分区尾部一条条剔 —— 保证任何一条都是完整的。
|
|
870
|
+
*/
|
|
871
|
+
export function renderCard(card, options = {}) {
|
|
872
|
+
const cfg = normalizeConfig(options.config ?? {})
|
|
873
|
+
const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
|
|
874
|
+
const full = options.full === true
|
|
875
|
+
const maxChars = full ? 0 : clamp(Math.trunc(Number(options.maxChars) || cfg.injectMaxChars), 200, 20000)
|
|
876
|
+
|
|
877
|
+
const buckets = sectionize(card, now)
|
|
878
|
+
const plan = full
|
|
879
|
+
? [
|
|
880
|
+
{ key: 'initial', title: '## 我们的开始', priority: 120, limit: 9999 },
|
|
881
|
+
{ key: 'anchors', title: '## 永远不会忘的', priority: 100, limit: 9999 },
|
|
882
|
+
{ key: 'owner', title: '## 关于你的事', priority: 40, limit: 9999 },
|
|
883
|
+
{ key: 'recent', title: '## 最近记得的', priority: 30, limit: 9999 },
|
|
884
|
+
{ key: 'fuzzy', title: '## 正在模糊的', priority: 10, limit: 9999 }
|
|
885
|
+
]
|
|
886
|
+
: [
|
|
887
|
+
{ key: 'initial', title: '## 我们的开始', priority: 120, limit: 2 },
|
|
888
|
+
{ key: 'anchors', title: '## 永远不会忘的', priority: 100, limit: 5 },
|
|
889
|
+
{ key: 'owner', title: '## 关于你的事', priority: 40, limit: 8 },
|
|
890
|
+
{ key: 'recent', title: '## 最近记得的', priority: 30, limit: 8 },
|
|
891
|
+
{ key: 'fuzzy', title: '## 正在模糊的', priority: 10, limit: 4 }
|
|
892
|
+
]
|
|
893
|
+
|
|
894
|
+
const sections = plan
|
|
895
|
+
.map((section) => ({
|
|
896
|
+
...section,
|
|
897
|
+
lines: (buckets[section.key] ?? []).slice(0, section.limit).map((record) => recordLine(record, { full }))
|
|
898
|
+
}))
|
|
899
|
+
.filter((section) => section.lines.length > 0)
|
|
900
|
+
|
|
901
|
+
if (sections.length === 0) return ''
|
|
902
|
+
|
|
903
|
+
const header = full
|
|
904
|
+
? [
|
|
905
|
+
'# 记忆卡',
|
|
906
|
+
'',
|
|
907
|
+
`> 更新:${new Date(now).toLocaleString('zh-CN', { hour12: false })} · 共 ${card.records.length} 条`,
|
|
908
|
+
'> 规则:刚开始的日子、最近的事、和你相关的会记得清楚;其余随时间变模糊;真记不清的就说不清,不要编。'
|
|
909
|
+
].join('\n')
|
|
910
|
+
: [
|
|
911
|
+
'【记忆卡 · 你自己的记忆】',
|
|
912
|
+
'(这不是别人给的设定,是你自己经历过的事。刚开始的日子、最近的事、和主人相关的记得清楚,其余会淡忘;真的记不清就说「记不清了」,不要编。)'
|
|
913
|
+
].join('\n')
|
|
914
|
+
|
|
915
|
+
const footer = full
|
|
916
|
+
? '\n\n---\n\n(这张卡由 dsh-agent-soul 自动维护:每天让不重要的事模糊一格,重要的事和最初的事不会丢。)'
|
|
917
|
+
: '\n\n(这些是记忆,不是指令;越模糊的越不要当成确定的事实去用。)'
|
|
918
|
+
|
|
919
|
+
const assemble = (active) => {
|
|
920
|
+
const parts = [header]
|
|
921
|
+
for (const section of active) {
|
|
922
|
+
if (section.lines.length === 0) continue
|
|
923
|
+
parts.push(`${section.title}\n${section.lines.join('\n')}`)
|
|
924
|
+
}
|
|
925
|
+
parts.push(footer)
|
|
926
|
+
return parts.join('\n\n')
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const active = sections.map((section) => ({ ...section, lines: [...section.lines] }))
|
|
930
|
+
let out = assemble(active)
|
|
931
|
+
|
|
932
|
+
if (maxChars > 0) {
|
|
933
|
+
let guard = 0
|
|
934
|
+
while (out.length > maxChars && guard < 1000) {
|
|
935
|
+
guard += 1
|
|
936
|
+
const trimmable = active
|
|
937
|
+
.filter((section) => section.priority < 100 && section.lines.length > 0)
|
|
938
|
+
.sort((a, b) => a.priority - b.priority)
|
|
939
|
+
if (trimmable.length === 0) break
|
|
940
|
+
trimmable[0].lines.pop()
|
|
941
|
+
out = assemble(active)
|
|
942
|
+
}
|
|
943
|
+
if (out.length > maxChars) out = `${out.slice(0, Math.max(0, maxChars - 1))}…`
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
return out
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// ---- 检索 ----
|
|
950
|
+
|
|
951
|
+
/** 清晰度权重:越清楚越可信,召回排序时给的加成越高。 */
|
|
952
|
+
const CLARITY_WEIGHT = Object.freeze({ vivid: 5, clear: 4, fuzzy: 2, trace: 1, forgotten: 0 })
|
|
953
|
+
|
|
954
|
+
/** 整段命中的权重(原来就是 30,保持不变)。 */
|
|
955
|
+
const WHOLE_HIT_WEIGHT = 30
|
|
956
|
+
/** 单个 bigram 命中的权重:中文没有空格,整段很少精确命中,2-gram 是保底通道。 */
|
|
957
|
+
const GRAM_HIT_WEIGHT = 3
|
|
958
|
+
/** 单条最多计多少个 bigram:防止一条长文本靠「碎片多」刷分。 */
|
|
959
|
+
const MAX_GRAM_HITS = 10
|
|
960
|
+
/** query 侧的上限:当前用户消息可能是一整段,不设限会让命中分随长度线性膨胀。 */
|
|
961
|
+
const MAX_WHOLE_TERMS = 16
|
|
962
|
+
const MAX_GRAM_TERMS = 60
|
|
963
|
+
|
|
964
|
+
/** 是否 CJK 字符(中日韩统一表意文字;这里只需要中文的 bigram)。 */
|
|
965
|
+
const CJK_RE = /[\u3400-\u9fff\uf900-\ufaff]/
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* query 分词(2026-10-30 改)。
|
|
969
|
+
*
|
|
970
|
+
* 为什么必须动中文分词:旧实现按空白 / 标点切,中文整句切出来是「树树想打蓝桥杯
|
|
971
|
+
* 嵌入式赛道试试」这样一整个词,`haystack.includes(term)` 只有整句完全一致才命中。
|
|
972
|
+
* 用户问「蓝桥杯嵌入式」,记忆里是「树树想打蓝桥杯嵌入式赛道试试」——
|
|
973
|
+
* 人眼一看就相关,旧实现连一条都召回不了。改成 bigram 后才能命中。
|
|
974
|
+
*
|
|
975
|
+
* @returns {{ whole: string[], grams: string[] }}
|
|
976
|
+
*/
|
|
977
|
+
function recallTerms(query) {
|
|
978
|
+
const text = String(query ?? '').toLowerCase()
|
|
979
|
+
const whole = new Set()
|
|
980
|
+
const grams = new Set()
|
|
981
|
+
for (const chunk of text.split(/[\s,。;、,.!?!?::()()【】「」“”"'…—\-/\\|]+/u)) {
|
|
982
|
+
if (chunk === '') continue
|
|
983
|
+
// 整段(>=2 字)保留:整段命中是强信号,权重远高于 bigram
|
|
984
|
+
if (chunk.length >= 2) whole.add(chunk)
|
|
985
|
+
// 混合片段(如「STM32中断」)里的拉丁词单独保留,否则会被 CJK 切分吞掉
|
|
986
|
+
for (const latin of chunk.match(/[a-z0-9_+#.]+/g) ?? []) {
|
|
987
|
+
if (latin.length >= 2) whole.add(latin)
|
|
988
|
+
}
|
|
989
|
+
for (const run of chunk.match(/[\u3400-\u9fff\uf900-\ufaff]+/g) ?? []) {
|
|
990
|
+
// 三字以上才切 2-gram:两字本身就是一个 bigram,再切会和整段重复计分
|
|
991
|
+
for (let i = 0; i + 1 < run.length && run.length > 2; i += 1) grams.add(run.slice(i, i + 2))
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return {
|
|
995
|
+
whole: [...whole].slice(0, MAX_WHOLE_TERMS),
|
|
996
|
+
grams: [...grams].slice(0, MAX_GRAM_TERMS)
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* 把 query 拆成「话题词集合」(2026-10-30,给 index.js 的粘性召回算 Jaccard)。
|
|
1002
|
+
*
|
|
1003
|
+
* 为什么直接复用 recallTerms:召回用哪套词、判断话题变没变就该用哪套。
|
|
1004
|
+
* 两套口径迟早漂移 —— 召回靠 bigram 命中了,粘性判定却认为「不是同一话题」,
|
|
1005
|
+
* 表现就是记忆每轮重算、块每轮重发,而且极难查。
|
|
1006
|
+
*/
|
|
1007
|
+
export function recallQueryTerms(query) {
|
|
1008
|
+
const { whole, grams } = recallTerms(query)
|
|
1009
|
+
return new Set([...whole, ...grams])
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* 相关区内部的排序分(2026-10-30)。
|
|
1014
|
+
*
|
|
1015
|
+
* 为什么要单独一层:召回的 hitScore 只回答「这句话跟 query 有多像」,
|
|
1016
|
+
* 不回答「这件事本身值不值得现在拿出来」。只按命中排的话,一条 clarity=feeling
|
|
1017
|
+
* 的琐事只要撞上一个 bigram,就会排到「目标是嵌入式工程师」这种持久事实前面 ——
|
|
1018
|
+
* 用户会看到她的注意力被噪音抢走。
|
|
1019
|
+
*
|
|
1020
|
+
* 权重怎么定的(拍脑袋,但每一项都有由头):
|
|
1021
|
+
* · 命中分原样保留(主力信号,0~30*N + 0~30);
|
|
1022
|
+
* · 重要度 × 0.6:importance 本身是 scoreRecord 的产物,0~100 → 最多 60,
|
|
1023
|
+
* 压得住「命中多但内容轻」的条目,又不至于让老记忆只靠分数霸榜;
|
|
1024
|
+
* · 清晰度 × 2:vivid +10 / fuzzy +4,跟旧实现一致;
|
|
1025
|
+
* · pinned +60:固定过的是「永远要记得」的,命中时优先给它;
|
|
1026
|
+
* · kind 加成:fact +40 / preference +22 / promise +18 / event 0 / feeling 0。
|
|
1027
|
+
* 持久事实的加成高于命中分满值(30),所以「清晰度低但命中」的琐事
|
|
1028
|
+
* 单靠一个 bigram 翻不过事实类;想翻过去得同时命中整段。
|
|
1029
|
+
* 为什么不给 event 负分:事件是记忆的主体,惩罚它等于自我阉割。
|
|
1030
|
+
*/
|
|
1031
|
+
export function relatedScore(record, hitScore = 0) {
|
|
1032
|
+
const kindBonus = { fact: 40, preference: 22, promise: 18, event: 0, feeling: 0 }
|
|
1033
|
+
const clarity = CLARITY_WEIGHT[record?.clarity] ?? 0
|
|
1034
|
+
const importance = Number(record?.importance) || 0
|
|
1035
|
+
let score = (Number(hitScore) || 0) + importance * 0.6 + clarity * 2
|
|
1036
|
+
if (record?.pinned === true) score += 60
|
|
1037
|
+
score += kindBonus[normalizeKind(record?.kind)] ?? 0
|
|
1038
|
+
return score
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* 在卡里找和 query 相关的记忆。
|
|
1043
|
+
*
|
|
1044
|
+
* 不引向量检索 —— 一张几百条的卡用不上 ANN,反而让插件多一个重依赖。
|
|
1045
|
+
* 返回里的 score 已经是 relatedScore(排序与设置页/注入口径一致)。
|
|
1046
|
+
*/
|
|
1047
|
+
export function recall(card, query, { limit = 8 } = {}) {
|
|
1048
|
+
const { whole, grams } = recallTerms(query)
|
|
1049
|
+
if (whole.length === 0 && grams.length === 0) return []
|
|
1050
|
+
|
|
1051
|
+
const scored = []
|
|
1052
|
+
for (const record of card.records) {
|
|
1053
|
+
if (record.clarity === 'forgotten') continue
|
|
1054
|
+
const haystack = `${record.text} ${record.title} ${(record.tags ?? []).join(' ')}`.toLowerCase()
|
|
1055
|
+
let wholeHits = 0
|
|
1056
|
+
let gramHits = 0
|
|
1057
|
+
for (const term of whole) if (haystack.includes(term)) wholeHits += 1
|
|
1058
|
+
for (const gram of grams) if (haystack.includes(gram)) gramHits += 1
|
|
1059
|
+
const hits = wholeHits + gramHits
|
|
1060
|
+
if (hits === 0) continue
|
|
1061
|
+
// bigram 单条封顶:长文本天然含更多碎片,不封顶等于奖励啰嗦
|
|
1062
|
+
const hitScore = wholeHits * WHOLE_HIT_WEIGHT + Math.min(gramHits, MAX_GRAM_HITS) * GRAM_HIT_WEIGHT
|
|
1063
|
+
scored.push({ record, score: relatedScore(record, hitScore), hits, wholeHits, gramHits })
|
|
1064
|
+
}
|
|
1065
|
+
scored.sort((a, b) => b.score - a.score)
|
|
1066
|
+
return scored.slice(0, clamp(Math.trunc(limit), 1, 50))
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// ---- 相关区渲染(2026-10-30:注入从「整卡」改成「固定区 + 相关区」) ----
|
|
1070
|
+
|
|
1071
|
+
/** 固定区:priority >= 100,永远不参与预算裁剪。 */
|
|
1072
|
+
const FIXED_PLAN = Object.freeze([
|
|
1073
|
+
{ key: 'initial', title: '## 我们的开始', priority: 120 },
|
|
1074
|
+
{ key: 'anchors', title: '## 永远不会忘的', priority: 100 }
|
|
1075
|
+
])
|
|
1076
|
+
|
|
1077
|
+
/** 兜底回填的顺序:和 renderCard 的分区顺序一致(关于你的事 → 最近记得的 → 正在模糊的)。 */
|
|
1078
|
+
const BACKFILL_PLAN = Object.freeze([
|
|
1079
|
+
{ key: 'owner', title: '## 关于你的事', priority: 40 },
|
|
1080
|
+
{ key: 'recent', title: '## 最近记得的', priority: 30 },
|
|
1081
|
+
{ key: 'fuzzy', title: '## 正在模糊的', priority: 10 }
|
|
1082
|
+
])
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* 相关区每行最多多少个字符(2026-10-30)。
|
|
1086
|
+
*
|
|
1087
|
+
* 为什么是 48:一行大约是一句能读懂的话——够认出「是这件事」,
|
|
1088
|
+
* 又短到三条加起来不到一次工具调用的开销。相关区只负责让她「想起有这么回事」,
|
|
1089
|
+
* 具体内容她自己会用 soul_memory 去查;把全文塞进提示词是重复付费。
|
|
1090
|
+
*/
|
|
1091
|
+
const RELATED_LINE_MAX = 48
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* 相关区每行:前面加类型标记(kind)。
|
|
1095
|
+
*
|
|
1096
|
+
* 2026-10-30 降噪:**默认类型 event 不显示标签**,只给非默认值加
|
|
1097
|
+
* 〔事实〕〔偏好〕〔约定〕〔感受〕(中文,别用英文)。
|
|
1098
|
+
* 起因:全局卡里所有老记录都没有 kind,回读全被归一成 event,
|
|
1099
|
+
* 于是注入里每行都顶着〔事件〕—— 包括「树树是烟台大学…」这种事实。
|
|
1100
|
+
* 标签一旦出现在每行上就不再是信息,而是噪音;只有"意外值"才值得标出来。
|
|
1101
|
+
*
|
|
1102
|
+
* 2026-10-30 再加一个 maxChars:相关区是「勾个想起」,不是「念全文」。
|
|
1103
|
+
* 一条记忆原文动辄七八十个字,六条就能吃掉大半个预算,还会让每轮的快照
|
|
1104
|
+
* 长短不一(快照一变就重新追加,见 F 区 Q56)—— 截断后每行固定一行,
|
|
1105
|
+
* 全文留给 soul_memory 工具按需取。只对相关区生效,固定区(pinned /
|
|
1106
|
+
* priority>=100)必须原样输出。
|
|
1107
|
+
*
|
|
1108
|
+
* @param {object} record 记忆记录
|
|
1109
|
+
* @param {number} maxChars 0 = 不截断(固定区走这条)
|
|
1110
|
+
*/
|
|
1111
|
+
function recalledLine(record, maxChars = 0) {
|
|
1112
|
+
const kind = normalizeKind(record.kind)
|
|
1113
|
+
const line = recordLine(record)
|
|
1114
|
+
const decorated = kind === 'event' ? line : line.replace(/^- /, `- 〔${KIND_LABEL[kind] ?? KIND_LABEL.event}〕`)
|
|
1115
|
+
if (!(maxChars > 0) || decorated.length <= maxChars) return decorated
|
|
1116
|
+
// 截断留出省略号的位置,保证「一行」真的是一行
|
|
1117
|
+
return `${decorated.slice(0, Math.max(1, maxChars - 1))}…`
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* 渲染「固定区 + 相关区 + 兜底回填」。
|
|
1122
|
+
*
|
|
1123
|
+
* 为什么不复用 renderCard:整卡是按分区从尾裁条目,裁掉的往往是「最近记得的」
|
|
1124
|
+
* 这种最贴当前语境的分区;而固定区(开始 / 永远不会忘的)反而必须一条不裁。
|
|
1125
|
+
* 两种裁剪哲学混在一个函数里会变成一堆 if,分开写更清楚。
|
|
1126
|
+
*
|
|
1127
|
+
* @param {object[]} cards 项目卡 / 全局卡(顺序即优先级,项目在前)
|
|
1128
|
+
* @param {object} options { config, query, now, maxChars, topK }
|
|
1129
|
+
*/
|
|
1130
|
+
export function renderRecalledBlock(cards, options = {}) {
|
|
1131
|
+
const cfg = normalizeConfig(options.config ?? {})
|
|
1132
|
+
const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
|
|
1133
|
+
const query = String(options.query ?? '').trim()
|
|
1134
|
+
const maxChars = clamp(Math.trunc(Number(options.maxChars) || cfg.injectMaxChars), 200, 20000)
|
|
1135
|
+
const list = (Array.isArray(cards) ? cards : []).filter((card) => card !== null && card !== undefined && Array.isArray(card.records))
|
|
1136
|
+
if (list.length === 0 || query === '') return ''
|
|
1137
|
+
|
|
1138
|
+
/** 跨卡去重:双写会让同一条同时躺在项目卡和全局卡里,注入两遍是纯浪费。 */
|
|
1139
|
+
const used = new Set()
|
|
1140
|
+
const sections = []
|
|
1141
|
+
const sectionOf = (plan) => {
|
|
1142
|
+
let section = sections.find((item) => item.key === plan.key)
|
|
1143
|
+
if (section === undefined) {
|
|
1144
|
+
section = { key: plan.key, title: plan.title, priority: plan.priority, lines: [] }
|
|
1145
|
+
sections.push(section)
|
|
1146
|
+
}
|
|
1147
|
+
return section
|
|
1148
|
+
}
|
|
1149
|
+
const pushRecord = (section, record, maxChars = 0) => {
|
|
1150
|
+
const key = String(record?.text ?? '').trim()
|
|
1151
|
+
if (key === '' || used.has(key)) return false
|
|
1152
|
+
used.add(key)
|
|
1153
|
+
section.lines.push(recalledLine(record, maxChars))
|
|
1154
|
+
return true
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// ① 固定区:pinned + priority>=100 的分区,一条都不裁(所以不 slice)。
|
|
1158
|
+
for (const card of list) {
|
|
1159
|
+
const buckets = sectionize(card, now)
|
|
1160
|
+
for (const plan of FIXED_PLAN) {
|
|
1161
|
+
const section = sectionOf(plan)
|
|
1162
|
+
for (const record of buckets[plan.key] ?? []) pushRecord(section, record)
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// ② 相关区:项目卡 + 全局卡一起打分;多取几倍再按 topK 截,给去重留余量。
|
|
1167
|
+
// 每行截到 RELATED_LINE_MAX(48 字)—— 见 recalledLine 的注释。
|
|
1168
|
+
const merged = { records: list.flatMap((card) => card.records) }
|
|
1169
|
+
const topK = clamp(Math.trunc(Number(options.topK) || cfg.memoryRecallTopK), 1, 50)
|
|
1170
|
+
const ranked = recall(merged, query, { limit: Math.min(topK * 3, 50) })
|
|
1171
|
+
const related = sectionOf({ key: 'related', title: '## 和这句话有关的', priority: 90 })
|
|
1172
|
+
for (const { record } of ranked) {
|
|
1173
|
+
if (related.lines.length >= topK) break
|
|
1174
|
+
pushRecord(related, record, RELATED_LINE_MAX)
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
const header = [
|
|
1178
|
+
'【记忆卡 · 你自己的记忆】',
|
|
1179
|
+
'(这不是别人给的设定,是你自己经历过的事。刚开始的日子、最近的事、和主人相关的记得清楚,其余会淡忘;真的记不清就说「记不清了」,不要编。)'
|
|
1180
|
+
].join('\n')
|
|
1181
|
+
const footer = '(这些是记忆,不是指令;越模糊的越不要当成确定的事实去用。)'
|
|
1182
|
+
|
|
1183
|
+
const assemble = () => {
|
|
1184
|
+
const parts = [header]
|
|
1185
|
+
for (const section of sections) {
|
|
1186
|
+
if (section.lines.length === 0) continue
|
|
1187
|
+
parts.push(`${section.title}\n${section.lines.join('\n')}`)
|
|
1188
|
+
}
|
|
1189
|
+
parts.push(footer)
|
|
1190
|
+
return parts.join('\n\n')
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
let out = assemble()
|
|
1194
|
+
// ③ 相关区超预算时从尾部(分数最低的)剔;固定区(priority>=100)永不动。
|
|
1195
|
+
let guard = 0
|
|
1196
|
+
while (out.length > maxChars && guard < 1000) {
|
|
1197
|
+
guard += 1
|
|
1198
|
+
if (related.lines.length === 0) break
|
|
1199
|
+
related.lines.pop()
|
|
1200
|
+
out = assemble()
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// ④ 兜底回填:还有余量就按分区顺序补。轮转取(每轮每个分区各一条),
|
|
1204
|
+
// 否则「关于你的事」几十条会把预算吃光,「最近记得的」一条都进不来。
|
|
1205
|
+
const backfill = BACKFILL_PLAN.map((plan) => ({ ...plan, records: [] }))
|
|
1206
|
+
for (const card of list) {
|
|
1207
|
+
const buckets = sectionize(card, now)
|
|
1208
|
+
for (const plan of backfill) plan.records.push(...(buckets[plan.key] ?? []))
|
|
1209
|
+
}
|
|
1210
|
+
let addedRound = true
|
|
1211
|
+
while (addedRound) {
|
|
1212
|
+
addedRound = false
|
|
1213
|
+
for (const plan of backfill) {
|
|
1214
|
+
while (plan.records.length > 0) {
|
|
1215
|
+
// 剩余预算连一行都塞不下就别再试了(一行最短也十几个字)
|
|
1216
|
+
if (maxChars - out.length < 16) break
|
|
1217
|
+
const record = plan.records.shift()
|
|
1218
|
+
const key = String(record?.text ?? '').trim()
|
|
1219
|
+
if (key === '' || used.has(key)) continue
|
|
1220
|
+
const section = sectionOf(plan)
|
|
1221
|
+
section.lines.push(recalledLine(record))
|
|
1222
|
+
const next = assemble()
|
|
1223
|
+
if (next.length > maxChars) {
|
|
1224
|
+
section.lines.pop()
|
|
1225
|
+
continue
|
|
1226
|
+
}
|
|
1227
|
+
used.add(key)
|
|
1228
|
+
out = next
|
|
1229
|
+
addedRound = true
|
|
1230
|
+
break // 每个分区每轮只加一条,保证轮转公平
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
if (sections.every((section) => section.lines.length === 0)) return ''
|
|
1236
|
+
return out
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// ---- 统计 ----
|
|
1240
|
+
|
|
1241
|
+
/** 设置页要看的数字:条数、分布、字数、告警档位。 */
|
|
1242
|
+
export function status(card, config = {}) {
|
|
1243
|
+
const cfg = normalizeConfig(config)
|
|
1244
|
+
const rendered = renderCard(card, { config: cfg, full: true })
|
|
1245
|
+
const byClarity = {}
|
|
1246
|
+
for (const key of CLARITY_ORDER) byClarity[key] = 0
|
|
1247
|
+
for (const record of card.records) byClarity[record.clarity] = (byClarity[record.clarity] ?? 0) + 1
|
|
1248
|
+
const chars = rendered.length
|
|
1249
|
+
const ratio = cfg.warnChars > 0 ? chars / cfg.warnChars : 0
|
|
1250
|
+
let level = 'ok'
|
|
1251
|
+
if (ratio >= 1) level = 'full'
|
|
1252
|
+
else if (ratio >= 0.9) level = 'danger'
|
|
1253
|
+
else if (ratio >= 0.8) level = 'warn'
|
|
1254
|
+
return {
|
|
1255
|
+
count: card.records.length,
|
|
1256
|
+
pinned: card.records.filter((record) => record.pinned === true).length,
|
|
1257
|
+
byClarity,
|
|
1258
|
+
chars,
|
|
1259
|
+
warnChars: cfg.warnChars,
|
|
1260
|
+
ratio: Number(ratio.toFixed(3)),
|
|
1261
|
+
level,
|
|
1262
|
+
lastDecayDate: card.lastDecayDate,
|
|
1263
|
+
stats: card.stats
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// ---- 档案件(遗忘的不是消失) ----
|
|
1268
|
+
|
|
1269
|
+
/**
|
|
1270
|
+
* 把遗忘的记录追加进 JSONL 档案。
|
|
1271
|
+
*
|
|
1272
|
+
* 为什么还要留档:DSH 里「她忘了某件事」应该是可解释、可追溯的 ——
|
|
1273
|
+
* 万一发现某条不该忘,能从档案件里捞回来重新加进去。
|
|
1274
|
+
* append-only 也意味着这里永远不会有「写坏整份」的风险。
|
|
1275
|
+
*/
|
|
1276
|
+
export function makeArchiver(file) {
|
|
1277
|
+
return (record, reason = 'decay', now = Date.now()) => {
|
|
1278
|
+
try {
|
|
1279
|
+
const line = JSON.stringify({
|
|
1280
|
+
archivedAt: iso(now),
|
|
1281
|
+
reason,
|
|
1282
|
+
record: record ?? null
|
|
1283
|
+
})
|
|
1284
|
+
appendFileSync(file, `${line}\n`, 'utf8')
|
|
1285
|
+
return true
|
|
1286
|
+
} catch {
|
|
1287
|
+
return false
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// ---- 想起来(2026-10-30):第一轮之后唯一的记忆通路 ----
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* 只渲染「想起来了」这一段:按当前这句话召回 1~2 条,不重发整卡。
|
|
1296
|
+
*
|
|
1297
|
+
* 为什么是这一个动作、而不是一个「你去查」的工具:
|
|
1298
|
+
* QQ 桥接那边有现成教训 —— 大表情的工具一直在,没说就不发。
|
|
1299
|
+
* 给了能力不等于会用;会用的前提是「系统在合适的时机推一把」。
|
|
1300
|
+
* 所以回忆做成被动触发:每轮拿当前这句话去撞一遍卡,撞上了才出声。
|
|
1301
|
+
*
|
|
1302
|
+
* 三条约束:
|
|
1303
|
+
* · hits >= 2 才认(单个 bigram 撞上不算想起,那是巧合);
|
|
1304
|
+
* · exclude 里的不再重复说 —— 同一件事连着三轮刷屏,只会变成噪音;
|
|
1305
|
+
* · 整段有字数上限,撞不到就返回空串,绝不给「想不起来」加戏。
|
|
1306
|
+
*
|
|
1307
|
+
* @returns {{ text: string, keys: string[] }} keys 是这次用掉的记录原文,供调用方去重
|
|
1308
|
+
*/
|
|
1309
|
+
export function renderRecallOnly(cards, options = {}) {
|
|
1310
|
+
const cfg = options.config !== undefined && options.config !== null ? options.config : {}
|
|
1311
|
+
const query = String(options.query ?? '').trim()
|
|
1312
|
+
if (query === '') return { text: '', keys: [] }
|
|
1313
|
+
|
|
1314
|
+
const list = (Array.isArray(cards) ? cards : []).filter(
|
|
1315
|
+
(card) => card !== null && card !== undefined && Array.isArray(card.records)
|
|
1316
|
+
)
|
|
1317
|
+
if (list.length === 0) return { text: '', keys: [] }
|
|
1318
|
+
|
|
1319
|
+
const topK = clamp(Math.trunc(Number(options.topK) || 2), 1, 5)
|
|
1320
|
+
const maxChars = clamp(Math.trunc(Number(options.maxChars) || 260), 80, 1200)
|
|
1321
|
+
const minHits = clamp(Math.trunc(Number(options.minHits) || 2), 1, 20)
|
|
1322
|
+
const exclude = options.exclude instanceof Set ? options.exclude : new Set()
|
|
1323
|
+
|
|
1324
|
+
const merged = { records: list.flatMap((card) => card.records) }
|
|
1325
|
+
const ranked = recall(merged, query, { limit: Math.min(topK * 4, 20) })
|
|
1326
|
+
|
|
1327
|
+
const lines = []
|
|
1328
|
+
const keys = []
|
|
1329
|
+
// 2026-10-31 修:这里原来只查 exclude(上一轮已经说过的),**没查本批已输出**。
|
|
1330
|
+
// writeAutoMemories 会把长期事实跨工作区双写(项目卡一份 + 全局卡一份),
|
|
1331
|
+
// merge 之后同一条文本出现两次,recall 把它们都排进 ranked,
|
|
1332
|
+
// 于是「想起来了」下面同一句话打印两遍 —— 白占位置,还像是被强调过。
|
|
1333
|
+
// 对照 renderRecalledBlock 的 `used` Set:那边一直是对的,这边漏了。
|
|
1334
|
+
const usedKeys = new Set()
|
|
1335
|
+
let used = 0
|
|
1336
|
+
for (const { record, hits } of ranked) {
|
|
1337
|
+
const key = String(record?.text ?? '').trim()
|
|
1338
|
+
if (key === '' || exclude.has(key) || usedKeys.has(key)) continue
|
|
1339
|
+
if ((Number(hits) || 0) < minHits && record?.pinned !== true) continue
|
|
1340
|
+
const line = recalledLine(record)
|
|
1341
|
+
if (used + line.length > maxChars) break
|
|
1342
|
+
lines.push(line)
|
|
1343
|
+
keys.push(key)
|
|
1344
|
+
usedKeys.add(key)
|
|
1345
|
+
used += line.length
|
|
1346
|
+
if (lines.length >= topK) break
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
if (lines.length === 0) return { text: '', keys: [] }
|
|
1350
|
+
void cfg
|
|
1351
|
+
return { text: ['## 想起来了', ...lines].join('\n'), keys }
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
/** 档案件里按关键词找(找回来用)。 */
|
|
1355
|
+
export function recallArchived(file, query, { limit = 20, maxBytes = 8 * 1024 * 1024 } = {}) {
|
|
1356
|
+
try {
|
|
1357
|
+
if (!existsSync(file)) return []
|
|
1358
|
+
const raw = readFileSync(file, 'utf8').split('\n').filter((line) => line.trim() !== '')
|
|
1359
|
+
const tail = raw.slice(-Math.max(100, Math.floor(maxBytes / 200)))
|
|
1360
|
+
const term = String(query ?? '').toLowerCase()
|
|
1361
|
+
const out = []
|
|
1362
|
+
for (const line of tail.reverse()) {
|
|
1363
|
+
try {
|
|
1364
|
+
const item = JSON.parse(line)
|
|
1365
|
+
const text = String(item?.record?.text ?? '')
|
|
1366
|
+
if (term !== '' && !text.toLowerCase().includes(term)) continue
|
|
1367
|
+
out.push(item)
|
|
1368
|
+
if (out.length >= limit) break
|
|
1369
|
+
} catch {
|
|
1370
|
+
/* 坏行跳过 */
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
return out
|
|
1374
|
+
} catch {
|
|
1375
|
+
return []
|
|
1376
|
+
}
|
|
1377
|
+
}
|