cortico-world-memory-core 0.25.0 → 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/CHANGELOG.md +46 -9
- package/ENV_PROMPT.md +9 -10
- package/README.md +32 -14
- package/assets/readme/banner.png +0 -0
- package/assets/screenshots/detail.png +0 -0
- package/assets/screenshots/galaxy.png +0 -0
- package/assets/screenshots/health.png +0 -0
- package/assets/screenshots/turns.png +0 -0
- package/describe.json +294 -235
- package/icon.svg +32 -26
- package/package.json +12 -9
- package/src/config.ts +26 -3
- package/src/recall.ts +118 -8
- package/src/review.ts +146 -0
- package/src/site.ts +57 -10
- package/src/store.ts +85 -39
- package/src/tools.ts +6 -8
- package/src/world.ts +225 -47
- package/webui/app.js +590 -1055
- package/webui/atlas.css +116 -0
- package/webui/index.html +24 -18
- package/webui/next.css +158 -8
- package/webui/next.html +31 -29
- package/webui/next.js +5 -14
- package/webui/starfield/atlas.js +168 -0
- package/webui/starfield/film.svg +22 -0
- package/webui/starfield/lucide-LICENSE.txt +15 -0
- package/webui/starfield/pause.svg +16 -0
- package/webui/starfield/play.svg +15 -0
- package/webui/starfield/scene.js +301 -0
- package/webui/starfield/three-LICENSE.txt +21 -0
- package/webui/starfield/three.core.min.js +6 -0
- package/webui/starfield/three.module.min.js +6 -0
- package/webui/style.css +160 -10
- package/webui/turns.css +21 -0
- package/assets/screenshots/graph.png +0 -0
- package/assets/screenshots/maintenance.png +0 -0
- package/assets/screenshots/table.png +0 -0
- package/assets/screenshots/timeline.png +0 -0
package/src/world.ts
CHANGED
|
@@ -7,10 +7,10 @@
|
|
|
7
7
|
* 2) 不每轮推送状态,只有 contextEveryMin>0 才推,默认 0;
|
|
8
8
|
* 3) 主动开口有「对方最近说过话」这道闸,避免对着空房间调用模型。
|
|
9
9
|
*/
|
|
10
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
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
|
-
|
|
544
|
-
|
|
545
|
-
|
|
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),
|
|
@@ -785,7 +833,13 @@ export class MemoryCoreWorld implements World {
|
|
|
785
833
|
if (name === 'mcore_plan') return this.handlePlan(args);
|
|
786
834
|
return `未知工具:${name}`;
|
|
787
835
|
} catch (error) {
|
|
788
|
-
|
|
836
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
837
|
+
try {
|
|
838
|
+
this.host?.log?.warn?.('[memory-core] 工具失败', { tool: name, error: msg });
|
|
839
|
+
} catch {
|
|
840
|
+
// ignore
|
|
841
|
+
}
|
|
842
|
+
return `执行失败:${msg}`;
|
|
789
843
|
}
|
|
790
844
|
}
|
|
791
845
|
|
|
@@ -817,6 +871,7 @@ export class MemoryCoreWorld implements World {
|
|
|
817
871
|
}
|
|
818
872
|
const doneProvided = typeof args.done === 'boolean';
|
|
819
873
|
const done = doneProvided ? Boolean(args.done) : card.done;
|
|
874
|
+
const keepLongTerm = typeof args.keepLongTerm === 'boolean' ? args.keepLongTerm : undefined;
|
|
820
875
|
|
|
821
876
|
// 正文变了:写新卡接替,旧卡留档(不抹掉「当时是怎么记的」)
|
|
822
877
|
if (text && text !== card.text) {
|
|
@@ -828,10 +883,17 @@ export class MemoryCoreWorld implements World {
|
|
|
828
883
|
dueAt,
|
|
829
884
|
source: 'tool',
|
|
830
885
|
origin: 'tool',
|
|
886
|
+
keepLongTerm,
|
|
831
887
|
...(card.src ? { src: card.src } : {}),
|
|
832
888
|
});
|
|
833
889
|
if (card.kind === 'promise') this.store.close(card.id);
|
|
834
|
-
this.store.
|
|
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);
|
|
892
|
+
try {
|
|
893
|
+
this.host?.log?.info?.('[memory-core] 改口', { from: card.id.slice(0, 8), to: res.card.id.slice(0, 8) });
|
|
894
|
+
} catch {
|
|
895
|
+
// ignore
|
|
896
|
+
}
|
|
835
897
|
return `已改口:${card.id.slice(0, 8)} → ${res.card.id.slice(0, 8)}。旧的那条留在库里可回溯。`;
|
|
836
898
|
}
|
|
837
899
|
|
|
@@ -841,6 +903,7 @@ export class MemoryCoreWorld implements World {
|
|
|
841
903
|
if (has('tags')) patch.tags = [...tags];
|
|
842
904
|
if (dueProvided) patch.dueAt = dueAt;
|
|
843
905
|
if (doneProvided) patch.done = done;
|
|
906
|
+
if (keepLongTerm !== undefined) patch.keepLongTerm = keepLongTerm;
|
|
844
907
|
// 截止时间或完成状态变了:提醒重新计数,别拿旧的「已提醒 6 次」把它压死
|
|
845
908
|
if (dueProvided || doneProvided) {
|
|
846
909
|
patch.remindedAt = undefined;
|
|
@@ -848,6 +911,11 @@ export class MemoryCoreWorld implements World {
|
|
|
848
911
|
}
|
|
849
912
|
if (!Object.keys(patch).length) return '没有要改的字段(正文相同、元数据也没变)。';
|
|
850
913
|
this.store.update(card.id, patch);
|
|
914
|
+
try {
|
|
915
|
+
this.host?.log?.info?.('[memory-core] 改', { id: card.id.slice(0, 8), fields: Object.keys(patch) });
|
|
916
|
+
} catch {
|
|
917
|
+
// ignore
|
|
918
|
+
}
|
|
851
919
|
return `已改:${card.id.slice(0, 8)}…(${Object.keys(patch).filter((k) => k !== 'remindedAt' && k !== 'remindCount').join('、') || '提醒状态'})`;
|
|
852
920
|
}
|
|
853
921
|
|
|
@@ -884,6 +952,7 @@ export class MemoryCoreWorld implements World {
|
|
|
884
952
|
dueAt,
|
|
885
953
|
source: 'tool',
|
|
886
954
|
origin: 'tool',
|
|
955
|
+
keepLongTerm: args.keepLongTerm === true,
|
|
887
956
|
...(src ? { src } : {}),
|
|
888
957
|
});
|
|
889
958
|
let extra = '';
|
|
@@ -908,7 +977,18 @@ export class MemoryCoreWorld implements World {
|
|
|
908
977
|
pile = `\n(提醒:「${top.word}」这个话题已经有 ${top.count} 条了。同一次事别再记一遍——真要合并就写一条新的、用 closes 把旧的收起来;如果它其实是条长期规矩,写成 fact。)`;
|
|
909
978
|
}
|
|
910
979
|
}
|
|
911
|
-
|
|
980
|
+
try {
|
|
981
|
+
this.host?.log?.info?.('[memory-core] 写入', {
|
|
982
|
+
id: res.card.id.slice(0, 8),
|
|
983
|
+
kind,
|
|
984
|
+
chars: text.length,
|
|
985
|
+
merged: res.merged,
|
|
986
|
+
...(closes ? { closes } : {}),
|
|
987
|
+
});
|
|
988
|
+
} catch {
|
|
989
|
+
// 日志失败不影响写入
|
|
990
|
+
}
|
|
991
|
+
return `已记下(${kind}${res.merged ? ',与已有记录合并' : ''} · ${res.card.id.slice(0, 8)})${extra}。共 ${this.store.stats().total} 条。${pile}`;
|
|
912
992
|
}
|
|
913
993
|
|
|
914
994
|
/**
|
|
@@ -946,24 +1026,46 @@ export class MemoryCoreWorld implements World {
|
|
|
946
1026
|
return best;
|
|
947
1027
|
}
|
|
948
1028
|
|
|
949
|
-
private findCard(prefix: string):
|
|
1029
|
+
private findCard(prefix: string): Card | undefined {
|
|
950
1030
|
if (!prefix) return undefined;
|
|
951
1031
|
return this.store.find(prefix) ?? this.store.all().find((c) => c.id.startsWith(prefix)) ?? undefined;
|
|
952
1032
|
}
|
|
953
1033
|
|
|
1034
|
+
private missNote = { q: '', at: 0 };
|
|
1035
|
+
|
|
1036
|
+
/** 搜不到时记一笔,之后按真实缺口补同义词,不靠拍脑袋。 */
|
|
1037
|
+
private logMiss(query: string, kind?: string): void {
|
|
1038
|
+
const q = query.trim().slice(0, 80);
|
|
1039
|
+
if (!q) return;
|
|
1040
|
+
if (this.missNote.q === q && Date.now() - this.missNote.at < 10 * 60_000) return;
|
|
1041
|
+
this.missNote = { q, at: Date.now() };
|
|
1042
|
+
try {
|
|
1043
|
+
appendFileSync(
|
|
1044
|
+
join(this.dataDir, 'misses.jsonl'),
|
|
1045
|
+
`${JSON.stringify({ ts: new Date().toISOString(), query: q, kind: kind ?? null })}\n`,
|
|
1046
|
+
'utf8',
|
|
1047
|
+
);
|
|
1048
|
+
} catch {
|
|
1049
|
+
// 记不上不影响召回
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
954
1053
|
private handleRecall(args: Record<string, unknown>): string {
|
|
955
1054
|
if (!this.cfg().memoryEnabled) return '记忆已关闭(设置页里可以打开)。';
|
|
956
1055
|
const idArg = str(args.id, 60);
|
|
957
1056
|
if (idArg) return this.handleSource(idArg);
|
|
958
1057
|
const query = str(args.query, 200);
|
|
959
1058
|
const mode = String(args.mode ?? (query ? 'search' : 'recent'));
|
|
1059
|
+
const searching = mode === 'search';
|
|
1060
|
+
if (searching && !tokenize(query).length) return '搜索需要有效的关键词。';
|
|
960
1061
|
const limit = num(args.limit, Number(this.cfg().recallLimit) || 5, 1, 12);
|
|
961
1062
|
const maxChars = num(this.cfg().recallMaxChars, 600, 120, 2000);
|
|
962
1063
|
const tz = this.tz();
|
|
963
1064
|
const lines: string[] = [];
|
|
964
1065
|
const push = (line: string) => {
|
|
965
|
-
if (lines.join('\n').length > maxChars) return;
|
|
1066
|
+
if (lines.join('\n').length > maxChars) return false;
|
|
966
1067
|
lines.push(line);
|
|
1068
|
+
return true;
|
|
967
1069
|
};
|
|
968
1070
|
|
|
969
1071
|
if (mode === 'open') {
|
|
@@ -996,17 +1098,19 @@ export class MemoryCoreWorld implements World {
|
|
|
996
1098
|
return out.join('\n').slice(0, maxChars + 40);
|
|
997
1099
|
}
|
|
998
1100
|
|
|
999
|
-
const ranked = rankCardsScored(
|
|
1000
|
-
query:
|
|
1101
|
+
const ranked = rankCardsScored(searching ? this.store.active() : this.store.recallable(), {
|
|
1102
|
+
query: searching ? query : undefined,
|
|
1001
1103
|
kind: str(args.kind, 20) || undefined,
|
|
1002
1104
|
days: num(args.days, 0, 0, 3650) || undefined,
|
|
1003
1105
|
limit,
|
|
1004
1106
|
useAging: this.cfg().recallUseAging !== false,
|
|
1107
|
+
synonyms: this.cfg().synonyms,
|
|
1108
|
+
cacheKey: String(this.store.revision),
|
|
1005
1109
|
});
|
|
1006
1110
|
const cards = ranked.map((x) => x.card);
|
|
1007
1111
|
const strongIds = new Set(ranked.filter((x) => x.tier === 'strong').map((x) => x.card.id));
|
|
1008
1112
|
|
|
1009
|
-
if (
|
|
1113
|
+
if (searching) {
|
|
1010
1114
|
const hits = rankRaw(this.raw.all(), query, Math.max(1, Math.min(3, limit)));
|
|
1011
1115
|
for (const hit of hits) {
|
|
1012
1116
|
const from = senderLabel(hit.sender);
|
|
@@ -1027,23 +1131,34 @@ export class MemoryCoreWorld implements World {
|
|
|
1027
1131
|
if (withSrc.length) push('(↩ 是写它时最近的那句原话;卡片本身是改写的)');
|
|
1028
1132
|
if (cards.some((c) => c.coldAt)) push('(❄ 是很久没被想起的旧记忆,仅供参考)');
|
|
1029
1133
|
|
|
1134
|
+
const hitMap = new Map(ranked.map((x) => [x.card.id, x.matched]));
|
|
1030
1135
|
const cardLine = (card: (typeof cards)[number]) => {
|
|
1031
1136
|
const tag = card.kind === 'fact' ? '' : `(${card.kind})`;
|
|
1032
1137
|
const when = card.src ? formatLocal(card.src.ts, tz).slice(5, 10) : '';
|
|
1033
1138
|
const mark = when ? ` ↩${when}` : '';
|
|
1034
1139
|
const cold = card.coldAt ? '❄' : '';
|
|
1140
|
+
// 解释一下为什么它被召回:模型能判断是字面对上,还是同义词补进来的
|
|
1141
|
+
const hit = searching ? hitMap.get(card.id) ?? [] : [];
|
|
1142
|
+
const why = hit.length ? ` 〔${hit.join('+')}〕` : '';
|
|
1035
1143
|
// 行首这 8 位就是 id:改口/作废时要用它传给 mcore_write 的 closes
|
|
1036
|
-
|
|
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}`;
|
|
1037
1146
|
};
|
|
1038
1147
|
|
|
1148
|
+
// 漏检记录:本地留一份,用来补同义词表;同一条查询 10 分钟内只记一次
|
|
1149
|
+
if (searching && !strongIds.size) {
|
|
1150
|
+
this.logMiss(query, str(args.kind, 20) || undefined);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1039
1153
|
// 搜出来的分两档:真对得上的,和只是靠权重/新鲜度浮上来的。
|
|
1040
1154
|
// 不分档的话,模型会把「有点像」当成「就是」,这也是它编故事的起点。
|
|
1041
|
-
|
|
1155
|
+
const usedIds: string[] = [];
|
|
1156
|
+
if (searching && cards.length) {
|
|
1042
1157
|
const strong = cards.filter((c) => strongIds.has(c.id));
|
|
1043
1158
|
const weak = cards.filter((c) => !strongIds.has(c.id));
|
|
1044
1159
|
if (strong.length) {
|
|
1045
1160
|
push('【对得上】');
|
|
1046
|
-
for (const card of strong) push(cardLine(card));
|
|
1161
|
+
for (const card of strong) if (push(cardLine(card))) usedIds.push(card.id);
|
|
1047
1162
|
if (weak.length) {
|
|
1048
1163
|
push('【可能沾边,别当准】');
|
|
1049
1164
|
for (const card of weak) push(cardLine(card));
|
|
@@ -1054,9 +1169,9 @@ export class MemoryCoreWorld implements World {
|
|
|
1054
1169
|
for (const card of weak.slice(0, 2)) push(cardLine(card));
|
|
1055
1170
|
}
|
|
1056
1171
|
} else {
|
|
1057
|
-
for (const card of cards) push(cardLine(card));
|
|
1172
|
+
for (const card of cards) if (push(cardLine(card))) usedIds.push(card.id);
|
|
1058
1173
|
}
|
|
1059
|
-
this.store.touch(
|
|
1174
|
+
this.store.touch(usedIds);
|
|
1060
1175
|
return lines.length ? lines.join('\n') : '没有找到相关的记忆。';
|
|
1061
1176
|
}
|
|
1062
1177
|
|
|
@@ -1256,6 +1371,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1256
1371
|
);
|
|
1257
1372
|
this.pruneDeletedThoughts();
|
|
1258
1373
|
this.absorbThoughts(now);
|
|
1374
|
+
this.absorbKeepSuggestions();
|
|
1259
1375
|
await this.maybeContext(now);
|
|
1260
1376
|
await this.maybePreactivate(now);
|
|
1261
1377
|
await this.maybeRemind(now);
|
|
@@ -1286,6 +1402,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1286
1402
|
'^(starpost\\.private\\.|qq\\.|desktop-pet\\.message)',
|
|
1287
1403
|
'^(desktop-pet\\.(chat|message|answer|voice)|private:|qq\\.private\\.|starpost\\.private\\.)',
|
|
1288
1404
|
];
|
|
1405
|
+
legacy.push('^(desktop-pet\\.(chat|message|answer|voice)|private:|qq\\.private\\.|qq-official\\.c2c[.:]|starpost\\.private\\.)');
|
|
1289
1406
|
const pattern = !raw || legacy.includes(raw) ? MEMORY_CORE_DEFAULTS.captureSenders : raw;
|
|
1290
1407
|
try {
|
|
1291
1408
|
return new RegExp(pattern);
|
|
@@ -1342,6 +1459,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1342
1459
|
text: string;
|
|
1343
1460
|
type?: string;
|
|
1344
1461
|
tags?: readonly string[];
|
|
1462
|
+
meta?: Record<string, unknown>;
|
|
1345
1463
|
}[] = [];
|
|
1346
1464
|
try {
|
|
1347
1465
|
events = host.store.range({ fromCursor: from + 1, toCursor: to, origin: 'external' });
|
|
@@ -1351,14 +1469,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1351
1469
|
scanned += events.length;
|
|
1352
1470
|
for (const e of events) {
|
|
1353
1471
|
const key = e.senderKey ?? '';
|
|
1354
|
-
|
|
1355
|
-
const tags = Array.isArray(e.tags) ? e.tags : [];
|
|
1356
|
-
// 方向过滤:qq-official 收发共用同一个 senderKey,只能看 type / tags。
|
|
1357
|
-
// 自己说出去的回执带 speak 标签或 *.sent / *.attempt,都不能记成「对方说的」。
|
|
1358
|
-
if ((kind.startsWith('qq-official.') || key.startsWith('qq-official.')) && tags.includes('speak')) continue;
|
|
1359
|
-
if (/\.(sent|attempt)$/.test(kind)) continue;
|
|
1360
|
-
// 插件占位兜底:老版本没有 type/tags 时,靠正文认「准备发送 → 私聊 msg_seq=…」
|
|
1361
|
-
if (/^准备发送\s*(?:→|->)/.test(String(e.text ?? '').trim())) continue;
|
|
1472
|
+
if (isOutboundOrReceipt(e)) continue;
|
|
1362
1473
|
// captureAll 打开时不再看白名单:群里的其他人、自己发的都记
|
|
1363
1474
|
if (!cfg.captureAll && !re.test(key)) {
|
|
1364
1475
|
// 记几个被挡掉的 key,出问题时一眼能看出是白名单还是正文的问题
|
|
@@ -1415,18 +1526,13 @@ export class MemoryCoreWorld implements World {
|
|
|
1415
1526
|
if (now - this.lastUserProbe < 30_000) return this.lastUserAt;
|
|
1416
1527
|
this.lastUserProbe = now;
|
|
1417
1528
|
try {
|
|
1418
|
-
|
|
1419
|
-
try {
|
|
1420
|
-
re = new RegExp(this.cfg().captureSenders || '^(starpost\\.private\\.|qq\\.)');
|
|
1421
|
-
} catch {
|
|
1422
|
-
re = /^(starpost\.private\.|qq\.)/;
|
|
1423
|
-
}
|
|
1529
|
+
const re = this.senderRe(this.cfg());
|
|
1424
1530
|
const events = this.host?.store?.range({ origin: 'external', limit: 60 }) ?? [];
|
|
1425
|
-
let best = 0;
|
|
1426
|
-
let bestText = '';
|
|
1427
|
-
let bestCursor = -1;
|
|
1531
|
+
let best = this.lastUserAt ?? 0;
|
|
1532
|
+
let bestText = this.lastTurn?.text ?? '';
|
|
1533
|
+
let bestCursor = this.lastTurn?.cursor ?? -1;
|
|
1428
1534
|
for (const e of events) {
|
|
1429
|
-
if (!re.test(e.senderKey ?? '')) continue;
|
|
1535
|
+
if (isOutboundOrReceipt(e) || !re.test(e.senderKey ?? '')) continue;
|
|
1430
1536
|
const t = Date.parse(e.ts);
|
|
1431
1537
|
if (Number.isFinite(t) && t > best) {
|
|
1432
1538
|
best = t;
|
|
@@ -1510,6 +1616,8 @@ export class MemoryCoreWorld implements World {
|
|
|
1510
1616
|
useAging: cfg.recallUseAging !== false,
|
|
1511
1617
|
requireHit: true,
|
|
1512
1618
|
minBigrams: 1,
|
|
1619
|
+
synonyms: cfg.synonyms,
|
|
1620
|
+
cacheKey: String(this.store.revision),
|
|
1513
1621
|
})
|
|
1514
1622
|
.map((x) => ({ card: x.card, adj: x.score * (kindBias[x.card.kind] ?? 1) }))
|
|
1515
1623
|
.sort((a, b) => b.adj - a.adj)
|
|
@@ -1575,7 +1683,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1575
1683
|
return null;
|
|
1576
1684
|
}
|
|
1577
1685
|
|
|
1578
|
-
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 }[] {
|
|
1579
1687
|
const file = join(this.dataDir, '..', 'self-awareness', 'thoughts.jsonl');
|
|
1580
1688
|
if (!existsSync(file)) return [];
|
|
1581
1689
|
let lines: string[] = [];
|
|
@@ -1584,10 +1692,10 @@ export class MemoryCoreWorld implements World {
|
|
|
1584
1692
|
} catch {
|
|
1585
1693
|
return [];
|
|
1586
1694
|
}
|
|
1587
|
-
const out:
|
|
1695
|
+
const out: ReturnType<MemoryCoreWorld['readThoughts']> = [];
|
|
1588
1696
|
for (const line of lines) {
|
|
1589
1697
|
try {
|
|
1590
|
-
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 };
|
|
1591
1699
|
// 同上:非字符串一律跳过,别让它变成一张「[object Object]」的卡片
|
|
1592
1700
|
if (typeof t.text !== 'string' || !t.text.trim()) continue;
|
|
1593
1701
|
out.push({
|
|
@@ -1595,6 +1703,7 @@ export class MemoryCoreWorld implements World {
|
|
|
1595
1703
|
ts: String(t.ts ?? ''),
|
|
1596
1704
|
text: t.text,
|
|
1597
1705
|
importance: Number(t.importance) || 0,
|
|
1706
|
+
memoryKeep: t.memoryKeep,
|
|
1598
1707
|
});
|
|
1599
1708
|
} catch {
|
|
1600
1709
|
// 坏行跳过
|
|
@@ -1603,6 +1712,64 @@ export class MemoryCoreWorld implements World {
|
|
|
1603
1712
|
return out.reverse();
|
|
1604
1713
|
}
|
|
1605
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
|
+
|
|
1606
1773
|
/**
|
|
1607
1774
|
* 把「她自己标成很重要」的想法收成一张 self 卡片。
|
|
1608
1775
|
* 文本前面加「独处时写下」——不然它会以卡片的身份进上下文,被当成此刻的想法,
|
|
@@ -1632,6 +1799,17 @@ export class MemoryCoreWorld implements World {
|
|
|
1632
1799
|
return;
|
|
1633
1800
|
}
|
|
1634
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
|
+
}
|
|
1635
1813
|
const victims = this.store
|
|
1636
1814
|
.all()
|
|
1637
1815
|
.filter((c) => c.srcThoughtId && ids.has(c.srcThoughtId))
|