feiyu-brain 1.4.2 → 1.5.1

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/core/memory.js CHANGED
@@ -4,12 +4,367 @@
4
4
  // 核心:忘了就是真的没有(不是"想不起来")。
5
5
 
6
6
  export const DAY_MS = 24 * 60 * 60 * 1000;
7
- export const TTL_DAYS = { episode: 30, impression: 90, imagination: 30, card: 30, fact: Infinity, taste: Infinity };
8
- export const PROMOTE_DAYS = 15;
7
+
8
+ /**
9
+ * 记忆的三段生命周期(参数按需求定死):
10
+ *
11
+ * 完整记忆 ──21 天没人提──→ 记忆卡片 ──2 年没人提──→ 遗忘
12
+ * ↑ ↑ 有人提:+30 天
13
+ * └────────────────────────┘ 连续提 15 天:升级长期记忆(2 年)
14
+ * 长期到期 → 降回卡片,重新走一圈
15
+ *
16
+ * 计时全部是「多久没人提」,不是「存了多久」。
17
+ * 每条记忆上挂一个 `expiresAt`(绝对时间),到期就往下走一级。
18
+ */
19
+ export const FULL_DAYS = 21; // 完整记忆能躺多久
20
+ export const CARD_DAYS = 730; // 卡片能躺多久(2 年)
21
+ export const LONG_DAYS = 730; // 长期记忆能躺多久(2 年)
22
+ export const EXTEND_DAYS = 30; // 被提一次,卡片续命多少天
23
+ export const PROMOTE_DAYS = 15; // 连续提这么多天 → 长期
24
+
25
+ /** 兼容旧名字 */
26
+ export const COMPRESS_DAYS = FULL_DAYS;
27
+ export const FORGET_DAYS = CARD_DAYS;
28
+
29
+ export const TTL_DAYS = { episode: CARD_DAYS, impression: CARD_DAYS, imagination: CARD_DAYS, card: CARD_DAYS, fact: Infinity, taste: Infinity };
30
+
9
31
  export const RETRIEVE_BUDGET_CHARS = 900; // ≈800 token(中文约 1.1~1.3 字/token)
10
32
  export const CARD_THRESHOLD_CHARS = 6000; // 上下文超过这个数就该压卡片
11
33
  export const CARD_MAX_CHARS = 160;
12
34
 
35
+ /** 兼容老名字 */
36
+ export const TTL_COMPRESS_DAYS = FULL_DAYS;
37
+
38
+ /* ── 记忆层级:纲比细节活得久 ─────────────────────────────────
39
+ *
40
+ * 细节(episode)→ 卡片(card)→ **纲(gist)**
41
+ *
42
+ * 人记不住小学每节课,但知道"我上过小学"。
43
+ * 那个"知道"就是纲——它不该跟细节一起烂掉。
44
+ *
45
+ * 纲是**提炼**出来的,不是人写的:
46
+ * · 人物纲:跟某人聊够 N 次 → 一条"认识他"的纲
47
+ * · 主题纲:同一个话题反复出现 → 一条"这事发生过 N 次"的纲
48
+ *
49
+ * 纲永不老化(但会随新事实更新文案)。
50
+ */
51
+
52
+ export const GIST_MIN_COUNT = 3;
53
+ /** 多久没提就把名字降级成"有个认识的" */
54
+ export const NAME_FADE_DAYS = 1095; // 3 年
55
+
56
+ function dayStr(ms) {
57
+ if (!ms) return '';
58
+ try { return new Date(ms).toISOString().slice(0, 10); } catch { return ''; }
59
+ }
60
+
61
+ /**
62
+ * 提炼纲。幂等:同一主题只会有一条,文案随次数更新。
63
+ */
64
+ export function distillGists(memory, now = Date.now(), { minCount = GIST_MIN_COUNT } = {}) {
65
+ const gists = new Map((memory.gists ?? []).map((g) => [g.id, g]));
66
+
67
+ // ① 人物纲:聊够次数的人,不能因为细节烂掉就"查无此人"
68
+ for (const [who, im] of Object.entries(memory.impressions ?? {})) {
69
+ const count = Number(im.count ?? 0);
70
+ if (!who || count < minCount) continue;
71
+ const id = `g_person_${who}`;
72
+ const stale = now - Number(im.lastAt ?? 0) > NAME_FADE_DAYS * DAY_MS;
73
+ gists.set(id, {
74
+ id,
75
+ kind: 'gist',
76
+ topic: 'person',
77
+ who,
78
+ text: stale
79
+ ? `有个认识的(${who}),聊过 ${count} 次,最后一次是 ${dayStr(im.lastAt)}——名字有点想不起来了`
80
+ : `${who}:认识,聊过 ${count} 次,最近一次 ${dayStr(im.lastAt)}`,
81
+ count,
82
+ lastAt: Number(im.lastAt ?? 0),
83
+ at: gists.get(id)?.at ?? now,
84
+ });
85
+ }
86
+
87
+ // ② 主题纲:反复出现的词,从卡片和细节里提炼
88
+ // 只认"实词"——含虚词的二元组(「了上」「的第」「学的」)一律不要
89
+ const FUNC = new Set('的了是我你他她它这那就都也还很不在有和与或但而并没被把给对从到为着过吗呢吧啊呀嘛哦嗯一个些么什怎样'.split(''));
90
+ const isRealWord = (g) => g.length === 2 && !FUNC.has(g[0]) && !FUNC.has(g[1]) && !STOP_GRAMS.has(g);
91
+
92
+ const df = new Map(); // 出现在多少条不同经历里
93
+ const days = new Map(); // 横跨多少天(同一天刷十遍不算"反复出现的主题")
94
+ for (const e of [...(memory.episodes ?? []), ...(memory.cards ?? [])]) {
95
+ const t = String(e.what ?? e.text ?? '');
96
+ if (t.length < 4) continue;
97
+ const day = dayStr(e.at ?? e.cardedAt ?? now);
98
+ const seen = new Set();
99
+ for (const g of bigrams(t)) {
100
+ if (!isRealWord(g) || seen.has(g)) continue;
101
+ seen.add(g);
102
+ df.set(g, (df.get(g) ?? 0) + 1);
103
+ if (!days.has(g)) days.set(g, new Set());
104
+ days.get(g).add(day);
105
+ }
106
+ }
107
+ // 要同时满足:出现够多次 + 横跨至少两天。跨天是关键——同一天重复是刷屏,不是主题。
108
+ const topics = [...df.entries()]
109
+ .filter(([g, n]) => n >= minCount && (days.get(g)?.size ?? 0) >= 2)
110
+ .sort((a, b) => b[1] - a[1])
111
+ .slice(0, 2);
112
+
113
+ // 主题的时间跨度:横跨半年以上才可能长成"伞"
114
+ const spanOf = (g) => {
115
+ let first = Infinity;
116
+ let last = 0;
117
+ for (const e of [...(memory.episodes ?? []), ...(memory.cards ?? [])]) {
118
+ const t = String(e.what ?? e.text ?? '');
119
+ if (!t.includes(g)) continue;
120
+ const at = Number(e.at ?? e.cardedAt ?? 0);
121
+ if (!at) continue;
122
+ if (at < first) first = at;
123
+ if (at > last) last = at;
124
+ }
125
+ if (!Number.isFinite(first)) return { firstAt: 0, lastAt: 0, spanDays: 0 };
126
+ return { firstAt: first, lastAt: last, spanDays: Math.round((last - first) / DAY_MS) };
127
+ };
128
+ for (const [word, n] of topics) {
129
+ const id = `g_topic_${word}`;
130
+ const span = spanOf(word);
131
+ gists.set(id, {
132
+ id,
133
+ kind: 'gist',
134
+ topic: 'theme',
135
+ keyword: word,
136
+ text: `「${word}」这件事,前后出现过 ${n} 次`,
137
+ count: n,
138
+ firstAt: span.firstAt,
139
+ lastAt: span.lastAt,
140
+ spanDays: span.spanDays,
141
+ at: gists.get(id)?.at ?? now,
142
+ });
143
+ }
144
+ // 已经不成立的主题纲要清掉(比如旧话题再没出现)
145
+ for (const [id, g] of gists) {
146
+ if (g.topic === 'theme' && !topics.some(([w]) => `g_topic_${w}` === id)) gists.delete(id);
147
+ }
148
+
149
+ memory.gists = [...gists.values()];
150
+ return memory.gists.length;
151
+ }
152
+
153
+ /** 名字还能不能想起来 */
154
+ export function nameFaded(impression, now = Date.now()) {
155
+ if (!impression) return true;
156
+ return now - Number(impression.lastAt ?? 0) > NAME_FADE_DAYS * DAY_MS;
157
+ }
158
+
159
+ /* ── 伞:纲之上那一层,不可再分 ───────────────────────────────
160
+ *
161
+ * 细节 → 卡片 → 纲 → **伞**
162
+ *
163
+ * 纲是"这事出现过 5 次",伞是"我上过学""扶摇是我熟人"。
164
+ * 伞不记次数、不记日期,只记**结构**——它是你介绍自己时说的那种话。
165
+ *
166
+ * 什么时候长出来:
167
+ * · 一个主题横跨半年以上、反复出现 → 它已经是你人生的一段
168
+ * · 一个人聊过十次以上 → 他已经在你生活里
169
+ */
170
+
171
+ export const UMBRELLA_MIN_SPAN_DAYS = 180;
172
+ export const UMBRELLA_MIN_PERSON_COUNT = 10;
173
+ export const UMBRELLA_MAX = 24;
174
+
175
+ function ym(ms) {
176
+ if (!ms) return '';
177
+ try { return new Date(ms).toISOString().slice(0, 7); } catch { return ''; }
178
+ }
179
+
180
+ /**
181
+ * 从已有的纲提炼伞。幂等,重复调用不会重复长。
182
+ */
183
+ export function distillUmbrellas(memory, now = Date.now()) {
184
+ const umbrellas = new Map((memory.umbrellas ?? []).map((u) => [u.id, u]));
185
+
186
+ for (const g of memory.gists ?? []) {
187
+ if (g.topic === 'person') {
188
+ if ((g.count ?? 0) < UMBRELLA_MIN_PERSON_COUNT) continue;
189
+ const id = `u_person_${g.who}`;
190
+ umbrellas.set(id, {
191
+ id,
192
+ kind: 'umbrella',
193
+ topic: 'person',
194
+ who: g.who,
195
+ text: `${g.who}:一直在的人`,
196
+ at: umbrellas.get(id)?.at ?? now,
197
+ });
198
+ continue;
199
+ }
200
+
201
+ if (g.topic === 'theme' || g.topic === 'model') {
202
+ const span = Number(g.spanDays ?? 0);
203
+ const count = Number(g.count ?? 0);
204
+ if (span < UMBRELLA_MIN_SPAN_DAYS && g.topic !== 'model') continue;
205
+ if (count < 6 && g.topic !== 'model') continue;
206
+ const id = `u_theme_${g.keyword ?? g.id}`;
207
+ const from = ym(g.firstAt);
208
+ const to = ym(g.lastAt);
209
+ umbrellas.set(id, {
210
+ id,
211
+ kind: 'umbrella',
212
+ topic: 'theme',
213
+ keyword: g.keyword ?? '',
214
+ text: from && to && from !== to
215
+ ? `「${g.keyword}」:${from} 到 ${to} 之间的事,前后 ${count} 次`
216
+ : `「${g.keyword}」:我人生里有过这么一段`,
217
+ at: umbrellas.get(id)?.at ?? now,
218
+ });
219
+ }
220
+ }
221
+
222
+ // 数量封顶:伞是"介绍自己",不该有几十条
223
+ memory.umbrellas = [...umbrellas.values()].slice(-UMBRELLA_MAX);
224
+ return memory.umbrellas.length;
225
+ }
226
+
227
+ /** 21 天内同一个话题出现这么多次 → 判定为重要 */
228
+ export const IMPORTANT_REPEAT = 3;
229
+ export const IMPORTANT_WINDOW_DAYS = 21;
230
+ /** 相似度下限(换说法也算同一件事,所以不能太高) */
231
+ export const IMPORTANT_SIM = 0.3;
232
+
233
+ function bigrams(s) {
234
+ const clean = String(s ?? '').replace(/[\s,。;、!?,.!?;:"'()()【】\[\]「」]/g, '');
235
+ const set = new Set();
236
+ for (let i = 0; i < clean.length - 1; i += 1) set.add(clean.slice(i, i + 2));
237
+ return set;
238
+ }
239
+
240
+ /** 两句话像不像(0~1) */
241
+ export function textSimilarity(a, b) {
242
+ const A = bigrams(a);
243
+ const B = bigrams(b);
244
+ if (!A.size || !B.size) return 0;
245
+ let n = 0;
246
+ for (const g of A) if (B.has(g)) n += 1;
247
+ return n / Math.min(A.size, B.size);
248
+ }
249
+
250
+ /** 虚词二元组:它们重合说明不了"同一件事" */
251
+ const STOP_GRAMS = new Set([
252
+ '什么', '这个', '那个', '一下', '可以', '就是', '然后', '现在', '今天', '真的',
253
+ '不是', '没有', '一个', '我们', '你们', '他们', '怎么', '为什么', '知道', '觉得',
254
+ '时候', '已经', '还是', '但是', '因为', '所以', '如果', '这样', '那样', '可以',
255
+ ]);
256
+
257
+ function topicGrams(s) {
258
+ const out = [];
259
+ for (const g of bigrams(s)) if (!STOP_GRAMS.has(g)) out.push(g);
260
+ return out;
261
+ }
262
+
263
+ /**
264
+ * 是不是同一件事。
265
+ *
266
+ * 不要求一字不差——「辞辞,该上学了」和「辞辞 快去上学」算同一件事,
267
+ * 因为它们共享「辞辞」「上学」两个实词二元组。
268
+ */
269
+ export function sameTopic(a, b, { minShared = 2, minSim = 0.3 } = {}) {
270
+ if (textSimilarity(a, b) < minSim) return false;
271
+ const A = topicGrams(a);
272
+ const B = new Set(topicGrams(b));
273
+ let shared = 0;
274
+ const used = new Set();
275
+ for (const g of A) {
276
+ if (B.has(g) && !used.has(g)) { shared += 1; used.add(g); }
277
+ }
278
+ return shared >= minShared;
279
+ }
280
+
281
+ /**
282
+ * 噪声过滤:刷屏、纯表情、太短的都不算"反复提起"。
283
+ *
284
+ * 喊名字、让你去上学、反复交代的事 —— 这些是有内容的重复;
285
+ * "哈哈哈哈"×20 条不是。
286
+ */
287
+ export function isRepeatNoise(text) {
288
+ const t = String(text ?? '').trim();
289
+ if (t.length < 4) return true; // 太短
290
+ const content = t.replace(/[\s\p{P}\p{S}\p{Emoji_Presentation}]/gu, '');
291
+ if (content.length < 3) return true; // 纯符号/表情
292
+ if (/^(哈|嘿|嗯|哦|啊|草|好|在){2,}$/u.test(content)) return true; // 单字刷屏
293
+ return false;
294
+ }
295
+
296
+ /**
297
+ * 这件事最近是不是被反复提过。
298
+ *
299
+ * 只统计"有内容、不是刷屏"的重复;同一个人 60 秒内的连发只算一次。
300
+ *
301
+ * @returns {{important:boolean, count:number, who:string, sample:string}}
302
+ */
303
+ export function detectRepeat(memory, { who = '', what = '' } = {}, now = Date.now(), {
304
+ repeat = IMPORTANT_REPEAT, windowDays = IMPORTANT_WINDOW_DAYS, sim = IMPORTANT_SIM,
305
+ } = {}) {
306
+ const text = String(what ?? '').trim();
307
+ if (!text || isRepeatNoise(text)) return { important: false, count: 0, who, sample: '' };
308
+
309
+ const since = now - windowDays * DAY_MS;
310
+ const hits = [];
311
+ for (const e of memory.episodes ?? []) {
312
+ if ((e.at ?? 0) < since) continue;
313
+ if (who && e.who && e.who !== who) continue; // 不同人说的同一句话,不算同一件事
314
+ if (isRepeatNoise(e.what)) continue;
315
+ if (sameTopic(text, e.what, { minSim: sim })) hits.push(e);
316
+ }
317
+
318
+ // 防刷屏:同一人 60 秒内**一字不差**的连发只算一次。
319
+ // 但换个说法地反复交代(「该上学了」「快去上学」「要迟到了」)要算——
320
+ // 那恰恰是"重要"的信号,不是噪声。
321
+ const distinct = [];
322
+ for (const h of hits.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))) {
323
+ const dup = distinct.some((d) => d.who === h.who
324
+ && Math.abs((d.at ?? 0) - (h.at ?? 0)) < 60000
325
+ && textSimilarity(d.what, h.what) > 0.9);
326
+ if (!dup) distinct.push(h);
327
+ }
328
+
329
+ const count = distinct.length + 1; // + 这次自己
330
+ return {
331
+ important: count >= repeat,
332
+ count,
333
+ who,
334
+ sample: distinct[0]?.what ?? text,
335
+ };
336
+ }
337
+
338
+ /** 把一条经历标成重要(永不压扁、永不遗忘) */
339
+ export function markImportant(memory, id, now = Date.now()) {
340
+ let n = 0;
341
+ memory.episodes = (memory.episodes ?? []).map((e) => {
342
+ if (e.id !== id) return e;
343
+ n += 1;
344
+ return { ...e, important: true, longTerm: true, compressed: false, expiresAt: now + LONG_DAYS * DAY_MS };
345
+ });
346
+ return n;
347
+ }
348
+
349
+ /**
350
+ * 追溯标记:这件事一旦被判定为重要,**之前提过的同话题也一并转重要**。
351
+ *
352
+ * 不然会出现"第 3 次才记住,前两次已经被压成卡片"的割裂。
353
+ */
354
+ export function markImportantByTopic(memory, { who = '', what = '' } = {}, now = Date.now(), { sim = IMPORTANT_SIM } = {}) {
355
+ let n = 0;
356
+ const text = String(what ?? '').trim();
357
+ if (!text) return 0;
358
+ memory.episodes = (memory.episodes ?? []).map((e) => {
359
+ if (e.important) return e;
360
+ if (who && e.who && e.who !== who) return e;
361
+ if (!sameTopic(text, e.what, { minSim: sim })) return e;
362
+ n += 1;
363
+ return { ...e, important: true, longTerm: true, compressed: false, expiresAt: now + LONG_DAYS * DAY_MS };
364
+ });
365
+ return n;
366
+ }
367
+
13
368
  export function emptyMemory() {
14
369
  return {
15
370
  facts: {}, // key → { text, kind:'fact', weight, lastRecall, consecutiveDays, longTerm }
@@ -19,6 +374,10 @@ export function emptyMemory() {
19
374
  episodes: [], // { id, at, who, what, feel, outcome, context, strategy, kind:'episode' }
20
375
  imagination: [], // 幻想:永不进 episodes(I6)
21
376
  cards: [], // 记忆卡片:上下文过长时的中段锚点
377
+ gists: [], // 纲:从细节/卡片提炼出的一层,永不老化
378
+ umbrellas: [], // 伞:纲之上那一层,不可再分("我上过学""他是我熟人")
379
+ concepts: {}, // 概念:什么是什么 + 为什么要这么做(有人教才会)
380
+ bonds: {}, // 恩情:谁对我好(主人不走这套,他的位置是焊死的)
22
381
  formerSelves: [], // 蜕下来的皮
23
382
  forgotten: [], // 真的忘了
24
383
  pending: [], // 想说没说的
@@ -32,6 +391,8 @@ export function addEpisode(memory, episode, now = Date.now()) {
32
391
  kind: 'episode',
33
392
  at: now,
34
393
  lastRecall: now,
394
+ // 完整期到什么时候结束 —— 到期才压扁,不是一存进来就开始老
395
+ expiresAt: now + FULL_DAYS * DAY_MS,
35
396
  consecutiveDays: 1,
36
397
  longTerm: false,
37
398
  ...episode,
@@ -113,7 +474,13 @@ export function addCard(memory, card) {
113
474
 
114
475
  /**
115
476
  * 被提起一次:续命。
116
- * 同一天内多次提起不重复计数(按自然日算"连续天数")。
477
+ *
478
+ * 「提起」包括:有人又聊到这件事、她自己想起来(检索命中)、手动 touch。
479
+ *
480
+ * 续命规则按需求定:
481
+ * · 完整期 → 计时归零,继续当完整记忆
482
+ * · 卡片期 → **+30 天**(不是重置,是加时;被提得越多活得越久)
483
+ * · 长期期 → 同样 +30 天,但保底还有 2 年
117
484
  */
118
485
  export function recall(item, now = Date.now()) {
119
486
  if (!item) return item;
@@ -122,32 +489,154 @@ export function recall(item, now = Date.now()) {
122
489
  const consecutiveDays = today === lastDay
123
490
  ? item.consecutiveDays ?? 1
124
491
  : (item.consecutiveDays ?? 0) + 1;
492
+
493
+ if (item.longTerm) {
494
+ return { ...item, lastRecall: now, consecutiveDays, expiresAt: now + LONG_DAYS * DAY_MS };
495
+ }
496
+
497
+ if (item.compressed) {
498
+ // 卡片被提:从"现在的到期时间"往后加 30 天
499
+ const base = Math.max(Number(item.expiresAt) || now, now);
500
+ return {
501
+ ...item,
502
+ lastRecall: now,
503
+ consecutiveDays,
504
+ expiresAt: base + EXTEND_DAYS * DAY_MS,
505
+ recallCount: (item.recallCount ?? 0) + 1,
506
+ // 连续提够 15 天 → 升级长期
507
+ ...(consecutiveDays >= PROMOTE_DAYS ? { longTerm: true, compressed: false, expiresAt: now + LONG_DAYS * DAY_MS } : {}),
508
+ };
509
+ }
510
+
511
+ // 完整期:归零 + 够 15 天升级长期
125
512
  const longTerm = item.longTerm || consecutiveDays >= PROMOTE_DAYS;
126
- return { ...item, lastRecall: now, consecutiveDays, longTerm };
513
+ return {
514
+ ...item,
515
+ lastRecall: now,
516
+ consecutiveDays,
517
+ longTerm,
518
+ compressed: false,
519
+ expiresAt: longTerm ? now + LONG_DAYS * DAY_MS : now + FULL_DAYS * DAY_MS,
520
+ };
521
+ }
522
+
523
+ /** 压扁一条/一组经历:留下"大概",丢掉细节 */
524
+ function compressGroup(list, now) {
525
+ const first = list[0];
526
+ const head = String(first.what ?? '').slice(0, 18);
527
+ const who = first.who ?? '';
528
+ const summary = list.length === 1
529
+ ? `(记不清了)${who ? `${who}:` : ''}${head}`
530
+ : `(记不清了)${who ? `${who}:` : ''}${head}…前后还有 ${list.length - 1} 件`;
531
+
532
+ return {
533
+ id: `cmp_${first.id ?? now}`,
534
+ kind: 'episode',
535
+ at: first.at ?? now,
536
+ lastRecall: first.lastRecall ?? first.at ?? now,
537
+ compressed: true,
538
+ cardedAt: now,
539
+ expiresAt: now + CARD_DAYS * DAY_MS, // 卡片从压扁这一刻起算 2 年
540
+ consecutiveDays: first.consecutiveDays ?? 1,
541
+ longTerm: false,
542
+ who,
543
+ what: summary.slice(0, 60),
544
+ feel: '',
545
+ mood: '',
546
+ emotion: 0,
547
+ source: first.source ?? 'live',
548
+ from: list.map((x) => x.id).filter(Boolean),
549
+ };
550
+ }
551
+
552
+ function isPermanent(item) {
553
+ // 「重要记忆」不老化:反复被交代的事、喊她名字、让她去上学——这些不许变成卡片
554
+ return Boolean(item?.important);
127
555
  }
128
556
 
129
557
  /**
130
- * 每日结算:到期且没升级的,进 forgotten。
131
- * 不是删除,是"认知上不存在了"。
558
+ * 每日结算:三段生命周期。
559
+ *
560
+ * [完整] --21 天--> [卡片] --2 年--> [遗忘]
561
+ * [长期] --2 年--> [降回卡片] --2 年--> [遗忘]
562
+ *
563
+ * @param {object} [opts]
564
+ * @param {number} [opts.compressDays] 完整期多长(默认 21)
565
+ * @param {number} [opts.forgetDays] 卡片/长期期多长(默认 730 = 2 年)
566
+ * @param {(item, reason)=>void} [opts.onArchive]
132
567
  */
133
- export function settle(memory, now = Date.now()) {
134
- const expired = (item) => {
135
- if (!item || item.longTerm) return false;
136
- const ttl = TTL_DAYS[item.kind] ?? TTL_DAYS.episode;
137
- if (!Number.isFinite(ttl)) return false;
138
- return now - (item.lastRecall ?? item.at ?? now) > ttl * DAY_MS;
568
+ export function settle(memory, now = Date.now(), opts = {}) {
569
+ const fullDays = Number.isFinite(opts.compressDays) ? opts.compressDays : FULL_DAYS;
570
+ const cardDays = Number.isFinite(opts.forgetDays) ? opts.forgetDays : CARD_DAYS;
571
+ const onArchive = typeof opts.onArchive === 'function' ? opts.onArchive : null;
572
+ const archive = (item, reason) => { if (onArchive) onArchive(item, reason); };
573
+
574
+ const fullExpiry = (item) => Number(item.expiresAt)
575
+ || ((item.lastRecall ?? item.at ?? now) + fullDays * DAY_MS);
576
+ const cardExpiry = (item) => Number(item.expiresAt)
577
+ || ((item.lastRecall ?? item.at ?? now) + cardDays * DAY_MS);
578
+
579
+ // ── 第一段:完整期到期 → 压扁(同一人同一天合成一条"大概")──
580
+ const keep = [];
581
+ const groups = new Map();
582
+ for (const e of memory.episodes ?? []) {
583
+ if (isPermanent(e) || e.longTerm || e.compressed) { keep.push(e); continue; }
584
+ if (now < fullExpiry(e)) { keep.push(e); continue; }
585
+ const day = new Date(e.at ?? now).toISOString().slice(0, 10);
586
+ const key = `${e.who ?? ''}|${day}`;
587
+ if (!groups.has(key)) groups.set(key, []);
588
+ groups.get(key).push(e);
589
+ }
590
+ for (const [key, list] of groups) {
591
+ const g = compressGroup(list, now);
592
+ g.expiresAt = now + cardDays * DAY_MS;
593
+ keep.push(g);
594
+ void key;
595
+ for (const it of list) archive(it, 'compressed');
596
+ }
597
+ memory.episodes = keep;
598
+
599
+ // ── 第二段:长期到期 → 降回卡片,重新走一圈(不是遗忘)──
600
+ memory.episodes = (memory.episodes ?? []).map((e) => {
601
+ if (!e.longTerm || isPermanent(e)) return e;
602
+ if (now < cardExpiry(e)) return e;
603
+ return {
604
+ ...e,
605
+ longTerm: false,
606
+ compressed: true,
607
+ cardedAt: now,
608
+ expiresAt: now + cardDays * DAY_MS,
609
+ demotedAt: now,
610
+ };
611
+ });
612
+
613
+ // ── 第三段:卡片到期 → 遗忘 ──
614
+ const shouldForget = (item) => {
615
+ if (!item) return false;
616
+ if (isPermanent(item)) return false;
617
+ if (item.longTerm) return false;
618
+ return now >= cardExpiry(item);
139
619
  };
140
620
 
141
621
  const keepE = [];
142
- for (const e of memory.episodes) (expired(e) ? memory.forgotten : keepE).push(e);
622
+ for (const e of memory.episodes) {
623
+ if (shouldForget(e)) { memory.forgotten.push(e); archive(e, 'forgotten'); }
624
+ else keepE.push(e);
625
+ }
143
626
  memory.episodes = keepE;
144
627
 
145
628
  const keepI = [];
146
- for (const i of memory.imagination) (expired(i) ? memory.forgotten : keepI).push(i);
629
+ for (const i of memory.imagination ?? []) {
630
+ if (shouldForget(i)) { memory.forgotten.push(i); archive(i, 'forgotten'); }
631
+ else keepI.push(i);
632
+ }
147
633
  memory.imagination = keepI;
148
634
 
149
635
  const keepC = [];
150
- for (const c of memory.cards ?? []) (expired(c) ? memory.forgotten : keepC).push(c);
636
+ for (const c of memory.cards ?? []) {
637
+ if (shouldForget(c)) { memory.forgotten.push(c); archive(c, 'forgotten'); }
638
+ else keepC.push(c);
639
+ }
151
640
  memory.cards = keepC;
152
641
 
153
642
  for (const bucket of ['facts', 'impressions']) {
@@ -155,7 +644,7 @@ export function settle(memory, now = Date.now()) {
155
644
  const kept = {};
156
645
  for (const [k, v] of Object.entries(src)) {
157
646
  const item = { kind: bucket === 'facts' ? 'fact' : 'impression', ...v };
158
- if (expired(item)) memory.forgotten.push({ key: k, ...item });
647
+ if (shouldForget(item)) { memory.forgotten.push({ key: k, ...item }); archive({ key: k, ...item }, 'forgotten'); }
159
648
  else kept[k] = v;
160
649
  }
161
650
  memory[bucket] = kept;
@@ -164,6 +653,19 @@ export function settle(memory, now = Date.now()) {
164
653
  return memory;
165
654
  }
166
655
 
656
+ /** 检索命中的经历算「被想起来」——记忆靠被想起活着 */
657
+ export function touchByIds(memory, ids = [], now = Date.now()) {
658
+ const set = new Set(ids.filter(Boolean));
659
+ if (!set.size) return 0;
660
+ let n = 0;
661
+ memory.episodes = (memory.episodes ?? []).map((e) => {
662
+ if (!set.has(e.id)) return e;
663
+ n += 1;
664
+ return recall(e, now);
665
+ });
666
+ return n;
667
+ }
668
+
167
669
  /**
168
670
  * 四路线索检索 —— 只取相关的,定长。
169
671
  * 人脑不是扫描记忆的,记忆是被线索勾出来的。
@@ -180,7 +682,7 @@ export function retrieve(cue, memory, { budget = RETRIEVE_BUDGET_CHARS, now = Da
180
682
  if (out.some((x) => x.text === t)) return; // 同一条别念两遍
181
683
  if (used + t.length > budget) return;
182
684
  if (id) seen.add(id);
183
- out.push({ lane, text: t });
685
+ out.push({ lane, text: t, id: id ?? null });
184
686
  used += t.length;
185
687
  };
186
688
 
@@ -203,12 +705,31 @@ export function retrieve(cue, memory, { budget = RETRIEVE_BUDGET_CHARS, now = Da
203
705
  for (const c of latest) push(`(之前)${c.text}`, 'card', c.id);
204
706
  }
205
707
 
708
+ // ⓪ 伞:结构层,最先给位置("我上过学""他是我熟人"是介绍自己的话)
709
+ if (Array.isArray(memory.umbrellas) && memory.umbrellas.length) {
710
+ const mine = memory.umbrellas.filter((u) => u.topic === 'person' && u.who && u.who === who);
711
+ const rest = memory.umbrellas.filter((u) => !mine.includes(u));
712
+ for (const u of [...mine, ...rest].slice(0, 3)) push(u.text, 'umbrella', u.id);
713
+ }
714
+
715
+ // ⓪ 纲:比细节活得久的那一层,先给它位置
716
+ if (Array.isArray(memory.gists) && memory.gists.length) {
717
+ // 跟这个人有关的纲优先,其余按次数
718
+ const mine = memory.gists.filter((g) => g.topic === 'person' && g.who && g.who === who);
719
+ const rest = memory.gists.filter((g) => !mine.includes(g)).sort((a, b) => (b.count ?? 0) - (a.count ?? 0));
720
+ for (const g of [...mine, ...rest].slice(0, 4)) push(g.text, 'gist', g.id);
721
+ }
722
+
206
723
  // ① 人:这人是谁 + 跟他的最近三次
207
724
  if (who) {
208
725
  const im = memory.impressions?.[who];
209
726
  if (im) {
210
727
  const traits = (im.traits ?? []).filter(Boolean);
211
- push(`${who}:${traits.length ? traits.join('、') : '还不熟'}(${im.count ?? 0} 次)`, 'person');
728
+ const faded = nameFaded(im, now);
729
+ // 太久没提:名字想不起来,但"认识这个人"这件事不能没
730
+ push(faded
731
+ ? `有个认识的(大概是${who})——名字有点想不起来了`
732
+ : `${who}:${traits.length ? traits.join('、') : '还不熟'}(${im.count ?? 0} 次)`, 'person');
212
733
  }
213
734
  const mine = memory.episodes.filter((e) => e.who === who).slice(-3);
214
735
  for (const e of mine) {