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/store.ts CHANGED
@@ -55,6 +55,12 @@ export interface Card {
55
55
  * 不是删除——默认不进召回和预激活,显式搜索仍然找得到,一键回暖。
56
56
  */
57
57
  coldAt?: string;
58
+ keepLongTerm?: boolean;
59
+ summaryOf?: string[];
60
+ }
61
+
62
+ export function lastMemoryTouch(card: Card): number {
63
+ return Math.max(Date.parse(card.createdAt) || 0, Date.parse(card.lastUsedAt ?? '') || 0, Date.parse(card.lastPrimedAt ?? '') || 0);
58
64
  }
59
65
 
60
66
  export interface RawEntry {
@@ -100,6 +106,7 @@ export interface CoreState {
100
106
  remindCountToday?: number;
101
107
  /** 已经收成卡片的想法 id(只留最近 100 个,够防重复了)。 */
102
108
  absorbedThoughtIds?: string[];
109
+ handledKeepSuggestions?: string[];
103
110
  rawWatermark?: number;
104
111
  /** 水位是按哪一版捕获逻辑推进的。旧版用了错的 range 语义,水位不可信,见 CAPTURE_WATERMARK_VERSION。 */
105
112
  watermarkVersion?: number;
@@ -278,22 +285,16 @@ export class CardStore {
278
285
  const span = Math.max(0, Number(days) || 0);
279
286
  if (!span) return [];
280
287
  const cutoff = now - span * 86_400_000;
281
- const lastTouch = (c: Card) =>
282
- Math.max(
283
- Date.parse(c.createdAt) || 0,
284
- Date.parse(c.lastUsedAt ?? '') || 0,
285
- Date.parse(c.lastPrimedAt ?? '') || 0,
286
- );
287
288
  return this.active()
288
289
  .filter((c) => {
289
- if (c.coldAt) return false;
290
+ if (c.coldAt || c.keepLongTerm === true) return false;
290
291
  // 只沉流水账和临时信息;fact / self / 未完成的承诺是「人」,不能沉
291
292
  if (c.kind !== 'episode' && c.kind !== 'note') return false;
292
293
  if (c.weight > 0.45) return false;
293
294
  if ((c.uses || 0) + (c.primedCount || 0) > 1) return false;
294
- return lastTouch(c) < cutoff;
295
+ return lastMemoryTouch(c) < cutoff;
295
296
  })
296
- .sort((a, b) => lastTouch(a) - lastTouch(b)); // 最久没碰的排前面,配额先吃它们
297
+ .sort((a, b) => lastMemoryTouch(a) - lastMemoryTouch(b)); // 最久没碰的排前面,配额先吃它们
297
298
  }
298
299
 
299
300
  chill(ids: readonly string[]): number {
@@ -301,7 +302,7 @@ export class CardStore {
301
302
  let n = 0;
302
303
  for (const id of ids) {
303
304
  const card = this.find(id);
304
- if (!card || card.status === 'retired' || card.coldAt) continue;
305
+ if (!card || card.status === 'retired' || card.coldAt || card.keepLongTerm === true) continue;
305
306
  card.coldAt = at;
306
307
  n += 1;
307
308
  }
@@ -367,6 +368,8 @@ export class CardStore {
367
368
  origin?: string;
368
369
  createdAt?: string;
369
370
  scope?: string;
371
+ keepLongTerm?: boolean;
372
+ summaryOf?: string[];
370
373
  /** 写这条时,对方最近说的那句原话(截断 80 字,已脱敏)。有它才追得回证据。 */
371
374
  src?: { cursor: number; ts: string; text?: string };
372
375
  }): { card: Card; merged: boolean } {
@@ -379,7 +382,12 @@ export class CardStore {
379
382
  (c) => c.kind === kind && c.status !== 'retired' && normalizeText(c.text) === key,
380
383
  );
381
384
  if (near) {
385
+ if (input.summaryOf) return { card: near, merged: true };
382
386
  near.weight = Math.max(near.weight, clamp01(Number(input.weight ?? near.weight)));
387
+ if (input.keepLongTerm === true) {
388
+ near.keepLongTerm = true;
389
+ delete near.coldAt;
390
+ }
383
391
  near.updatedAt = new Date().toISOString();
384
392
  if (input.dueAt && !near.dueAt) near.dueAt = input.dueAt;
385
393
  this.dirty = true;
@@ -404,6 +412,8 @@ export class CardStore {
404
412
  ...(input.dueAt ? { dueAt: input.dueAt } : {}),
405
413
  ...(kind === 'promise' ? { done: false } : {}),
406
414
  ...(input.src ? { src: input.src } : {}),
415
+ ...(input.keepLongTerm === true ? { keepLongTerm: true } : {}),
416
+ ...(input.summaryOf ? { summaryOf: [...input.summaryOf] } : {}),
407
417
  };
408
418
  this.cards.push(card);
409
419
  this.dirty = true;
@@ -415,6 +425,7 @@ export class CardStore {
415
425
  const card = this.find(id);
416
426
  if (!card) return undefined;
417
427
  Object.assign(card, patch, { updatedAt: new Date().toISOString() });
428
+ if (card.keepLongTerm === true) delete card.coldAt;
418
429
  this.dirty = true;
419
430
  this.save();
420
431
  return card;
@@ -453,7 +464,7 @@ export class CardStore {
453
464
  * 用新卡接替旧卡:旧卡退休、新卡记下它接替了谁。
454
465
  * 返回 [新卡, 旧卡];旧的找不到就只返回新卡。
455
466
  */
456
- supersede(oldId: string, next: Card): { card: Card; replaced: Card | null } {
467
+ supersede(oldId: string, next: Card, inheritKeepLongTerm = true): { card: Card; replaced: Card | null } {
457
468
  const old = this.find(oldId);
458
469
  if (!old || old.id === next.id) return { card: next, replaced: null };
459
470
  old.status = 'retired';
@@ -461,6 +472,11 @@ export class CardStore {
461
472
  old.retiredBy = next.id;
462
473
  old.updatedAt = old.retiredAt;
463
474
  next.supersedes = [...new Set([...(next.supersedes ?? []), old.id])];
475
+ if (old.summaryOf?.length) next.summaryOf = [...new Set([...(next.summaryOf ?? []), ...old.summaryOf])].filter((id) => id !== next.id);
476
+ if (inheritKeepLongTerm && old.keepLongTerm === true) {
477
+ next.keepLongTerm = true;
478
+ delete next.coldAt;
479
+ }
464
480
  this.dirty = true;
465
481
  this.save(true);
466
482
  return { card: next, replaced: old };
@@ -506,8 +522,13 @@ export class CardStore {
506
522
  if (!drop || drop.status === 'retired') continue;
507
523
  kept.tags = [...new Set([...kept.tags, ...drop.tags])].slice(0, 8);
508
524
  kept.weight = Math.max(kept.weight, drop.weight);
525
+ if (drop.keepLongTerm === true) {
526
+ kept.keepLongTerm = true;
527
+ delete kept.coldAt;
528
+ }
509
529
  if (drop.dueAt && (!kept.dueAt || Date.parse(drop.dueAt) < Date.parse(kept.dueAt))) kept.dueAt = drop.dueAt;
510
530
  kept.supersedes = [...new Set([...(kept.supersedes ?? []), ...(drop.supersedes ?? []), drop.id])];
531
+ if (drop.summaryOf?.length) kept.summaryOf = [...new Set([...(kept.summaryOf ?? []), ...drop.summaryOf])].filter((id) => id !== kept.id);
511
532
  kept.updatedAt = new Date().toISOString();
512
533
  drop.status = 'retired';
513
534
  drop.retiredAt = kept.updatedAt;
@@ -639,6 +660,7 @@ export class CardStore {
639
660
  }
640
661
 
641
662
  touch(ids: readonly string[]): void {
663
+ if (!ids.length) return;
642
664
  const now = new Date().toISOString();
643
665
  for (const id of ids) {
644
666
  const card = this.find(id);
@@ -766,7 +788,9 @@ export class CardStore {
766
788
  : undefined,
767
789
  primedCount: Number.isFinite(Number(c.primedCount)) ? Number(c.primedCount) : undefined,
768
790
  lastPrimedAt: typeof c.lastPrimedAt === 'string' ? c.lastPrimedAt : undefined,
769
- coldAt: typeof c.coldAt === 'string' ? c.coldAt : undefined,
791
+ coldAt: c.keepLongTerm !== true && typeof c.coldAt === 'string' ? c.coldAt : undefined,
792
+ keepLongTerm: c.keepLongTerm === true ? true : undefined,
793
+ summaryOf: Array.isArray(c.summaryOf) ? [...new Set(c.summaryOf.filter((ref) => typeof ref === 'string' && /^[\w-]{1,60}$/.test(ref) && ref !== id))] : undefined,
770
794
  };
771
795
  this.cards.push(card);
772
796
  byId.add(id);
@@ -982,44 +1006,44 @@ export class RawLog {
982
1006
 
983
1007
  /** 删掉一条原文:热数据从内存表里摘掉重写;在归档里就改写那天对应的文件。 */
984
1008
  remove(cursor: number): boolean {
985
- const id = Number(cursor);
986
- if (!Number.isFinite(id)) return false;
987
- const at = this.entries.findIndex((e) => e.cursor === id);
988
- if (at >= 0) {
989
- this.entries.splice(at, 1);
990
- this.rewrite();
991
- return true;
1009
+ return this.removeMany([cursor]) > 0;
1010
+ }
1011
+
1012
+ removeMany(cursors: number[]): number {
1013
+ const remaining = new Set(cursors.filter(Number.isSafeInteger));
1014
+ const count = remaining.size;
1015
+ if (!count) return 0;
1016
+ const keptHot = this.entries.filter(entry => !remaining.delete(entry.cursor));
1017
+ if (keptHot.length !== this.entries.length) {
1018
+ if (!writeAtomic(this.file, keptHot.map(entry => JSON.stringify(entry)).join('\n') + '\n')) throw new Error('主人原文未能保存');
1019
+ this.entries = keptHot;
992
1020
  }
993
1021
  for (const { file } of this.archiveFiles()) {
1022
+ if (!remaining.size) break;
994
1023
  try {
995
1024
  const lines = readFileSync(file, 'utf8').split('\n');
996
- let hit = -1;
997
- for (let i = 0; i < lines.length; i += 1) {
998
- if (!lines[i].trim()) continue;
1025
+ const hits: number[] = [];
1026
+ const kept = lines.filter(line => {
1027
+ if (!line.trim()) return false;
999
1028
  try {
1000
- if ((JSON.parse(lines[i]) as RawEntry).cursor === id) {
1001
- hit = i;
1002
- break;
1003
- }
1004
- } catch {
1005
- // 坏行跳过
1006
- }
1007
- }
1008
- if (hit < 0) continue;
1009
- lines.splice(hit, 1);
1010
- const kept = lines.filter((line) => line.trim());
1029
+ const id = (JSON.parse(line) as RawEntry).cursor;
1030
+ if (remaining.has(id)) { hits.push(id); return false; }
1031
+ } catch { /* 保留未识别的行 */ }
1032
+ return true;
1033
+ });
1034
+ if (!hits.length) continue;
1011
1035
  if (!kept.length) {
1012
1036
  // 那天只有这一条,删完就把空文件收掉,免得归档里留个 0 行的日期
1013
1037
  unlinkSync(file);
1014
1038
  } else {
1015
- writeAtomic(file, `${kept.join('\n')}\n`);
1039
+ if (!writeAtomic(file, `${kept.join('\n')}\n`)) continue;
1016
1040
  }
1017
- return true;
1041
+ for (const hit of hits) remaining.delete(hit);
1018
1042
  } catch {
1019
1043
  // 读不了就试下一个文件
1020
1044
  }
1021
1045
  }
1022
- return false;
1046
+ return count - remaining.size;
1023
1047
  }
1024
1048
 
1025
1049
  /** 热数据里的旧格式已经由 load() 的 rewrite 抹掉了,这里只处理 archive/ 下的文件。 */
@@ -1064,6 +1088,24 @@ export class RawLog {
1064
1088
  return n;
1065
1089
  }
1066
1090
 
1091
+ sourceContext(source: NonNullable<Card['src']>): RawEntry[] {
1092
+ const day = dayKeyOf(source.ts);
1093
+ if (!day || !Number.isSafeInteger(source.cursor)) return [];
1094
+ const rows = new Map(this.entries.filter(row => dayKeyOf(row.ts) === day).map(row => [row.cursor, row]));
1095
+ const file = join(this.archiveDir, `${day}.jsonl`);
1096
+ if (existsSync(file)) for (const line of readFileSync(file, 'utf8').split('\n')) {
1097
+ try {
1098
+ const row = JSON.parse(line) as RawEntry;
1099
+ if (typeof row?.text === 'string' && !rows.has(row.cursor)) rows.set(row.cursor, row);
1100
+ } catch { continue; }
1101
+ }
1102
+ const anchor = rows.get(source.cursor);
1103
+ if (!anchor || Date.parse(anchor.ts) !== Date.parse(source.ts) || anchor.sender === 'desktop-pet.self') return [];
1104
+ const nearby = [...rows.values()].filter(row => row.sender === anchor.sender && Math.abs(Date.parse(row.ts) - Date.parse(anchor.ts)) <= 30 * 60_000).sort((left, right) => left.cursor - right.cursor);
1105
+ const at = nearby.indexOf(anchor);
1106
+ return nearby.slice(Math.max(0, at - 2), at + 3).map(row => ({ ...row, sender: maskSender(row.sender) }));
1107
+ }
1108
+
1067
1109
  /** 翻归档:默认最近 30 天,最多 8000 行。只给 mode=archive 用,不进常规召回。 */
1068
1110
  readArchive(days = 30, maxEntries = 8000): RawEntry[] {
1069
1111
  const span = Math.max(1, Math.min(365, Number(days) || 30));
@@ -1077,7 +1119,7 @@ export class RawLog {
1077
1119
  if (!line.trim()) continue;
1078
1120
  try {
1079
1121
  const e = JSON.parse(line) as RawEntry;
1080
- if (e && typeof e.text === 'string') {
1122
+ if (e && typeof e.text === 'string' && e.sender !== 'desktop-pet.self') {
1081
1123
  e.sender = maskSender(e.sender);
1082
1124
  out.push(e);
1083
1125
  }
@@ -1106,7 +1148,7 @@ export class RawLog {
1106
1148
  }
1107
1149
 
1108
1150
  all(): readonly RawEntry[] {
1109
- return this.entries;
1151
+ return this.entries.filter(entry => entry.sender !== 'desktop-pet.self');
1110
1152
  }
1111
1153
 
1112
1154
  reset(): void {
@@ -1124,7 +1166,7 @@ export class RawLog {
1124
1166
  // 回放时一次几千行,用 Set 判重,别拿 some() 平方级扫
1125
1167
  const have = new Set(this.entries.map((e) => e.cursor));
1126
1168
  const fresh = items
1127
- .filter((item) => !have.has(item.cursor))
1169
+ .filter((item) => item.sender !== 'desktop-pet.self' && !have.has(item.cursor))
1128
1170
  // 落盘前统一脱敏:不管调用方传的是原始 key 还是已脱敏的,这里都兜一道
1129
1171
  .map((item) => ({ ...item, sender: maskSender(item.sender) }));
1130
1172
  if (!fresh.length) return 0;
package/src/tools.ts CHANGED
@@ -17,12 +17,8 @@ export const TOOL_SPECS: ToolSpec[] = [
17
17
  {
18
18
  name: 'mcore_write',
19
19
  description:
20
- '写一条记忆。kind:fact=关于对方的事实,self=关于你自己的,'
21
- + 'episode=你自己经历过的(有画面有情绪的事,一天 3-5 条正常),'
22
- + 'promise=答应过的事(必须写 dueAt),note=临时信息和技术操作。'
23
- + '一条只写一件事,40-80 字。旧记录用 closes 关掉。'
24
- + '对方明确说「记一下 / 记住 / 别忘了」时必须调用,按语义选 kind;'
25
- + '编号只在对方问起时给。',
20
+ '写记忆。fact=对方事实,self=自己或关系,episode=亲身经历,promise=承诺须带 dueAt,note=临时或技术操作。'
21
+ + '对方要求记住时必调;一条一事,只在对方问起时给编号。',
26
22
  parameters: obj(
27
23
  {
28
24
  kind: {
@@ -35,6 +31,7 @@ export const TOOL_SPECS: ToolSpec[] = [
35
31
  tags: { type: 'array', items: { type: 'string' } },
36
32
  dueAt: { type: 'string', description: 'promise 用:ISO 或 YYYY-MM-DD HH:MM;没有截止时间写 none' },
37
33
  closes: { type: 'string', description: '要关掉的旧 id' },
34
+ keepLongTerm: { type: 'boolean', description: '明确要求长期保留才传 true' },
38
35
  },
39
36
  ['kind', 'text'],
40
37
  ),
@@ -53,6 +50,7 @@ export const TOOL_SPECS: ToolSpec[] = [
53
50
  tags: { type: 'array', items: { type: 'string' } },
54
51
  dueAt: { type: 'string', description: 'promise 用;none 清空' },
55
52
  done: { type: 'boolean', description: '做完' },
53
+ keepLongTerm: { type: 'boolean', description: '按对方要求开关长期保留' },
56
54
  },
57
55
  ['id'],
58
56
  ),
@@ -61,10 +59,8 @@ export const TOOL_SPECS: ToolSpec[] = [
61
59
  {
62
60
  name: 'mcore_recall',
63
61
  description:
64
- '查记忆。给 query 按内容搜(同时搜最近 7 天原文和工作区笔记),不给就看最近几条;'
65
- + 'mode=open 看没做完的承诺和今天的安排,mode=archive 翻归档(要 query);'
66
- + '给 id 看这条记忆的出处(当时的原话 + 前后文)。'
67
- + '对方提到人或旧事、问「你还记得吗」时先查再答。',
62
+ 'query 搜记忆、近 7 天原文和工作区笔记;不传看最近。'
63
+ + 'open 查未完承诺和日程,archive 搜归档(须 query),id 查出处。提到旧事先查再答。',
68
64
  parameters: obj(
69
65
  {
70
66
  query: { type: 'string', description: '关键词就够' },