cortico-world-memory-core 0.26.1 → 0.27.0

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/src/world.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  import { appendFileSync, existsSync, readFileSync } from 'node:fs';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { join } from 'node:path';
13
- import { randomUUID } from 'node:crypto';
13
+ import { createHash, randomUUID } from 'node:crypto';
14
14
  import type { ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
15
15
  import type { WorldContext } from 'cortico/world.ts';
16
16
  import { MEMORY_CORE_CONFIG_GROUP, MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
@@ -20,9 +20,12 @@ import {
20
20
  CardStore,
21
21
  RawLog,
22
22
  ensureDir,
23
+ lastMemoryTouch,
23
24
  maskSender,
24
25
  readJson,
26
+ writeAtomic,
25
27
  writeJson,
28
+ type Card,
26
29
  type CardKind,
27
30
  type CoreState,
28
31
  type PlanItem,
@@ -30,9 +33,10 @@ import {
30
33
  } from './store.ts';
31
34
  import { importLegacy } from './importer.ts';
32
35
  import { isContentToken, rankCardsScored, rankRaw, tokenize } from './recall.ts';
36
+ import { MemoryReview, REVIEW_LIMIT, reviewStamp } from './review.ts';
33
37
  import { advance, createInitialState, moodLabel } from './state.ts';
34
38
  import { formatLocal, hmToMinutes, humanSpan, inWindow, localParts } from './time.ts';
35
- import { MemorySite, type HealthReport, type ImportReport, type Snapshot } from './site.ts';
39
+ import { MemorySite, type HealthReport, type ImportReport, type KeepSuggestion, type SiteHooks, type Snapshot } from './site.ts';
36
40
  import { expandDirs, loadDocs, searchDocs } from './workspace.ts';
37
41
 
38
42
  const ENV_PROMPT_FILE = fileURLToPath(new URL('../ENV_PROMPT.md', import.meta.url));
@@ -53,6 +57,14 @@ const CAPTURE_WATERMARK_VERSION = 2;
53
57
  * 取大一点:宿主每次 range 都要遍历一遍分片,窗口太碎会让回放变成几百次全表扫描。 */
54
58
  const CAPTURE_BATCH = 2_000;
55
59
 
60
+ function isOutboundOrReceipt(event: { senderKey?: string; type?: string; tags?: readonly string[]; text?: string; meta?: Record<string, unknown> }): boolean {
61
+ const kind = event.type ?? '';
62
+ const key = event.senderKey ?? '';
63
+ if (key === 'desktop-pet.self' || kind === 'desktop-pet.self' || event.meta?.dismissed === true) return true;
64
+ if (key.startsWith('desktop-pet.') && !/^desktop-pet\.(chat|text|message|answer|voice)$/.test(key)) return true;
65
+ return /\.(sent|attempt)$/.test(kind) || Boolean(event.tags?.includes('speak')) || /^准备发送\s*(?:→|->)/.test(String(event.text ?? '').trim());
66
+ }
67
+
56
68
  function clip(text: string, limit: number): string {
57
69
  const s = String(text ?? '').replace(/\s+/g, ' ').trim();
58
70
  return s.length > limit ? `${s.slice(0, limit)}…` : s;
@@ -138,6 +150,7 @@ export class MemoryCoreWorld implements World {
138
150
  private host: WorldHost | null = null;
139
151
  private readonly dataDir: string;
140
152
  private readonly store: CardStore;
153
+ private readonly review: MemoryReview;
141
154
  private readonly raw: RawLog;
142
155
  private state: CoreState;
143
156
  private plans: PlanItem[] = [];
@@ -161,6 +174,7 @@ export class MemoryCoreWorld implements World {
161
174
  this.dataDir = join(base, 'memory-core');
162
175
  ensureDir(this.dataDir);
163
176
  this.store = new CardStore(this.dataDir);
177
+ this.review = new MemoryReview(this.store, () => this.chillDays(), () => str(this.cfg().reviewModel, 120));
164
178
  this.raw = new RawLog(
165
179
  this.dataDir,
166
180
  Math.max(1, Number(ctx.cfg?.rawRetentionDays ?? 7)),
@@ -295,10 +309,7 @@ export class MemoryCoreWorld implements World {
295
309
  ],
296
310
  config: [MEMORY_CORE_CONFIG_GROUP],
297
311
  links: this.siteOrigin
298
- ? [
299
- { label: '记忆地图 · 图谱与时间线', href: this.siteOrigin, inheritTheme: true },
300
- { label: '记忆核心 · 新版星系', href: `${this.siteOrigin}/next`, inheritTheme: true },
301
- ]
312
+ ? [{ label: '打开记忆核心', href: `${this.siteOrigin}/next?view=galaxy&atlas=story`, inheritTheme: true }]
302
313
  : [],
303
314
  storage: [
304
315
  {
@@ -464,7 +475,7 @@ export class MemoryCoreWorld implements World {
464
475
  };
465
476
  }
466
477
 
467
- private siteHooks() {
478
+ private siteHooks(): SiteHooks {
468
479
  return {
469
480
  snapshot: () => this.snapshot(),
470
481
  docs: () => this.docs(),
@@ -497,6 +508,7 @@ export class MemoryCoreWorld implements World {
497
508
  next.kind = kind;
498
509
  }
499
510
  if (patch.weight !== undefined) next.weight = num(patch.weight, 0.5, 0, 1);
511
+ if (typeof patch.keepLongTerm === 'boolean') next.keepLongTerm = patch.keepLongTerm;
500
512
  if (Array.isArray(patch.tags)) {
501
513
  next.tags = (patch.tags as unknown[]).map((t) => String(t).slice(0, 20)).filter(Boolean).slice(0, 8);
502
514
  }
@@ -538,12 +550,47 @@ export class MemoryCoreWorld implements World {
538
550
  return rankRaw(this.raw.readArchive(span, 20000), query, cap);
539
551
  },
540
552
  deleteTurn: (cursor: number) => this.raw.remove(cursor),
553
+ sourceContext: (id) => {
554
+ const source = this.store.find(id)?.src;
555
+ return source ? this.raw.sourceContext(source) : [];
556
+ },
557
+ fishPage: (before) => {
558
+ const hidden = new Set(readJson<number[]>(join(this.dataDir, 'hidden-fish.json'), []));
559
+ const events = this.host?.store?.range({ source: 'desktop-pet', senderKey: 'desktop-pet.self', limit: 200, ...(before === undefined ? {} : { toCursor: before - 1 }) }) ?? [];
560
+ const rows = events.flatMap(event => {
561
+ if (event.type !== 'desktop-pet.self' || event.meta?.kind !== 'say' || !Array.isArray(event.meta.beats) || hidden.has(event.cursor)) return [];
562
+ const text = event.meta.beats.map(beat => typeof beat?.text === 'string' ? beat.text : '').filter(Boolean).join('\n').trim();
563
+ return text ? [{ cursor: event.cursor, ts: event.ts, text }] : [];
564
+ });
565
+ return { rows, before: events.length === 200 ? events[0].cursor : null };
566
+ },
567
+ removeTurns: (owner, fish) => {
568
+ if (fish.length) {
569
+ const file = join(this.dataDir, 'hidden-fish.json');
570
+ if (!writeAtomic(file, JSON.stringify([...new Set([...readJson<number[]>(file, []), ...fish])]))) throw new Error('未能保存隐藏记录');
571
+ }
572
+ return { removed: this.raw.removeMany(owner), hidden: fish.length };
573
+ },
541
574
  mergeCards: (keepId: string, dropIds: string[]) => this.store.merge(keepId, dropIds),
542
575
  purgeCards: (ids: string[]) => this.store.purge(ids),
543
- chillCards: (ids: string[]) =>
544
- this.store.chill(
545
- ids.length ? ids : this.store.chillEligible(this.chillDays(), Date.now()).map((c) => c.id),
546
- ),
576
+ chillPreview: () => {
577
+ const now = Date.now();
578
+ return this.store.chillEligible(this.chillDays(), now).map((card) => {
579
+ const last = lastMemoryTouch(card);
580
+ return {
581
+ id: card.id, text: card.text, kind: card.kind, weight: card.weight, stamp: reviewStamp(card),
582
+ lastActivityAt: new Date(last).toISOString(), idleDays: Math.floor((now - last) / 86_400_000),
583
+ };
584
+ });
585
+ },
586
+ assessChill: (refs) => this.review.assess(refs),
587
+ applyChillReview: (id, selected) => this.review.apply(id, selected),
588
+ keepSuggestions: () => this.keepSuggestions(),
589
+ chillCards: (ids: string[]) => {
590
+ if (!ids.length) return 0;
591
+ const selected = new Set(ids);
592
+ return this.store.chill(this.store.chillEligible(this.chillDays()).filter((card) => selected.has(card.id)).map((card) => card.id));
593
+ },
547
594
  warmCards: (ids: string[]) => this.store.warm(ids.length ? ids : this.store.cold().map((c) => c.id)),
548
595
  patchState: (input: Record<string, unknown>) => {
549
596
  if (input.energy !== undefined) this.state.energy = num(input.energy, this.state.energy, 0, 100);
@@ -622,7 +669,7 @@ export class MemoryCoreWorld implements World {
622
669
  const day = (ts: string) => formatLocal(ts, this.tz()).slice(0, 10);
623
670
  // 被用过 = 工具召回 + 每轮预激活。只算前者会把「系统主动想起过」的卡误判成死卡
624
671
  const touched = (c: { uses?: number; primedCount?: number }) => (c.uses || 0) + (c.primedCount || 0);
625
- const dead = live.filter((c) => touched(c) === 0 && now - Date.parse(c.createdAt) > 7 * 86_400_000);
672
+ const dead = live.filter((c) => !c.keepLongTerm && touched(c) === 0 && now - Date.parse(c.createdAt) > 7 * 86_400_000);
626
673
  const count = new Map<string, number>();
627
674
  for (const c of live) {
628
675
  const d = day(c.createdAt);
@@ -676,6 +723,7 @@ export class MemoryCoreWorld implements World {
676
723
  cold: this.store.cold().length,
677
724
  eligible: this.store.chillEligible(this.chillDays(), now).length,
678
725
  afterDays: this.chillDays(),
726
+ reviewLimit: str(this.cfg().reviewModel, 120) ? REVIEW_LIMIT : 0,
679
727
  },
680
728
  deadIds: dead.map((c) => c.id),
681
729
  coldIds: this.store.cold().map((c) => c.id),
@@ -823,6 +871,7 @@ export class MemoryCoreWorld implements World {
823
871
  }
824
872
  const doneProvided = typeof args.done === 'boolean';
825
873
  const done = doneProvided ? Boolean(args.done) : card.done;
874
+ const keepLongTerm = typeof args.keepLongTerm === 'boolean' ? args.keepLongTerm : undefined;
826
875
 
827
876
  // 正文变了:写新卡接替,旧卡留档(不抹掉「当时是怎么记的」)
828
877
  if (text && text !== card.text) {
@@ -834,10 +883,12 @@ export class MemoryCoreWorld implements World {
834
883
  dueAt,
835
884
  source: 'tool',
836
885
  origin: 'tool',
886
+ keepLongTerm,
837
887
  ...(card.src ? { src: card.src } : {}),
838
888
  });
839
889
  if (card.kind === 'promise') this.store.close(card.id);
840
- this.store.supersede(card.id, res.card);
890
+ if (res.card.id === card.id && keepLongTerm === false) this.store.update(card.id, { keepLongTerm: false });
891
+ this.store.supersede(card.id, res.card, keepLongTerm !== false);
841
892
  try {
842
893
  this.host?.log?.info?.('[memory-core] 改口', { from: card.id.slice(0, 8), to: res.card.id.slice(0, 8) });
843
894
  } catch {
@@ -852,6 +903,7 @@ export class MemoryCoreWorld implements World {
852
903
  if (has('tags')) patch.tags = [...tags];
853
904
  if (dueProvided) patch.dueAt = dueAt;
854
905
  if (doneProvided) patch.done = done;
906
+ if (keepLongTerm !== undefined) patch.keepLongTerm = keepLongTerm;
855
907
  // 截止时间或完成状态变了:提醒重新计数,别拿旧的「已提醒 6 次」把它压死
856
908
  if (dueProvided || doneProvided) {
857
909
  patch.remindedAt = undefined;
@@ -900,6 +952,7 @@ export class MemoryCoreWorld implements World {
900
952
  dueAt,
901
953
  source: 'tool',
902
954
  origin: 'tool',
955
+ keepLongTerm: args.keepLongTerm === true,
903
956
  ...(src ? { src } : {}),
904
957
  });
905
958
  let extra = '';
@@ -973,7 +1026,7 @@ export class MemoryCoreWorld implements World {
973
1026
  return best;
974
1027
  }
975
1028
 
976
- private findCard(prefix: string): { id: string; kind: string } | undefined {
1029
+ private findCard(prefix: string): Card | undefined {
977
1030
  if (!prefix) return undefined;
978
1031
  return this.store.find(prefix) ?? this.store.all().find((c) => c.id.startsWith(prefix)) ?? undefined;
979
1032
  }
@@ -1003,13 +1056,16 @@ export class MemoryCoreWorld implements World {
1003
1056
  if (idArg) return this.handleSource(idArg);
1004
1057
  const query = str(args.query, 200);
1005
1058
  const mode = String(args.mode ?? (query ? 'search' : 'recent'));
1059
+ const searching = mode === 'search';
1060
+ if (searching && !tokenize(query).length) return '搜索需要有效的关键词。';
1006
1061
  const limit = num(args.limit, Number(this.cfg().recallLimit) || 5, 1, 12);
1007
1062
  const maxChars = num(this.cfg().recallMaxChars, 600, 120, 2000);
1008
1063
  const tz = this.tz();
1009
1064
  const lines: string[] = [];
1010
1065
  const push = (line: string) => {
1011
- if (lines.join('\n').length > maxChars) return;
1066
+ if (lines.join('\n').length > maxChars) return false;
1012
1067
  lines.push(line);
1068
+ return true;
1013
1069
  };
1014
1070
 
1015
1071
  if (mode === 'open') {
@@ -1042,8 +1098,8 @@ export class MemoryCoreWorld implements World {
1042
1098
  return out.join('\n').slice(0, maxChars + 40);
1043
1099
  }
1044
1100
 
1045
- const ranked = rankCardsScored(mode === 'search' ? this.store.active() : this.store.recallable(), {
1046
- query: mode === 'search' ? query : undefined,
1101
+ const ranked = rankCardsScored(searching ? this.store.active() : this.store.recallable(), {
1102
+ query: searching ? query : undefined,
1047
1103
  kind: str(args.kind, 20) || undefined,
1048
1104
  days: num(args.days, 0, 0, 3650) || undefined,
1049
1105
  limit,
@@ -1054,7 +1110,7 @@ export class MemoryCoreWorld implements World {
1054
1110
  const cards = ranked.map((x) => x.card);
1055
1111
  const strongIds = new Set(ranked.filter((x) => x.tier === 'strong').map((x) => x.card.id));
1056
1112
 
1057
- if (mode === 'search' && query) {
1113
+ if (searching) {
1058
1114
  const hits = rankRaw(this.raw.all(), query, Math.max(1, Math.min(3, limit)));
1059
1115
  for (const hit of hits) {
1060
1116
  const from = senderLabel(hit.sender);
@@ -1082,25 +1138,27 @@ export class MemoryCoreWorld implements World {
1082
1138
  const mark = when ? ` ↩${when}` : '';
1083
1139
  const cold = card.coldAt ? '❄' : '';
1084
1140
  // 解释一下为什么它被召回:模型能判断是字面对上,还是同义词补进来的
1085
- const hit = mode === 'search' ? hitMap.get(card.id) ?? [] : [];
1141
+ const hit = searching ? hitMap.get(card.id) ?? [] : [];
1086
1142
  const why = hit.length ? ` 〔${hit.join('+')}〕` : '';
1087
1143
  // 行首这 8 位就是 id:改口/作废时要用它传给 mcore_write 的 closes
1088
- return `· ${card.id.slice(0, 8)} ${cold}${formatLocal(card.createdAt, tz).slice(5)} ${clip(card.text, 110)}${tag}${mark}${why}`;
1144
+ const summary = card.summaryOf?.length ? '〔提炼〕' : '';
1145
+ return `· ${card.id.slice(0, 8)} ${cold}${formatLocal(card.createdAt, tz).slice(5)} ${summary}${clip(card.text, 110)}${tag}${mark}${why}`;
1089
1146
  };
1090
1147
 
1091
1148
  // 漏检记录:本地留一份,用来补同义词表;同一条查询 10 分钟内只记一次
1092
- if (mode === 'search' && query && !ranked.some((x) => x.tier === 'strong')) {
1149
+ if (searching && !strongIds.size) {
1093
1150
  this.logMiss(query, str(args.kind, 20) || undefined);
1094
1151
  }
1095
1152
 
1096
1153
  // 搜出来的分两档:真对得上的,和只是靠权重/新鲜度浮上来的。
1097
1154
  // 不分档的话,模型会把「有点像」当成「就是」,这也是它编故事的起点。
1098
- if (mode === 'search' && query && cards.length) {
1155
+ const usedIds: string[] = [];
1156
+ if (searching && cards.length) {
1099
1157
  const strong = cards.filter((c) => strongIds.has(c.id));
1100
1158
  const weak = cards.filter((c) => !strongIds.has(c.id));
1101
1159
  if (strong.length) {
1102
1160
  push('【对得上】');
1103
- for (const card of strong) push(cardLine(card));
1161
+ for (const card of strong) if (push(cardLine(card))) usedIds.push(card.id);
1104
1162
  if (weak.length) {
1105
1163
  push('【可能沾边,别当准】');
1106
1164
  for (const card of weak) push(cardLine(card));
@@ -1111,9 +1169,9 @@ export class MemoryCoreWorld implements World {
1111
1169
  for (const card of weak.slice(0, 2)) push(cardLine(card));
1112
1170
  }
1113
1171
  } else {
1114
- for (const card of cards) push(cardLine(card));
1172
+ for (const card of cards) if (push(cardLine(card))) usedIds.push(card.id);
1115
1173
  }
1116
- this.store.touch(cards.map((c) => c.id));
1174
+ this.store.touch(usedIds);
1117
1175
  return lines.length ? lines.join('\n') : '没有找到相关的记忆。';
1118
1176
  }
1119
1177
 
@@ -1313,6 +1371,7 @@ export class MemoryCoreWorld implements World {
1313
1371
  );
1314
1372
  this.pruneDeletedThoughts();
1315
1373
  this.absorbThoughts(now);
1374
+ this.absorbKeepSuggestions();
1316
1375
  await this.maybeContext(now);
1317
1376
  await this.maybePreactivate(now);
1318
1377
  await this.maybeRemind(now);
@@ -1343,6 +1402,7 @@ export class MemoryCoreWorld implements World {
1343
1402
  '^(starpost\\.private\\.|qq\\.|desktop-pet\\.message)',
1344
1403
  '^(desktop-pet\\.(chat|message|answer|voice)|private:|qq\\.private\\.|starpost\\.private\\.)',
1345
1404
  ];
1405
+ legacy.push('^(desktop-pet\\.(chat|message|answer|voice)|private:|qq\\.private\\.|qq-official\\.c2c[.:]|starpost\\.private\\.)');
1346
1406
  const pattern = !raw || legacy.includes(raw) ? MEMORY_CORE_DEFAULTS.captureSenders : raw;
1347
1407
  try {
1348
1408
  return new RegExp(pattern);
@@ -1399,6 +1459,7 @@ export class MemoryCoreWorld implements World {
1399
1459
  text: string;
1400
1460
  type?: string;
1401
1461
  tags?: readonly string[];
1462
+ meta?: Record<string, unknown>;
1402
1463
  }[] = [];
1403
1464
  try {
1404
1465
  events = host.store.range({ fromCursor: from + 1, toCursor: to, origin: 'external' });
@@ -1408,14 +1469,7 @@ export class MemoryCoreWorld implements World {
1408
1469
  scanned += events.length;
1409
1470
  for (const e of events) {
1410
1471
  const key = e.senderKey ?? '';
1411
- const kind = String(e.type ?? '');
1412
- const tags = Array.isArray(e.tags) ? e.tags : [];
1413
- // 方向过滤:qq-official 收发共用同一个 senderKey,只能看 type / tags。
1414
- // 自己说出去的回执带 speak 标签或 *.sent / *.attempt,都不能记成「对方说的」。
1415
- if ((kind.startsWith('qq-official.') || key.startsWith('qq-official.')) && tags.includes('speak')) continue;
1416
- if (/\.(sent|attempt)$/.test(kind)) continue;
1417
- // 插件占位兜底:老版本没有 type/tags 时,靠正文认「准备发送 → 私聊 msg_seq=…」
1418
- if (/^准备发送\s*(?:→|->)/.test(String(e.text ?? '').trim())) continue;
1472
+ if (isOutboundOrReceipt(e)) continue;
1419
1473
  // captureAll 打开时不再看白名单:群里的其他人、自己发的都记
1420
1474
  if (!cfg.captureAll && !re.test(key)) {
1421
1475
  // 记几个被挡掉的 key,出问题时一眼能看出是白名单还是正文的问题
@@ -1472,18 +1526,13 @@ export class MemoryCoreWorld implements World {
1472
1526
  if (now - this.lastUserProbe < 30_000) return this.lastUserAt;
1473
1527
  this.lastUserProbe = now;
1474
1528
  try {
1475
- let re: RegExp;
1476
- try {
1477
- re = new RegExp(this.cfg().captureSenders || '^(starpost\\.private\\.|qq\\.)');
1478
- } catch {
1479
- re = /^(starpost\.private\.|qq\.)/;
1480
- }
1529
+ const re = this.senderRe(this.cfg());
1481
1530
  const events = this.host?.store?.range({ origin: 'external', limit: 60 }) ?? [];
1482
- let best = 0;
1483
- let bestText = '';
1484
- let bestCursor = -1;
1531
+ let best = this.lastUserAt ?? 0;
1532
+ let bestText = this.lastTurn?.text ?? '';
1533
+ let bestCursor = this.lastTurn?.cursor ?? -1;
1485
1534
  for (const e of events) {
1486
- if (!re.test(e.senderKey ?? '')) continue;
1535
+ if (isOutboundOrReceipt(e) || !re.test(e.senderKey ?? '')) continue;
1487
1536
  const t = Date.parse(e.ts);
1488
1537
  if (Number.isFinite(t) && t > best) {
1489
1538
  best = t;
@@ -1634,7 +1683,7 @@ export class MemoryCoreWorld implements World {
1634
1683
  return null;
1635
1684
  }
1636
1685
 
1637
- private readThoughts(limit = 40): { id: string; ts: string; text: string; importance: number }[] {
1686
+ private readThoughts(limit = 40): { id: string; ts: string; text: string; importance: number; memoryKeep?: unknown }[] {
1638
1687
  const file = join(this.dataDir, '..', 'self-awareness', 'thoughts.jsonl');
1639
1688
  if (!existsSync(file)) return [];
1640
1689
  let lines: string[] = [];
@@ -1643,10 +1692,10 @@ export class MemoryCoreWorld implements World {
1643
1692
  } catch {
1644
1693
  return [];
1645
1694
  }
1646
- const out: { id: string; ts: string; text: string; importance: number }[] = [];
1695
+ const out: ReturnType<MemoryCoreWorld['readThoughts']> = [];
1647
1696
  for (const line of lines) {
1648
1697
  try {
1649
- const t = JSON.parse(line) as { id?: string; ts?: string; text?: unknown; importance?: number };
1698
+ const t = JSON.parse(line) as { id?: string; ts?: string; text?: unknown; importance?: number; memoryKeep?: unknown };
1650
1699
  // 同上:非字符串一律跳过,别让它变成一张「[object Object]」的卡片
1651
1700
  if (typeof t.text !== 'string' || !t.text.trim()) continue;
1652
1701
  out.push({
@@ -1654,6 +1703,7 @@ export class MemoryCoreWorld implements World {
1654
1703
  ts: String(t.ts ?? ''),
1655
1704
  text: t.text,
1656
1705
  importance: Number(t.importance) || 0,
1706
+ memoryKeep: t.memoryKeep,
1657
1707
  });
1658
1708
  } catch {
1659
1709
  // 坏行跳过
@@ -1662,6 +1712,64 @@ export class MemoryCoreWorld implements World {
1662
1712
  return out.reverse();
1663
1713
  }
1664
1714
 
1715
+ /**
1716
+ * 她独处时判断重要的经历,直接标长期保留,不再等确认。
1717
+ * `handledKeepSuggestions` 只防重复写入和重复日志:你手动取消保留后不会被再次自动加回。
1718
+ */
1719
+ private absorbKeepSuggestions(): void {
1720
+ const handled = new Set(this.state.handledKeepSuggestions ?? []);
1721
+ const fresh = this.scanKeepSuggestions().filter((item) => !item.applied && !handled.has(item.id));
1722
+ if (!fresh.length) return;
1723
+ for (const item of fresh) {
1724
+ this.store.update(item.cardId, { keepLongTerm: true });
1725
+ try {
1726
+ this.host?.log?.info?.('[memory-core] 她自己决定长期保留', { cardId: item.cardId, reason: item.reason });
1727
+ } catch {
1728
+ // ignore
1729
+ }
1730
+ }
1731
+ this.state.handledKeepSuggestions = [...handled, ...fresh.map((item) => item.id)].slice(-160);
1732
+ this.save(true);
1733
+ }
1734
+
1735
+ private scanKeepSuggestions(): KeepSuggestion[] {
1736
+ if (!this.cfg().memoryEnabled) return [];
1737
+ const out: KeepSuggestion[] = [];
1738
+ const seen = new Set<string>();
1739
+ for (const thought of this.readThoughts(80)) {
1740
+ if (!/^[\w-]{1,60}$/.test(thought.id) || seen.has(thought.id)) continue;
1741
+ const keep = thought.memoryKeep as { cardId?: unknown; textHash?: unknown; reason?: unknown } | null | undefined;
1742
+ if (!keep || typeof keep.cardId !== 'string' || typeof keep.reason !== 'string') continue;
1743
+ const reason = keep.reason.trim();
1744
+ if (!reason || reason.length > 160) continue;
1745
+ const card = this.store.find(keep.cardId);
1746
+ if (!card || card.kind !== 'episode' || card.status === 'retired') continue;
1747
+ if (keep.textHash !== createHash('sha256').update(card.text).digest('hex')) continue;
1748
+ out.push({
1749
+ id: thought.id,
1750
+ ts: thought.ts,
1751
+ reason,
1752
+ cardId: card.id,
1753
+ text: card.text,
1754
+ cold: Boolean(card.coldAt),
1755
+ applied: card.keepLongTerm === true,
1756
+ });
1757
+ seen.add(thought.id);
1758
+ }
1759
+ return out;
1760
+ }
1761
+
1762
+ /** 页面只列她现在保留着的,当作她自己的记录。 */
1763
+ private keepSuggestions(): KeepSuggestion[] {
1764
+ const out: KeepSuggestion[] = [];
1765
+ for (const item of this.scanKeepSuggestions()) {
1766
+ if (!item.applied || out.some((seen) => seen.cardId === item.cardId)) continue;
1767
+ out.push(item);
1768
+ if (out.length >= 20) break;
1769
+ }
1770
+ return out;
1771
+ }
1772
+
1665
1773
  /**
1666
1774
  * 把「她自己标成很重要」的想法收成一张 self 卡片。
1667
1775
  * 文本前面加「独处时写下」——不然它会以卡片的身份进上下文,被当成此刻的想法,
@@ -1691,6 +1799,17 @@ export class MemoryCoreWorld implements World {
1691
1799
  return;
1692
1800
  }
1693
1801
  if (!ids.size) return;
1802
+ try {
1803
+ const thoughts = readFileSync(join(this.dataDir, '..', 'self-awareness', 'thoughts.jsonl'), 'utf8');
1804
+ for (const line of thoughts.split('\n')) {
1805
+ if (!line.trim()) continue;
1806
+ const thought = JSON.parse(line) as { id?: unknown } | null;
1807
+ if (typeof thought?.id === 'string') ids.delete(thought.id);
1808
+ if (!ids.size) return;
1809
+ }
1810
+ } catch {
1811
+ return;
1812
+ }
1694
1813
  const victims = this.store
1695
1814
  .all()
1696
1815
  .filter((c) => c.srcThoughtId && ids.has(c.srcThoughtId))