cortico-world-memory-core 0.4.4 → 0.12.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/src/world.ts CHANGED
@@ -1,1199 +1,1456 @@
1
- /**
2
- * 记忆核心:四套记忆合成的一套。
3
- * 一张卡片表 + 4 个工具 + 一段静态提示词 + 自己的状态与日程 + 主动开口。
4
- *
5
- * 省 token 的三条硬约束(改代码时别破坏):
6
- * 1) envPromptVars() 只返回常量,前缀永远不变 → 缓存命中率高;
7
- * 2) 不每轮推送状态,只有 contextEveryMin>0 才推,默认 0;
8
- * 3) 主动开口有「对方最近说过话」这道闸,避免对着空房间调用模型。
9
- */
10
- import { existsSync } from 'node:fs';
11
- import { fileURLToPath } from 'node:url';
12
- import { join } from 'node:path';
13
- import { randomUUID } from 'node:crypto';
14
- import type { ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
15
- import type { WorldContext } from 'cortico/world.ts';
16
- import { MEMORY_CORE_CONFIG_GROUP, MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
17
- import { TOOL_SPECS } from './tools.ts';
18
- import {
19
- CARD_KINDS,
20
- CardStore,
21
- RawLog,
22
- ensureDir,
23
- maskSender,
24
- readJson,
25
- writeJson,
26
- type CardKind,
27
- type CoreState,
28
- type PlanItem,
29
- type RawEntry,
30
- } from './store.ts';
31
- import { importLegacy } from './importer.ts';
32
- import { rankCards, rankRaw } from './recall.ts';
33
- import { advance, createInitialState, moodLabel } from './state.ts';
34
- import { formatLocal, hmToMinutes, humanSpan, inWindow, localParts } from './time.ts';
35
- import { MemorySite, type HealthReport, type ImportReport, type Snapshot } from './site.ts';
36
- import { expandDirs, loadDocs, searchDocs } from './workspace.ts';
37
-
38
- const ENV_PROMPT_FILE = fileURLToPath(new URL('../ENV_PROMPT.md', import.meta.url));
39
- const WEB_DIR = fileURLToPath(new URL('../webui/', import.meta.url));
40
- const TICK_MS = 60_000;
41
-
42
- /**
43
- * 捕获水位的可信版本号。
44
- * v1 用 `range({fromCursor, limit})` 分页,但宿主的 limit 是「从区间末尾取」,
45
- * 一次就把水位推到历史末尾、前面的全跳过。升到 v2 后旧水位作废,自动重放一遍。
46
- */
47
- const CAPTURE_WATERMARK_VERSION = 2;
48
- /** 一次 range 的窗口宽度。cursor 是全局连续的,按窗口边界推进,窗口内没有匹配也能往前走。
49
- * 取大一点:宿主每次 range 都要遍历一遍分片,窗口太碎会让回放变成几百次全表扫描。 */
50
- const CAPTURE_BATCH = 2_000;
51
-
52
- function clip(text: string, limit: number): string {
53
- const s = String(text ?? '').replace(/\s+/g, ' ').trim();
54
- return s.length > limit ? `${s.slice(0, limit)}…` : s;
55
- }
56
-
57
- function num(value: unknown, fallback: number, lo: number, hi: number): number {
58
- const n = Number(value);
59
- if (!Number.isFinite(n)) return fallback;
60
- return Math.min(hi, Math.max(lo, n));
61
- }
62
-
63
- function str(value: unknown, limit = 200): string {
64
- return typeof value === 'string' ? clip(value, limit) : '';
65
- }
66
-
67
- /**
68
- * 事件正文外层常裹着东西,剥干净的才是对方说的话:
69
- * - `[星邮消息] {"text":"..."}` —— JSON 壳;
70
- * - `[11-03 周二 18:04] [typed] 月:在吗` —— 宿主加的抬头(时间 / 输入方式 / 说话人);
71
- * - `【QQ私聊 22:37 月(QQ:1940008084)】:#-479828398 有点` —— QQ 那层壳 + 消息号;
72
- * - `[23:34] [answer] 月回答「…」:选了第 1 项「…」` —— 选项卡的答案,只留选了什么。
73
- */
74
- function extractUserText(raw: string): string {
75
- let text = String(raw ?? '').trim();
76
- const m = /^\[[^\]]{0,12}消息\]\s*(\{[\s\S]*\})$/.exec(text);
77
- if (m) {
78
- try {
79
- const obj = JSON.parse(m[1]) as Record<string, unknown>;
80
- for (const key of ['text', 'message', 'content', 'msg']) {
81
- const v = obj[key];
82
- if (typeof v === 'string' && v.trim()) {
83
- text = v.trim();
84
- break;
85
- }
86
- }
87
- } catch {
88
- // 不是 JSON 就按原样
89
- }
90
- }
91
- // 宿主给每层壳的顺序不固定(【】、#消息号、[时间] [输入方式]、说话人:),
92
- // 一轮一轮剥到不再变化为止;名字那一步排除数字开头,免得把「18:30 开会」吃掉。
93
- let out = text;
94
- for (let i = 0; i < 4; i += 1) {
95
- const next = out
96
- .replace(/^【[^】]{0,40}】[::]?\s*/, '')
97
- .replace(/^#-?\d+\s*/, '')
98
- .replace(/^\[[^\]]{0,24}\]\s*/, '')
99
- .replace(/^(?![\[\d])[^\s::\d]{1,12}[::]\s*/, '');
100
- if (next === out) break;
101
- out = next;
102
- }
103
- return out
104
- .replace(/^[^「」]{0,6}回答「[^」]{0,80}」[::]\s*/, '')
105
- .replace(/^自己写了[::]\s*/, '')
106
- .trim();
107
- }
108
-
109
- export class MemoryCoreWorld implements World {
110
- readonly id = 'memory-core';
111
- private readonly ctx: WorldContext<MemoryCoreConfig>;
112
- private host: WorldHost | null = null;
113
- private readonly dataDir: string;
114
- private readonly store: CardStore;
115
- private readonly raw: RawLog;
116
- private state: CoreState;
117
- private plans: PlanItem[] = [];
118
- private timer: ReturnType<typeof setInterval> | null = null;
119
- private stopped = false;
120
- private ticking = false;
121
- private lastUserProbe = 0;
122
- private lastUserAt: number | null = null;
123
- private lastContextAt = 0;
124
- private lastSaveAt = 0;
125
- private site: MemorySite | null = null;
126
- private siteOrigin: string | null = null;
127
-
128
- constructor(ctx: WorldContext<MemoryCoreConfig>) {
129
- this.ctx = ctx;
130
- const base = typeof ctx.dataDir === 'string' && ctx.dataDir ? ctx.dataDir : '.';
131
- this.dataDir = join(base, 'memory-core');
132
- ensureDir(this.dataDir);
133
- this.store = new CardStore(this.dataDir);
134
- this.raw = new RawLog(
135
- this.dataDir,
136
- Math.max(1, Number(ctx.cfg?.rawRetentionDays ?? 7)),
137
- Math.max(0, Number(ctx.cfg?.rawArchiveDays ?? 90)),
138
- );
139
- this.state = createInitialState(new Date(), this.tz(), this.cfg());
140
- this.load();
141
- }
142
-
143
- private cfg(): MemoryCoreConfig {
144
- return this.ctx.cfg;
145
- }
146
-
147
- private tz(): string {
148
- return this.ctx.timezone || 'Asia/Shanghai';
149
- }
150
-
151
- /**
152
- * 周期提醒的天数。老部署的 config.json 里没有这个键(宿主只在首次激活时写入默认值),
153
- * 所以不能直接 Number(undefined),要回落到默认值。
154
- */
155
- private promiseRepeat(): number {
156
- const raw = this.cfg().promiseRepeatDays;
157
- if (raw === undefined || raw === null) return MEMORY_CORE_DEFAULTS.promiseRepeatDays;
158
- return Math.max(0, Number(raw) || 0);
159
- }
160
-
161
- private load(): void {
162
- try {
163
- const raw = readJson<Partial<CoreState> | null>(join(this.dataDir, 'state.json'), null);
164
- if (raw && typeof raw === 'object') {
165
- this.state = { ...createInitialState(new Date(), this.tz(), this.cfg()), ...raw };
166
- }
167
- const plans = readJson<PlanItem[]>(join(this.dataDir, 'plans.json'), []);
168
- this.plans = Array.isArray(plans) ? plans.filter((p) => p && typeof p.title === 'string') : [];
169
- } catch {
170
- // 读不出来就用初始状态
171
- }
172
- }
173
-
174
- private save(force = false): void {
175
- const now = Date.now();
176
- if (!force && now - this.lastSaveAt < 15_000) return;
177
- this.lastSaveAt = now;
178
- writeJson(join(this.dataDir, 'state.json'), this.state);
179
- writeJson(join(this.dataDir, 'plans.json'), this.plans);
180
- }
181
-
182
- // ---- World 契约 ----
183
-
184
- /** 前缀必须稳定:这里只回常量,不塞时间/计数,否则每次变动都会让整段缓存失效。 */
185
- envPromptVars(): Record<string, string> {
186
- return {};
187
- }
188
-
189
- tools(): ToolDef[] {
190
- return TOOL_SPECS.map((spec) => ({
191
- ...spec,
192
- handler: async (args: Record<string, unknown>) => this.dispatch(spec.name, args ?? {}),
193
- }));
194
- }
195
-
196
- webUi(): WorldWebUiDecl {
197
- const cfg = this.cfg();
198
- const stats = this.store.stats();
199
- const count = this.countToday();
200
- return {
201
- label: '记忆核心',
202
- lamps: [
203
- {
204
- label: '记忆',
205
- state: cfg.memoryEnabled ? 'online' : 'offline',
206
- hint: cfg.memoryEnabled
207
- ? `${stats.total} 条在用的${stats.retired ? ` · ${stats.retired} 条已退休` : ''}`
208
- : '已关闭',
209
- },
210
- {
211
- label: '主动开口',
212
- state: cfg.proactiveEnabled ? 'online' : 'offline',
213
- hint: cfg.proactiveEnabled ? this.dueHint() : '已关闭',
214
- },
215
- {
216
- label: '对话原文',
217
- state: cfg.captureTurns ? 'online' : 'offline',
218
- hint: cfg.captureTurns
219
- ? `${this.raw.size} 行,近 ${cfg.rawRetentionDays} 天${
220
- this.raw.stats().days ? ` · 归档 ${this.raw.stats().days} 天` : ''
221
- }`
222
- : '已关闭',
223
- },
224
- ],
225
- badges: [
226
- { label: '今日主动', value: `${count}/${cfg.proactiveDailyCap || '∞'}` },
227
- { label: '精力', value: Math.round(this.state.energy), tone: this.state.energy < 35 ? 'off' : 'on' },
228
- { label: '记忆', value: stats.total },
229
- ],
230
- promptDocs: [
231
- {
232
- key: 'worlds.memory-core.envPrompt',
233
- title: '记忆核心 · 环境提示词',
234
- description: '进 system 前缀的那一段,没有占位符:改这里不会影响其他插件,但会让前缀重算一次。',
235
- path: ENV_PROMPT_FILE,
236
- role: 'envPrompt',
237
- },
238
- ],
239
- config: [MEMORY_CORE_CONFIG_GROUP],
240
- links: this.siteOrigin
241
- ? [{ label: '记忆地图 · 图谱与时间线', href: this.siteOrigin, inheritTheme: true }]
242
- : [],
243
- storage: [
244
- {
245
- key: 'memory-core-data',
246
- label: '卡片 / 对话原文 / 状态 / 日程',
247
- kind: 'disk',
248
- location: this.dataDir,
249
- danger: true,
250
- note: '清空后卡片、对话原文、状态与日程都不在了(导入过就会重新导入旧记忆)。',
251
- stat: () => `卡片 ${stats.total} 条 · 对话原文 ${this.raw.size} 行 · 日程 ${this.plans.length} 项`,
252
- clear: () => {
253
- this.store.reset();
254
- this.raw.reset();
255
- this.plans = [];
256
- this.state = createInitialState(new Date(), this.tz(), this.cfg());
257
- this.save(true);
258
- return '已清空。';
259
- },
260
- },
261
- ],
262
- };
263
- }
264
-
265
- async start(host: WorldHost): Promise<void> {
266
- this.host = host;
267
- this.stopped = false;
268
- ensureDir(this.dataDir);
269
- this.importOnce();
270
- // 归档里可能还留着老格式的明文账号,抹一次就够(热数据在 load 时已经抹了)
271
- if (!this.state.senderScrubbedAt) {
272
- const scrubbed = this.raw.scrubArchiveSenders();
273
- this.state.senderScrubbedAt = new Date().toISOString();
274
- this.save(true);
275
- if (scrubbed) {
276
- try {
277
- host.log?.info?.(`[memory-core] 归档里 ${scrubbed} 条来源已脱敏`);
278
- } catch {
279
- // 日志失败不影响挂载
280
- }
281
- }
282
- }
283
- try {
284
- host.log?.info?.('[memory-core] 启动', {
285
- dataDir: this.dataDir,
286
- cards: this.store.stats().total,
287
- raw: this.raw.size,
288
- });
289
- } catch {
290
- // 日志失败不影响挂载
291
- }
292
- await this.tick(true);
293
- this.timer = setInterval(() => {
294
- void this.tick(false);
295
- }, TICK_MS);
296
- this.timer.unref?.();
297
- this.save(true);
298
- await this.startSite();
299
- }
300
-
301
- async stop(): Promise<void> {
302
- this.stopped = true;
303
- if (this.timer) clearInterval(this.timer);
304
- this.timer = null;
305
- this.save(true);
306
- this.store.save(true);
307
- await this.site?.stop();
308
- this.site = null;
309
- this.siteOrigin = null;
310
- this.host = null;
311
- }
312
-
313
- // ---- 记忆地图站点 ----
314
-
315
- private async startSite(): Promise<void> {
316
- if (!this.cfg().siteEnabled) return;
317
- try {
318
- this.site = new MemorySite(this.siteHooks(), WEB_DIR, Number(this.cfg().sitePort) || 7801);
319
- this.siteOrigin = await this.site.start();
320
- if (this.siteOrigin) {
321
- try {
322
- this.host?.log?.info?.('[memory-core] 记忆地图已启动', { origin: this.siteOrigin });
323
- } catch {
324
- // 日志失败不影响挂载
325
- }
326
- }
327
- } catch (error) {
328
- this.site = null;
329
- try {
330
- this.host?.log?.warn?.('[memory-core] 记忆地图启动失败', String(error));
331
- } catch {
332
- // ignore
333
- }
334
- }
335
- }
336
-
337
- private docs(): ReturnType<typeof loadDocs> {
338
- const cfg = this.cfg();
339
- if (!cfg.workspaceScanEnabled) return [];
340
- return loadDocs({
341
- dirs: cfg.workspaceDirs,
342
- exts: cfg.workspaceExts,
343
- maxFiles: Number(cfg.workspaceMaxFiles) || 300,
344
- maxFileKB: Number(cfg.workspaceMaxFileKB) || 256,
345
- botDir: this.ctx.botDir,
346
- });
347
- }
348
-
349
- private snapshot(): Snapshot {
350
- const all = this.store.all();
351
- const cards = this.store.active();
352
- const now = Date.now();
353
- const day = (ts: string) => formatLocal(ts, this.tz()).slice(0, 10);
354
- const today = formatLocal(new Date(now), this.tz()).slice(0, 10);
355
- const byKind: Record<string, number> = {};
356
- const tagCount = new Map<string, number>();
357
- const dayCount = new Map<string, number>();
358
- let weightSum = 0;
359
- for (const card of cards) {
360
- byKind[card.kind] = (byKind[card.kind] || 0) + 1;
361
- weightSum += card.weight;
362
- for (const tag of card.tags) tagCount.set(tag, (tagCount.get(tag) || 0) + 1);
363
- const d = day(card.createdAt);
364
- dayCount.set(d, (dayCount.get(d) || 0) + 1);
365
- }
366
- const byDay: Array<{ day: string; n: number }> = [];
367
- for (let i = 13; i >= 0; i -= 1) {
368
- const d = formatLocal(new Date(now - i * 86_400_000), this.tz()).slice(0, 10);
369
- byDay.push({ day: d, n: dayCount.get(d) || 0 });
370
- }
371
- const open = cards.filter((c) => c.kind === 'promise' && !c.done);
372
- const docs = this.docs();
373
- const cfg = this.cfg();
374
- const origin = this.site?.origin ?? this.siteOrigin ?? '';
375
- return {
376
- now: new Date().toISOString(),
377
- cards: all,
378
- turns: this.raw.all(),
379
- plans: this.plans,
380
- state: this.state,
381
- proactive: {
382
- enabled: Boolean(cfg.proactiveEnabled),
383
- count: this.countToday(),
384
- cap: Number(cfg.proactiveDailyCap) || 0,
385
- dueAt: this.state.proactiveDueAt ?? null,
386
- lastTalkAt: this.state.lastTalkAt ?? null,
387
- },
388
- stats: {
389
- total: cards.length,
390
- retired: all.length - cards.length,
391
- byKind,
392
- openPromises: open.length,
393
- overdue: open.filter((c) => c.dueAt && Date.parse(c.dueAt) <= now).length,
394
- todayNew: dayCount.get(today) || 0,
395
- weekNew: byDay.slice(7).reduce((sum, x) => sum + x.n, 0),
396
- avgWeight: cards.length ? weightSum / cards.length : 0,
397
- tags: [...tagCount.entries()].sort((a, b) => b[1] - a[1]).map(([tag, n]) => ({ tag, n })).slice(0, 40),
398
- byDay,
399
- scopes: this.store.scopes(),
400
- },
401
- docs: { enabled: Boolean(cfg.workspaceScanEnabled), count: docs.length, dirs: cfg.workspaceScanEnabled ? expandDirs(cfg.workspaceDirs, this.ctx.botDir) : [] },
402
- archive: { ...this.raw.stats(), retention: Math.max(0, Number(cfg.rawArchiveDays) || 0) },
403
- site: { port: origin ? Number(new URL(origin).port) : 0, origin },
404
- };
405
- }
406
-
407
- private siteHooks() {
408
- return {
409
- snapshot: () => this.snapshot(),
410
- docs: () => this.docs(),
411
- docRoots: () => expandDirs(this.cfg().workspaceDirs, this.ctx.botDir),
412
- createCard: (input: Record<string, unknown>) => {
413
- const kind = String(input.kind ?? 'note') as CardKind;
414
- if (!CARD_KINDS.includes(kind)) throw new Error('kind 只能是 fact / self / episode / promise / note');
415
- const text = String(input.text ?? '').replace(/\s+/g, ' ').trim();
416
- if (!text) throw new Error('内容不能为空');
417
- const dueAt = input.dueAt ? String(input.dueAt).replace(' ', 'T') : undefined;
418
- const res = this.store.add({
419
- kind,
420
- text,
421
- weight: num(input.weight, 0.5, 0, 1),
422
- tags: Array.isArray(input.tags) ? (input.tags as unknown[]).map((t) => String(t)) : [],
423
- dueAt,
424
- source: 'map',
425
- origin: 'map',
426
- });
427
- return res.card;
428
- },
429
- updateCard: (id: string, patch: Record<string, unknown>) => {
430
- const current = this.store.find(id);
431
- if (!current) return undefined;
432
- const next: Record<string, unknown> = {};
433
- const text = typeof patch.text === 'string' ? patch.text.replace(/\s+/g, ' ').trim().slice(0, 500) : '';
434
- if (patch.kind !== undefined) {
435
- const kind = String(patch.kind) as CardKind;
436
- if (!CARD_KINDS.includes(kind)) throw new Error('kind 不合法');
437
- next.kind = kind;
438
- }
439
- if (patch.weight !== undefined) next.weight = num(patch.weight, 0.5, 0, 1);
440
- if (Array.isArray(patch.tags)) {
441
- next.tags = (patch.tags as unknown[]).map((t) => String(t).slice(0, 20)).filter(Boolean).slice(0, 8);
442
- }
443
- if (patch.dueAt !== undefined) next.dueAt = patch.dueAt ? String(patch.dueAt).replace(' ', 'T') : undefined;
444
- if (patch.done !== undefined) next.done = Boolean(patch.done);
445
- if (patch.scope !== undefined) next.scope = String(patch.scope).slice(0, 24) || 'main';
446
- // 内容变了不覆盖:追加一版,旧的标退休并指向新版,可回滚
447
- if (text && text !== current.text) {
448
- const fresh = this.store.revise(id, text, 'edit');
449
- if (!fresh) return undefined;
450
- return Object.keys(next).length ? this.store.update(fresh.id, next) : fresh;
451
- }
452
- return this.store.update(id, next);
453
- },
454
- deleteCard: (id: string) => this.store.retire(id, 'manual') !== undefined,
455
- retireCard: (id: string) => this.store.retire(id, 'manual') !== undefined,
456
- restoreCard: (id: string) => this.store.restore(id) !== undefined,
457
- lineage: (id: string) => this.store.lineage(id),
458
- maintenance: () => ({
459
- dupes: this.store.duplicates().map((g) => ({ score: g.score, ids: g.cards.map((c) => c.id) })),
460
- stale: this.store.stale().map((c) => c.id),
461
- junk: this.store.junk().map((c) => c.id),
462
- retired: this.store.retired().map((c) => c.id),
463
- promises: {
464
- noDue: this.store.promisesWithoutDue().map((c) => c.id),
465
- overdue: this.store
466
- .active()
467
- .filter((c) => c.kind === 'promise' && !c.done && c.dueAt && Date.parse(c.dueAt) <= Date.now())
468
- .map((c) => c.id),
469
- },
470
- }),
471
- health: () => this.healthReport(),
472
- importData: (payload: Record<string, unknown>) => this.importBackup(payload),
473
- archiveSearch: (q: string, days: number, limit: number) => {
474
- const query = String(q ?? '').trim();
475
- if (!query) return [];
476
- const span = Math.min(3650, Math.max(1, Number(days) || 90));
477
- const cap = Math.min(50, Math.max(1, Number(limit) || 40));
478
- return rankRaw(this.raw.readArchive(span, 20000), query, cap);
479
- },
480
- deleteTurn: (cursor: number) => this.raw.remove(cursor),
481
- mergeCards: (keepId: string, dropIds: string[]) => this.store.merge(keepId, dropIds),
482
- purgeCards: (ids: string[]) => this.store.purge(ids),
483
- patchState: (input: Record<string, unknown>) => {
484
- if (input.energy !== undefined) this.state.energy = num(input.energy, this.state.energy, 0, 100);
485
- if (input.mood !== undefined) this.state.mood = num(input.mood, this.state.mood, 0, 100);
486
- if (typeof input.activity === 'string' && input.activity.trim()) this.state.activity = clip(input.activity, 40);
487
- if (typeof input.location === 'string') this.state.location = clip(input.location, 40);
488
- if (input.sleeping !== undefined) {
489
- this.state.sleeping = input.sleeping === true;
490
- if (this.state.sleeping) this.state.activity = '睡觉';
491
- }
492
- this.state.updatedAt = new Date().toISOString();
493
- this.save(true);
494
- return this.state;
495
- },
496
- planAction: (input: Record<string, unknown>) => {
497
- this.handlePlan({ action: input.action, items: input.items, id: input.id });
498
- return { plans: this.plans };
499
- },
500
- exportAll: (fmt: string) => this.exportAll(fmt),
501
- };
502
- }
503
-
504
- private exportAll(fmt: string): { body: string; mime: string; filename: string } {
505
- const stamp = formatLocal(new Date(), this.tz()).replace(/[: ]/g, '-').slice(0, 16);
506
- const live = [...this.store.active()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
507
- const cards = [...this.store.all()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
508
- if (fmt === 'md') {
509
- const title: Record<string, string> = {
510
- fact: '关于你',
511
- self: '关于我',
512
- episode: '一起经历过',
513
- promise: '答应过的事',
514
- note: '临时记下的',
515
- };
516
- const retired = this.store.stats().retired;
517
- const lines = [`# 记忆核心 · ${live.length} 条${retired ? `(另有 ${retired} 条已退休)` : ''}`, ''];
518
- for (const kind of CARD_KINDS) {
519
- const group = live.filter((c) => c.kind === kind);
520
- if (!group.length) continue;
521
- lines.push(`## ${title[kind]}(${group.length})`, '');
522
- for (const card of group) {
523
- const when = formatLocal(card.createdAt, this.tz()).slice(0, 10);
524
- const meta = [`${when}`, `权重 ${card.weight.toFixed(2)}`, card.tags.length ? card.tags.map((t) => `#${t}`).join(' ') : '']
525
- .filter(Boolean)
526
- .join(' · ');
527
- const due = card.dueAt ? `(${card.done ? '已完成' : '未完成'} · 截止 ${formatLocal(card.dueAt, this.tz())})` : '';
528
- lines.push(`- ${card.text}${due}`, ` <sub>${meta}</sub>`);
529
- }
530
- lines.push('');
531
- }
532
- return { body: lines.join('\n'), mime: 'text/markdown', filename: `memory-core-${stamp}.md` };
533
- }
534
- return {
535
- body: JSON.stringify(
536
- {
537
- exportedAt: new Date().toISOString(),
538
- cards,
539
- turns: this.raw.all(),
540
- plans: this.plans,
541
- state: this.state,
542
- },
543
- null,
544
- 2,
545
- ),
546
- mime: 'application/json',
547
- filename: `memory-core-${stamp}.json`,
548
- };
549
- }
550
-
551
- /** 一轮结束:对方刚说过话才把下一次主动往后推,否则内部 turn 会把 dueAt 一路推没。 */
552
- /** 健康面板:只报事实,不猜。给的是「现在库长什么样」,不是评分。 */
553
- private healthReport(): HealthReport {
554
- const now = Date.now();
555
- const all = this.store.all();
556
- const live = this.store.active();
557
- const day = (ts: string) => formatLocal(ts, this.tz()).slice(0, 10);
558
- const dead = live.filter((c) => (c.uses || 0) === 0 && now - Date.parse(c.createdAt) > 7 * 86_400_000);
559
- const count = new Map<string, number>();
560
- for (const c of live) {
561
- const d = day(c.createdAt);
562
- count.set(d, (count.get(d) || 0) + 1);
563
- }
564
- const perDay: Array<{ day: string; n: number }> = [];
565
- for (let i = 13; i >= 0; i -= 1) {
566
- const d = formatLocal(new Date(now - i * 86_400_000), this.tz()).slice(0, 10);
567
- perDay.push({ day: d, n: count.get(d) || 0 });
568
- }
569
- const open = live.filter((c) => c.kind === 'promise' && !c.done);
570
- const rawStats = this.raw.stats();
571
- return {
572
- generatedAt: new Date().toISOString(),
573
- cards: { total: all.length, active: live.length, retired: all.length - live.length, dead: dead.length },
574
- recall: {
575
- calls: live.reduce((n, c) => n + (c.uses || 0), 0),
576
- cardsTouched: live.filter((c) => (c.uses || 0) > 0).length,
577
- },
578
- perDay,
579
- promises: {
580
- open: open.length,
581
- overdue: open.filter((c) => c.dueAt && Date.parse(c.dueAt) <= now).length,
582
- noDue: open.filter((c) => !c.dueAt).length,
583
- repeating: this.promiseRepeat(),
584
- },
585
- raw: { lines: this.raw.size, archivedDays: rawStats.days, archivedLines: this.raw.archiveLines() },
586
- backup: this.store.backupInfo(),
587
- deadIds: dead.map((c) => c.id),
588
- };
589
- }
590
-
591
- /**
592
- * 导入备份。只加不覆盖:已有的卡片按 id 或「同类型 + 同文本」跳过。
593
- * state 只接 rawWatermark 而且只往前推——水位倒回去会把已经录过的原文再录一遍。
594
- */
595
- private importBackup(payload: Record<string, unknown>): ImportReport {
596
- const warnings: string[] = [];
597
- const data = (payload.data && typeof payload.data === 'object' ? payload.data : payload) as Record<string, unknown>;
598
- if (!Array.isArray(data.cards)) warnings.push('没有 cards 字段,只导入了原文和日程。');
599
- const cards = this.store.importCards(Array.isArray(data.cards) ? data.cards : []);
600
-
601
- const turnsIn = Array.isArray(data.turns) ? data.turns : [];
602
- const entries: RawEntry[] = [];
603
- let badTurns = 0;
604
- for (const raw of turnsIn) {
605
- const t = (raw ?? {}) as Partial<RawEntry>;
606
- const cursor = Number(t.cursor);
607
- if (!Number.isFinite(cursor) || typeof t.text !== 'string' || !t.text.trim()) {
608
- badTurns += 1;
609
- continue;
610
- }
611
- entries.push({
612
- cursor,
613
- ts: typeof t.ts === 'string' && t.ts ? t.ts : new Date().toISOString(),
614
- sender: maskSender(String(t.sender ?? 'import')).slice(0, 40),
615
- text: t.text.slice(0, 200),
616
- });
617
- }
618
- const addedTurns = this.raw.add(entries);
619
-
620
- const plansIn = Array.isArray(data.plans) ? data.plans : [];
621
- let plansAdded = 0;
622
- let plansSkipped = 0;
623
- for (const raw of plansIn) {
624
- const p = (raw ?? {}) as Partial<PlanItem>;
625
- const title = typeof p.title === 'string' ? p.title.trim() : '';
626
- const time = typeof p.time === 'string' ? p.time.trim() : '';
627
- if (!title || !time) {
628
- plansSkipped += 1;
629
- continue;
630
- }
631
- if (this.plans.some((x) => x.time === time && x.title === title)) {
632
- plansSkipped += 1;
633
- continue;
634
- }
635
- this.plans.push({
636
- id: typeof p.id === 'string' && p.id ? p.id : randomUUID(),
637
- time,
638
- title,
639
- place: typeof p.place === 'string' ? p.place : undefined,
640
- done: p.done === true,
641
- });
642
- plansAdded += 1;
643
- }
644
- if (plansAdded) this.save(true);
645
-
646
- let watermark = Number(this.state.rawWatermark ?? 0) || 0;
647
- const st = data.state as Partial<CoreState> | undefined;
648
- const incoming = Number(st?.rawWatermark);
649
- if (Number.isFinite(incoming) && incoming > watermark) {
650
- watermark = incoming;
651
- this.state.rawWatermark = watermark;
652
- this.save(true);
653
- }
654
- if (badTurns) warnings.push(`${badTurns} 行原文格式不对,已跳过。`);
655
- if (turnsIn.length && addedTurns === 0) warnings.push('原文都是已有的,没有新增。');
656
- return {
657
- cards,
658
- turns: { added: addedTurns, skipped: turnsIn.length - addedTurns },
659
- plans: { added: plansAdded, skipped: plansSkipped },
660
- state: { watermark },
661
- warnings,
662
- };
663
- }
664
-
665
- onTurnEnded(): void {
666
- const now = new Date();
667
- this.lastUserProbe = 0;
668
- const lastUser = this.probeLastUser(now.getTime());
669
- if (!lastUser || now.getTime() - lastUser > 10 * 60_000) return;
670
- this.state.lastTalkAt = now.toISOString();
671
- this.state.proactiveDueAt = this.nextDue(now).toISOString();
672
- this.save(true);
673
- }
674
-
675
- // ---- 工具实现 ----
676
-
677
- private async dispatch(name: string, args: Record<string, unknown>): Promise<string> {
678
- try {
679
- if (name === 'mcore_write') return this.handleWrite(args);
680
- if (name === 'mcore_recall') return this.handleRecall(args);
681
- if (name === 'mcore_state') return this.handleState(args);
682
- if (name === 'mcore_plan') return this.handlePlan(args);
683
- return `未知工具:${name}`;
684
- } catch (error) {
685
- return `执行失败:${error instanceof Error ? error.message : String(error)}`;
686
- }
687
- }
688
-
689
- private handleWrite(args: Record<string, unknown>): string {
690
- if (!this.cfg().memoryEnabled) return '记忆已关闭(设置页里可以打开)。';
691
- const kind = String(args.kind ?? '') as CardKind;
692
- if (!CARD_KINDS.includes(kind)) return 'kind 只能是 fact / self / episode / promise / note。';
693
- const text = str(args.text, 500);
694
- if (!text) return 'text 不能为空。';
695
- const dueAtRaw = str(args.dueAt, 40).trim();
696
- // 没有时间的承诺等于永远不提醒;但也不能逼模型编一个时间。
697
- // 所以给一条明确出口:确实没有截止时间就写 none,当成「无截止」存下来,体检页可以补。
698
- const undated = /^(none|null|无|没有|无截止)$/i.test(dueAtRaw);
699
- if (kind === 'promise' && !dueAtRaw) {
700
- return '承诺必须带 dueAt(ISO 时间,例如 2026-11-06T07:20)。不知道具体时间就问对方一句;确实没有截止时间就写 dueAt:"none"。';
701
- }
702
- const dueAt = undated ? undefined : dueAtRaw.replace(' ', 'T');
703
- const res = this.store.add({
704
- kind,
705
- text,
706
- weight: num(args.weight, 0.5, 0, 1),
707
- tags: Array.isArray(args.tags) ? (args.tags as unknown[]).map((t) => String(t)) : [],
708
- dueAt,
709
- source: 'tool',
710
- origin: 'tool',
711
- });
712
- let extra = '';
713
- const closes = str(args.closes, 60);
714
- if (closes) {
715
- const target = this.findCard(closes);
716
- if (target && target.id !== res.card.id) {
717
- // 旧的那条不再参与检索,但留在库里可回溯(血缘挂在「新卡接替了谁」上)
718
- if (target.kind === 'promise') this.store.close(target.id);
719
- this.store.supersede(target.id, res.card);
720
- extra = ',被它替代的那条已经收起来';
721
- } else {
722
- extra = ',但要关的记录没找到';
723
- }
724
- }
725
- return `已记下(${kind}${res.merged ? ',与已有记录合并' : ''})${extra}。共 ${this.store.stats().total} 条。`;
726
- }
727
-
728
- private findCard(prefix: string): { id: string; kind: string } | undefined {
729
- if (!prefix) return undefined;
730
- return this.store.find(prefix) ?? this.store.all().find((c) => c.id.startsWith(prefix)) ?? undefined;
731
- }
732
-
733
- private handleRecall(args: Record<string, unknown>): string {
734
- if (!this.cfg().memoryEnabled) return '记忆已关闭(设置页里可以打开)。';
735
- const query = str(args.query, 200);
736
- const mode = String(args.mode ?? (query ? 'search' : 'recent'));
737
- const limit = num(args.limit, Number(this.cfg().recallLimit) || 5, 1, 12);
738
- const maxChars = num(this.cfg().recallMaxChars, 600, 120, 2000);
739
- const tz = this.tz();
740
- const lines: string[] = [];
741
- const push = (line: string) => {
742
- if (lines.join('\n').length > maxChars) return;
743
- lines.push(line);
744
- };
745
-
746
- if (mode === 'open') {
747
- const open = this.store.openPromises(limit);
748
- if (open.length) {
749
- lines.push('【没做完的承诺】');
750
- for (const c of open) {
751
- const due = c.dueAt ? ` 截止 ${formatLocal(c.dueAt, tz)}` : '';
752
- push(`· ${c.id.slice(0, 8)} ${clip(c.text, 90)}${due}`);
753
- }
754
- }
755
- const today = this.plans.filter((p) => !p.done);
756
- if (today.length) {
757
- lines.push('【今天的安排】');
758
- for (const p of today) push(`· ${p.time} ${clip(p.title, 40)}${p.place ? `(${p.place})` : ''}`);
759
- }
760
- return lines.length ? lines.join('\n') : '没有未完成的事。';
761
- }
762
-
763
- if (mode === 'archive') {
764
- if (!query) return '翻归档要带 query,给几个关键词。';
765
- const span = num(args.days, 30, 1, 3650);
766
- const hits = rankRaw(this.raw.readArchive(span), query, Math.max(1, Math.min(limit, 8)));
767
- if (!hits.length) return `归档里没找到「${clip(query, 20)}」。`;
768
- const out: string[] = ['【归档原文】'];
769
- for (const hit of hits) out.push(`· [${formatLocal(hit.ts, tz).slice(0, 10)}] ${clip(hit.text, 110)}`);
770
- return out.join('\n').slice(0, maxChars + 40);
771
- }
772
-
773
- const cards = rankCards(this.store.active(), {
774
- query: mode === 'search' ? query : undefined,
775
- kind: str(args.kind, 20) || undefined,
776
- days: num(args.days, 0, 0, 3650) || undefined,
777
- limit,
778
- useAging: this.cfg().recallUseAging !== false,
779
- });
780
-
781
- if (mode === 'search' && query) {
782
- const hits = rankRaw(this.raw.all(), query, Math.max(1, Math.min(3, limit)));
783
- for (const hit of hits) {
784
- push(`· [对话 ${formatLocal(hit.ts, tz).slice(5)}] ${clip(hit.text, 90)}`);
785
- }
786
- if (this.cfg().workspaceScanEnabled && lines.join('\n').length < maxChars) {
787
- const docHits = searchDocs(this.docs(), query, 2);
788
- for (const hit of docHits) {
789
- push(`· [文件 ${clip(hit.file.rel, 40)}] ${clip(hit.snippet, 90)}`);
790
- }
791
- }
792
- }
793
-
794
- for (const card of cards) {
795
- const tag = card.kind === 'fact' ? '' : `(${card.kind})`;
796
- // 行首这 8 位就是 id:改口/作废时要用它传给 mcore_write 的 closes
797
- push(`· ${card.id.slice(0, 8)} ${formatLocal(card.createdAt, tz).slice(5)} ${clip(card.text, 110)}${tag}`);
798
- }
799
- this.store.touch(cards.map((c) => c.id));
800
- return lines.length ? lines.join('\n') : '没有找到相关的记忆。';
801
- }
802
-
803
- private handleState(args: Record<string, unknown>): string {
804
- const action = String(args.action ?? 'get');
805
- const now = new Date();
806
- if (action === 'rest') {
807
- this.state.sleeping = true;
808
- this.state.activity = '睡觉';
809
- this.state.energy = Math.min(100, this.state.energy + 4);
810
- this.state.proactiveDueAt = new Date(now.getTime() + 90 * 60_000).toISOString();
811
- this.save(true);
812
- return '去睡了,精力回来一点。';
813
- }
814
- if (action === 'update') {
815
- if (args.energy !== undefined) this.state.energy = num(args.energy, this.state.energy, 0, 100);
816
- if (args.mood !== undefined) this.state.mood = num(args.mood, this.state.mood, 0, 100);
817
- if (args.activity !== undefined) this.state.activity = str(args.activity, 40) || this.state.activity;
818
- if (args.location !== undefined) this.state.location = str(args.location, 40) || this.state.location;
819
- if (args.sleeping !== undefined) {
820
- this.state.sleeping = args.sleeping === true;
821
- if (this.state.sleeping) this.state.activity = '睡觉';
822
- }
823
- this.state.updatedAt = now.toISOString();
824
- this.save(true);
825
- }
826
- const stats = this.store.stats();
827
- const dueAt = this.state.proactiveDueAt ? formatLocal(this.state.proactiveDueAt, this.tz()).slice(11) : '未安排';
828
- const count = this.countToday();
829
- return [
830
- `精力 ${Math.round(this.state.energy)}/100,心情 ${moodLabel(this.state.mood)},正在${this.state.activity}${this.state.location ? `,在${this.state.location}` : ''}。`,
831
- `下次主动约 ${dueAt};今天已主动 ${count}/${this.cfg().proactiveDailyCap || '∞'} 次。`,
832
- `记忆 ${stats.total} 条,对话原文 ${this.raw.size} 行。`,
833
- ].join('\n');
834
- }
835
-
836
- private handlePlan(args: Record<string, unknown>): string {
837
- const action = String(args.action ?? 'list');
838
- if (action === 'add') {
839
- const items = Array.isArray(args.items) ? args.items : [];
840
- let added = 0;
841
- for (const raw of items.slice(0, 8)) {
842
- const item = raw as Record<string, unknown>;
843
- const time = str(item.time, 5);
844
- const title = str(item.title, 40);
845
- if (!time || !title || hmToMinutes(time) === null) continue;
846
- this.plans.push({ id: randomUUID(), time, title, place: str(item.place, 30) || undefined });
847
- added += 1;
848
- }
849
- this.plans.sort((a, b) => (hmToMinutes(a.time) ?? 0) - (hmToMinutes(b.time) ?? 0));
850
- this.save(true);
851
- return added ? `加了 ${added} 项,今天共 ${this.plans.filter((p) => !p.done).length} 项。` : '没有有效的项(time 用 HH:MM,title 不能空)。';
852
- }
853
- if (action === 'done') {
854
- const id = str(args.id, 60);
855
- const hit = this.plans.find((p) => p.id === id || p.id.startsWith(id));
856
- if (!hit) return '没找到这一项。';
857
- hit.done = true;
858
- this.save(true);
859
- return `「${hit.title}」标成做完了。`;
860
- }
861
- if (action === 'clear') {
862
- this.plans = [];
863
- this.save(true);
864
- return '日程清空了。';
865
- }
866
- if (!this.plans.length) return '今天没有安排。';
867
- return this.plans
868
- .map((p) => `· ${p.id.slice(0, 8)} ${p.time} ${p.done ? '✓ ' : ''}${p.title}${p.place ? `(${p.place})` : ''}`)
869
- .join('\n');
870
- }
871
-
872
- // ---- 内部 ----
873
-
874
- private importOnce(): void {
875
- const marker = join(this.dataDir, 'imported.json');
876
- if (existsSync(marker)) return;
877
- try {
878
- const report = importLegacy({ dataDir: this.ctx.dataDir, store: this.store });
879
- writeJson(marker, report);
880
- try {
881
- this.host?.log?.info?.('[memory-core] 旧记忆导入完成', report.sources);
882
- } catch {
883
- // ignore
884
- }
885
- } catch (error) {
886
- try {
887
- this.host?.log?.warn?.('[memory-core] 导入失败', String(error));
888
- } catch {
889
- // ignore
890
- }
891
- }
892
- }
893
-
894
- private async tick(force: boolean): Promise<void> {
895
- if (this.ticking) return;
896
- if (this.stopped && !force) return;
897
- this.ticking = true;
898
- try {
899
- const now = new Date();
900
- advance(this.state, now, this.tz(), this.cfg());
901
- this.capture(
902
- Boolean(this.cfg().captureBackfill)
903
- && (Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION || !this.state.backfillDoneAt),
904
- );
905
- await this.maybeContext(now);
906
- await this.maybeRemind(now);
907
- await this.maybeProactive(now);
908
- await this.maybeNightly(now);
909
- this.save();
910
- } catch (error) {
911
- try {
912
- this.host?.log?.warn?.('[memory-core] tick 失败', String(error));
913
- } catch {
914
- // ignore
915
- }
916
- } finally {
917
- this.ticking = false;
918
- }
919
- }
920
-
921
- /**
922
- * 白名单正则。老版本默认值 `^(starpost\.private\.|qq\.|desktop-pet\.message)` 一个真实 key 都匹配不上
923
- * (实际是 `private:1940008084`、`desktop-pet.chat` 这种),读到这个旧默认就换成新的,免得用户
924
- * 明明没动过设置却一直录不到东西。
925
- */
926
- private senderRe(cfg: MemoryCoreConfig): RegExp {
927
- const raw = String(cfg.captureSenders ?? '').trim();
928
- const legacy = '^(starpost\\.private\\.|qq\\.|desktop-pet\\.message)';
929
- const pattern = !raw || raw === legacy ? MEMORY_CORE_DEFAULTS.captureSenders : raw;
930
- try {
931
- return new RegExp(pattern);
932
- } catch {
933
- return new RegExp(MEMORY_CORE_DEFAULTS.captureSenders);
934
- }
935
- }
936
-
937
- /**
938
- * 从宿主的 external 事件流里捞对方说的话。
939
- *
940
- * 宿主 `range` 的语义有两处容易踩:`limit` 是**从区间末尾取**,不是从头取;
941
- * 只有不传 fromCursor 时才走「倒着凑最近 N 条」的快路径。所以拿
942
- * `{fromCursor, limit}` 当分页会一次跳到历史末尾——v1 就是这么把 2.5 万条
943
- * 外对话全跳过的。这里改用 toCursor 开窗,一窗一窗往前推。
944
- */
945
- private capture(backfill = false): void {
946
- const cfg = this.cfg();
947
- const host = this.host;
948
- if (!cfg.captureTurns || !host?.store) return;
949
- const re = this.senderRe(cfg);
950
- // 旧版水位是按错的 limit 语义推出来的,不可信:重放一遍
951
- if (backfill && Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION) {
952
- this.state.rawWatermark = 0;
953
- this.state.watermarkVersion = CAPTURE_WATERMARK_VERSION;
954
- this.state.backfillStartedAt = new Date().toISOString();
955
- this.state.backfillDoneAt = undefined;
956
- }
957
- // 区间上界:只取最后一条,读一个分片就够
958
- let head = 0;
959
- try {
960
- const last = host.store.range({ limit: 1 });
961
- head = last.length ? last[0].cursor : 0;
962
- } catch {
963
- return;
964
- }
965
- let from = Number(this.state.rawWatermark ?? 0) || 0;
966
- if (from > head) from = 0; // 宿主换过数据目录,cursor 从头开始
967
- const minLen = Math.max(1, Number(cfg.captureMinLength) || 4);
968
- const items: RawEntry[] = [];
969
- const keys = new Set<string>();
970
- let scanned = 0;
971
- // 实时每拍最多追 4 窗(2000 条)防积压;回放一次最多 400 窗(20 万条)
972
- const budget = backfill ? 400 : 4;
973
- let rounds = 0;
974
- let drained = from >= head;
975
- while (!drained && rounds < budget) {
976
- rounds += 1;
977
- const to = Math.min(from + CAPTURE_BATCH, head);
978
- let events: readonly { cursor: number; ts: string; senderKey?: string; text: string }[] = [];
979
- try {
980
- events = host.store.range({ fromCursor: from + 1, toCursor: to, origin: 'external' });
981
- } catch {
982
- break;
983
- }
984
- scanned += events.length;
985
- for (const e of events) {
986
- const key = e.senderKey ?? '';
987
- if (!re.test(key)) {
988
- // 记几个被挡掉的 key,出问题时一眼能看出是白名单还是正文的问题
989
- if (key && keys.size < 6) keys.add(key);
990
- continue;
991
- }
992
- const text = clip(extractUserText(e.text), 200);
993
- // 单字、纯表情、`[取消]` 这类系统回执、图片 blob 描述,都不进原文库
994
- if (!text || text.length < minLen) continue;
995
- if (/\[blob\b/i.test(text)) continue;
996
- if (/^\[(表情包|CQ:|图片)/.test(text)) continue;
997
- if (/^[\p{P}\p{S}\s]+$/u.test(text)) continue;
998
- if (/^\[[^\]]{0,12}\]$/.test(text.trim())) continue;
999
- items.push({ cursor: e.cursor, ts: e.ts, sender: maskSender(key).slice(0, 40), text });
1000
- }
1001
- // 按窗口边界推进,不按「最后一个匹配到的 cursor」:窗口里可能一条 external 都没有
1002
- from = to;
1003
- if (from >= head) drained = true;
1004
- }
1005
- this.raw.add(items);
1006
- this.state.rawWatermark = from;
1007
- if (backfill && drained) this.state.backfillDoneAt = new Date().toISOString();
1008
- if (scanned || items.length) {
1009
- this.state.captureDebug = {
1010
- at: new Date().toISOString(),
1011
- scanned,
1012
- kept: items.length,
1013
- keys: items.length ? [] : [...keys],
1014
- ...(backfill && !drained ? { backfillFrom: from, backfillTo: head } : {}),
1015
- };
1016
- }
1017
- }
1018
-
1019
- private countToday(): number {
1020
- const day = localParts(new Date(), this.tz()).date;
1021
- return this.state.proactiveDay === day ? Number(this.state.proactiveCount ?? 0) : 0;
1022
- }
1023
-
1024
- private nextDue(now: Date): Date {
1025
- const cfg = this.cfg();
1026
- const gap = Math.max(5, Number(cfg.proactiveMinGapMin) || 100);
1027
- const jitter = Math.max(0, Number(cfg.proactiveJitterMin) || 0);
1028
- const extra = Math.round(Math.random() * jitter);
1029
- return new Date(now.getTime() + (gap + extra) * 60_000);
1030
- }
1031
-
1032
- private dueHint(): string {
1033
- if (!this.state.proactiveDueAt) return '未安排';
1034
- return `下次约 ${formatLocal(this.state.proactiveDueAt, this.tz()).slice(11)}`;
1035
- }
1036
-
1037
- /** 最近一次「有人跟我说话」的时间;30 秒缓存,避免每拍扫事件库。 */
1038
- private probeLastUser(now: number): number | null {
1039
- if (now - this.lastUserProbe < 30_000) return this.lastUserAt;
1040
- this.lastUserProbe = now;
1041
- try {
1042
- let re: RegExp;
1043
- try {
1044
- re = new RegExp(this.cfg().captureSenders || '^(starpost\\.private\\.|qq\\.)');
1045
- } catch {
1046
- re = /^(starpost\.private\.|qq\.)/;
1047
- }
1048
- const events = this.host?.store?.range({ origin: 'external', limit: 60 }) ?? [];
1049
- let best = 0;
1050
- for (const e of events) {
1051
- if (!re.test(e.senderKey ?? '')) continue;
1052
- const t = Date.parse(e.ts);
1053
- if (Number.isFinite(t) && t > best) best = t;
1054
- }
1055
- this.lastUserAt = best ? best : null;
1056
- } catch {
1057
- this.lastUserAt = null;
1058
- }
1059
- return this.lastUserAt;
1060
- }
1061
-
1062
- private async push(
1063
- type: string,
1064
- text: string,
1065
- trigger: 'piggyback' | 'flush' | 'preempt',
1066
- tags?: readonly 'snapshot'[],
1067
- ): Promise<boolean> {
1068
- if (!this.host) return false;
1069
- try {
1070
- await this.host.pushEvent(
1071
- {
1072
- type,
1073
- ts: new Date().toISOString(),
1074
- source: this.id,
1075
- origin: 'internal',
1076
- text,
1077
- ...(tags ? { tags } : {}),
1078
- },
1079
- { trigger },
1080
- );
1081
- return true;
1082
- } catch (error) {
1083
- try {
1084
- this.host.log?.warn?.('[memory-core] 推送失败', String(error));
1085
- } catch {
1086
- // ignore
1087
- }
1088
- return false;
1089
- }
1090
- }
1091
-
1092
- private async maybeContext(now: Date): Promise<void> {
1093
- const everyMin = Number(this.cfg().contextEveryMin) || 0;
1094
- if (everyMin <= 0) return;
1095
- if (now.getTime() - this.lastContextAt < everyMin * 60_000) return;
1096
- this.lastContextAt = now.getTime();
1097
- const line = `(你现在:${this.state.activity}${this.state.location ? `,在${this.state.location}` : ''},精力 ${Math.round(this.state.energy)},心情${moodLabel(this.state.mood)})`;
1098
- await this.push('mcore.context', line, 'piggyback', ['snapshot']);
1099
- }
1100
-
1101
- private async maybeRemind(now: Date): Promise<void> {
1102
- const due = this.store.duePromises(now.getTime(), this.promiseRepeat());
1103
- if (!due.length) return;
1104
- const lastUser = this.probeLastUser(now.getTime());
1105
- if (this.cfg().requireRecentUserHours > 0) {
1106
- const hours = Number(this.cfg().requireRecentUserHours);
1107
- if (!lastUser || now.getTime() - lastUser > hours * 3_600_000) return;
1108
- }
1109
- const card = due[0];
1110
- const ok = await this.push('mcore.due', `(答应过的事到点了:${clip(card.text, 80)})该提一句了。`, 'flush');
1111
- if (!ok) return;
1112
- this.store.update(card.id, { remindedAt: now.toISOString() });
1113
- }
1114
-
1115
- private async maybeProactive(now: Date): Promise<void> {
1116
- const cfg = this.cfg();
1117
- if (!cfg.proactiveEnabled) return;
1118
- const p = localParts(now, this.tz());
1119
- const due = this.state.proactiveDueAt ? Date.parse(this.state.proactiveDueAt) : 0;
1120
- if (Number.isFinite(due) && due > now.getTime()) return;
1121
-
1122
- const defer = (minutes: number) => {
1123
- this.state.proactiveDueAt = new Date(now.getTime() + minutes * 60_000).toISOString();
1124
- this.save();
1125
- };
1126
-
1127
- if (this.state.sleeping || inWindow(p.minutes, cfg.sleepStart, cfg.sleepEnd)) {
1128
- defer(45);
1129
- return;
1130
- }
1131
- if (inWindow(p.minutes, cfg.quietStart, cfg.quietEnd)) {
1132
- defer(40);
1133
- return;
1134
- }
1135
- const cap = Number(cfg.proactiveDailyCap) || 0;
1136
- const count = this.countToday();
1137
- if (cap > 0 && count >= cap) {
1138
- defer(60);
1139
- return;
1140
- }
1141
- const lastUser = this.probeLastUser(now.getTime());
1142
- const recentHours = Number(cfg.requireRecentUserHours) || 0;
1143
- if (recentHours > 0 && (!lastUser || now.getTime() - lastUser > recentHours * 3_600_000)) {
1144
- // 没人在就不开口,等下一个小时再看;这条是省 token 的关键。
1145
- defer(30);
1146
- return;
1147
- }
1148
- const gate = Number(cfg.idleGateMin) || 0;
1149
- if (lastUser && gate > 0 && now.getTime() - lastUser < gate * 60_000) {
1150
- defer(Math.ceil((gate * 60_000 - (now.getTime() - lastUser)) / 60_000) + 1);
1151
- return;
1152
- }
1153
-
1154
- const since = lastUser ? humanSpan(now.getTime() - lastUser) : null;
1155
- const reason = this.reasonFor(now);
1156
- const text = `(由头:${formatLocal(now, this.tz()).slice(11)},你${this.state.activity}`
1157
- + `${this.state.location ? `,在${this.state.location}` : ''},精力 ${Math.round(this.state.energy)}`
1158
- + `${since ? `;上次说话是 ${since} 前` : ''}。${reason})想主动跟对方说一句,别问「在吗」,直接说你此刻的事。`;
1159
- const ok = await this.push('mcore.wake', text, 'flush');
1160
- if (!ok) {
1161
- defer(15);
1162
- return;
1163
- }
1164
- this.state.proactiveDay = p.date;
1165
- this.state.proactiveCount = count + 1;
1166
- this.state.proactiveDueAt = this.nextDue(now).toISOString();
1167
- this.save(true);
1168
- }
1169
-
1170
- private reasonFor(now: Date): string {
1171
- const p = localParts(now, this.tz());
1172
- const open = this.store.openPromises(3);
1173
- if (open.length) return `上次没做完:${clip(open[0].text, 60)}。`;
1174
- const upcoming = this.plans
1175
- .filter((item) => !item.done && (hmToMinutes(item.time) ?? 0) >= p.minutes)
1176
- .sort((a, b) => (hmToMinutes(a.time) ?? 0) - (hmToMinutes(b.time) ?? 0))[0];
1177
- if (upcoming) return `你打算 ${upcoming.time} ${upcoming.title}。`;
1178
- if (p.hour >= 22) return '天晚了,你想在睡前说一句。';
1179
- if (p.hour >= 6 && p.hour < 9) return '刚醒,你想看看对方起了没。';
1180
- if (this.state.energy < 35) return '你有点累,想说说话缓一缓。';
1181
- if (this.state.mood < 40) return '你心情有点低落,想被陪一会儿。';
1182
- return '你闲下来,忽然想到对方。';
1183
- }
1184
-
1185
- private async maybeNightly(now: Date): Promise<void> {
1186
- const cfg = this.cfg();
1187
- if (!cfg.nightlyConsolidate) return;
1188
- const p = localParts(now, this.tz());
1189
- if (p.hour !== (Number(cfg.nightlyHour) || 3)) return;
1190
- if (this.state.lastNightlyDay === p.date) return;
1191
- const recent = this.raw.all().slice(-40).map((e) => `· ${e.text}`).join('\n');
1192
- const text = `(夜里整理)把今天的事写成 1-2 条 episode,把答应过没做完的写成 promise(带 dueAt),用 mcore_write 写。只写新的,不要重复。\n最近的对话:\n${clip(recent, 1200)}`;
1193
- const ok = await this.push('mcore.nightly', text, 'flush');
1194
- if (ok) {
1195
- this.state.lastNightlyDay = p.date;
1196
- this.save(true);
1197
- }
1198
- }
1199
- }
1
+ /**
2
+ * 记忆核心:四套记忆合成的一套。
3
+ * 一张卡片表 + 4 个工具 + 一段静态提示词 + 自己的状态与日程 + 主动开口。
4
+ *
5
+ * 省 token 的三条硬约束(改代码时别破坏):
6
+ * 1) envPromptVars() 只返回常量,前缀永远不变 → 缓存命中率高;
7
+ * 2) 不每轮推送状态,只有 contextEveryMin>0 才推,默认 0;
8
+ * 3) 主动开口有「对方最近说过话」这道闸,避免对着空房间调用模型。
9
+ */
10
+ import { existsSync } from 'node:fs';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { join } from 'node:path';
13
+ import { randomUUID } from 'node:crypto';
14
+ import type { ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
15
+ import type { WorldContext } from 'cortico/world.ts';
16
+ import { MEMORY_CORE_CONFIG_GROUP, MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
17
+ import { TOOL_SPECS } from './tools.ts';
18
+ import {
19
+ CARD_KINDS,
20
+ CardStore,
21
+ RawLog,
22
+ ensureDir,
23
+ maskSender,
24
+ readJson,
25
+ writeJson,
26
+ type CardKind,
27
+ type CoreState,
28
+ type PlanItem,
29
+ type RawEntry,
30
+ } from './store.ts';
31
+ import { importLegacy } from './importer.ts';
32
+ import { isContentToken, rankCardsScored, rankRaw, tokenize } from './recall.ts';
33
+ import { advance, createInitialState, moodLabel } from './state.ts';
34
+ import { formatLocal, hmToMinutes, humanSpan, inWindow, localParts } from './time.ts';
35
+ import { MemorySite, type HealthReport, type ImportReport, type Snapshot } from './site.ts';
36
+ import { expandDirs, loadDocs, searchDocs } from './workspace.ts';
37
+
38
+ const ENV_PROMPT_FILE = fileURLToPath(new URL('../ENV_PROMPT.md', import.meta.url));
39
+ const WEB_DIR = fileURLToPath(new URL('../webui/', import.meta.url));
40
+ const TICK_MS = 60_000;
41
+ /** 同一张卡两次「主动想起」之间至少隔这么久,别每轮都推同一条。 */
42
+ const PRIME_COOLDOWN_MS = 2 * 3_600_000;
43
+ /** 对方那句话超过这么久就不算「刚说的」,不拿它做预激活。 */
44
+ const PRIME_FRESH_MS = 10 * 60_000;
45
+
46
+ /**
47
+ * 捕获水位的可信版本号。
48
+ * v1 用 `range({fromCursor, limit})` 分页,但宿主的 limit 是「从区间末尾取」,
49
+ * 一次就把水位推到历史末尾、前面的全跳过。升到 v2 后旧水位作废,自动重放一遍。
50
+ */
51
+ const CAPTURE_WATERMARK_VERSION = 2;
52
+ /** 一次 range 的窗口宽度。cursor 是全局连续的,按窗口边界推进,窗口内没有匹配也能往前走。
53
+ * 取大一点:宿主每次 range 都要遍历一遍分片,窗口太碎会让回放变成几百次全表扫描。 */
54
+ const CAPTURE_BATCH = 2_000;
55
+
56
+ function clip(text: string, limit: number): string {
57
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
58
+ return s.length > limit ? `${s.slice(0, limit)}…` : s;
59
+ }
60
+
61
+ function num(value: unknown, fallback: number, lo: number, hi: number): number {
62
+ const n = Number(value);
63
+ if (!Number.isFinite(n)) return fallback;
64
+ return Math.min(hi, Math.max(lo, n));
65
+ }
66
+
67
+ function str(value: unknown, limit = 200): string {
68
+ return typeof value === 'string' ? clip(value, limit) : '';
69
+ }
70
+
71
+ /**
72
+ * 事件正文外层常裹着东西,剥干净的才是对方说的话:
73
+ * - `[星邮消息] {"text":"..."}` —— JSON 壳;
74
+ * - `[11-03 周二 18:04] [typed] 月:在吗` —— 宿主加的抬头(时间 / 输入方式 / 说话人);
75
+ * - `【QQ私聊 22:37 月(QQ:1940008084)】:#-479828398 有点` —— QQ 那层壳 + 消息号;
76
+ * - `[23:34] [answer] 月回答「…」:选了第 1 项「…」` —— 选项卡的答案,只留选了什么。
77
+ */
78
+ function extractUserText(raw: string): string {
79
+ let text = String(raw ?? '').trim();
80
+ const m = /^\[[^\]]{0,12}消息\]\s*(\{[\s\S]*\})$/.exec(text);
81
+ if (m) {
82
+ try {
83
+ const obj = JSON.parse(m[1]) as Record<string, unknown>;
84
+ for (const key of ['text', 'message', 'content', 'msg']) {
85
+ const v = obj[key];
86
+ if (typeof v === 'string' && v.trim()) {
87
+ text = v.trim();
88
+ break;
89
+ }
90
+ }
91
+ } catch {
92
+ // 不是 JSON 就按原样
93
+ }
94
+ }
95
+ // 宿主给每层壳的顺序不固定(【】、#消息号、[时间] [输入方式]、说话人:),
96
+ // 一轮一轮剥到不再变化为止;名字那一步排除数字开头,免得把「18:30 开会」吃掉。
97
+ let out = text;
98
+ for (let i = 0; i < 4; i += 1) {
99
+ const next = out
100
+ .replace(/^【[^】]{0,40}】[::]?\s*/, '')
101
+ .replace(/^#-?\d+\s*/, '')
102
+ .replace(/^\[[^\]]{0,24}\]\s*/, '')
103
+ .replace(/^(?![\[\d])[^\s::\d]{1,12}[::]\s*/, '');
104
+ if (next === out) break;
105
+ out = next;
106
+ }
107
+ return out
108
+ .replace(/^[^「」]{0,6}回答「[^」]{0,80}」[::]\s*/, '')
109
+ .replace(/^自己写了[::]\s*/, '')
110
+ .trim();
111
+ }
112
+
113
+ export class MemoryCoreWorld implements World {
114
+ readonly id = 'memory-core';
115
+ private readonly ctx: WorldContext<MemoryCoreConfig>;
116
+ private host: WorldHost | null = null;
117
+ private readonly dataDir: string;
118
+ private readonly store: CardStore;
119
+ private readonly raw: RawLog;
120
+ private state: CoreState;
121
+ private plans: PlanItem[] = [];
122
+ private timer: ReturnType<typeof setInterval> | null = null;
123
+ private stopped = false;
124
+ private ticking = false;
125
+ private lastUserProbe = 0;
126
+ private lastUserAt: number | null = null;
127
+ /** 对方最近说的那一句(游标 + 文本):预激活拿它当线索,写卡拿它当出处。 */
128
+ private lastTurn: { cursor: number; text: string; at: number } | null = null;
129
+ /** 已经为哪一句做过预激活,同一句不重复推。 */
130
+ private primedFor = '';
131
+ private lastContextAt = 0;
132
+ private lastSaveAt = 0;
133
+ private site: MemorySite | null = null;
134
+ private siteOrigin: string | null = null;
135
+
136
+ constructor(ctx: WorldContext<MemoryCoreConfig>) {
137
+ this.ctx = ctx;
138
+ const base = typeof ctx.dataDir === 'string' && ctx.dataDir ? ctx.dataDir : '.';
139
+ this.dataDir = join(base, 'memory-core');
140
+ ensureDir(this.dataDir);
141
+ this.store = new CardStore(this.dataDir);
142
+ this.raw = new RawLog(
143
+ this.dataDir,
144
+ Math.max(1, Number(ctx.cfg?.rawRetentionDays ?? 7)),
145
+ Math.max(0, Number(ctx.cfg?.rawArchiveDays ?? 90)),
146
+ );
147
+ this.state = createInitialState(new Date(), this.tz(), this.cfg());
148
+ this.load();
149
+ }
150
+
151
+ private cfg(): MemoryCoreConfig {
152
+ return this.ctx.cfg;
153
+ }
154
+
155
+ private tz(): string {
156
+ return this.ctx.timezone || 'Asia/Shanghai';
157
+ }
158
+
159
+ /**
160
+ * 周期提醒的天数。老部署的 config.json 里没有这个键(宿主只在首次激活时写入默认值),
161
+ * 所以不能直接 Number(undefined),要回落到默认值。
162
+ */
163
+ private promiseRepeat(): number {
164
+ const raw = this.cfg().promiseRepeatDays;
165
+ if (raw === undefined || raw === null) return MEMORY_CORE_DEFAULTS.promiseRepeatDays;
166
+ return Math.max(0, Number(raw) || 0);
167
+ }
168
+
169
+ /** 老部署的 config.json 没有 preactivateLines 这个键,缺省时回落到默认值而不是 0。 */
170
+ private preactivateCount(): number {
171
+ const raw = this.cfg().preactivateLines;
172
+ if (raw === undefined || raw === null) return MEMORY_CORE_DEFAULTS.preactivateLines;
173
+ return Math.min(3, Math.max(0, Number(raw) || 0));
174
+ }
175
+
176
+ /** 同样的坑:缺这个键时 Number(undefined) 是 NaN,会把冷层静默关掉。 */
177
+ private chillDays(): number {
178
+ const raw = this.cfg().chillAfterDays;
179
+ if (raw === undefined || raw === null) return MEMORY_CORE_DEFAULTS.chillAfterDays;
180
+ return Math.max(0, Number(raw) || 0);
181
+ }
182
+
183
+ private load(): void {
184
+ try {
185
+ const raw = readJson<Partial<CoreState> | null>(join(this.dataDir, 'state.json'), null);
186
+ if (raw && typeof raw === 'object') {
187
+ this.state = { ...createInitialState(new Date(), this.tz(), this.cfg()), ...raw };
188
+ }
189
+ const plans = readJson<PlanItem[]>(join(this.dataDir, 'plans.json'), []);
190
+ this.plans = Array.isArray(plans) ? plans.filter((p) => p && typeof p.title === 'string') : [];
191
+ } catch {
192
+ // 读不出来就用初始状态
193
+ }
194
+ }
195
+
196
+ private save(force = false): void {
197
+ const now = Date.now();
198
+ if (!force && now - this.lastSaveAt < 15_000) return;
199
+ this.lastSaveAt = now;
200
+ writeJson(join(this.dataDir, 'state.json'), this.state);
201
+ writeJson(join(this.dataDir, 'plans.json'), this.plans);
202
+ }
203
+
204
+ // ---- World 契约 ----
205
+
206
+ /** 前缀必须稳定:这里只回常量,不塞时间/计数,否则每次变动都会让整段缓存失效。 */
207
+ envPromptVars(): Record<string, string> {
208
+ return {};
209
+ }
210
+
211
+ tools(): ToolDef[] {
212
+ return TOOL_SPECS.map((spec) => ({
213
+ ...spec,
214
+ handler: async (args: Record<string, unknown>) => this.dispatch(spec.name, args ?? {}),
215
+ }));
216
+ }
217
+
218
+ webUi(): WorldWebUiDecl {
219
+ const cfg = this.cfg();
220
+ const stats = this.store.stats();
221
+ const count = this.countToday();
222
+ return {
223
+ label: '记忆核心',
224
+ lamps: [
225
+ {
226
+ label: '记忆',
227
+ state: cfg.memoryEnabled ? 'online' : 'offline',
228
+ hint: cfg.memoryEnabled
229
+ ? `${stats.total} 条在用的${stats.retired ? ` · ${stats.retired} 条已退休` : ''}`
230
+ : '已关闭',
231
+ },
232
+ {
233
+ label: '主动开口',
234
+ state: cfg.proactiveEnabled ? 'online' : 'offline',
235
+ hint: cfg.proactiveEnabled ? this.dueHint() : '已关闭',
236
+ },
237
+ {
238
+ label: '对话原文',
239
+ state: cfg.captureTurns ? 'online' : 'offline',
240
+ hint: cfg.captureTurns
241
+ ? `${this.raw.size} 行,近 ${cfg.rawRetentionDays} 天${
242
+ this.raw.stats().days ? ` · 归档 ${this.raw.stats().days} 天` : ''
243
+ }`
244
+ : '已关闭',
245
+ },
246
+ ],
247
+ badges: [
248
+ { label: '今日主动', value: `${count}/${cfg.proactiveDailyCap || '∞'}` },
249
+ { label: '精力', value: Math.round(this.state.energy), tone: this.state.energy < 35 ? 'off' : 'on' },
250
+ { label: '记忆', value: stats.total },
251
+ ],
252
+ promptDocs: [
253
+ {
254
+ key: 'worlds.memory-core.envPrompt',
255
+ title: '记忆核心 · 环境提示词',
256
+ description: '进 system 前缀的那一段,没有占位符:改这里不会影响其他插件,但会让前缀重算一次。',
257
+ path: ENV_PROMPT_FILE,
258
+ role: 'envPrompt',
259
+ },
260
+ ],
261
+ config: [MEMORY_CORE_CONFIG_GROUP],
262
+ links: this.siteOrigin
263
+ ? [{ label: '记忆地图 · 图谱与时间线', href: this.siteOrigin, inheritTheme: true }]
264
+ : [],
265
+ storage: [
266
+ {
267
+ key: 'memory-core-data',
268
+ label: '卡片 / 对话原文 / 状态 / 日程',
269
+ kind: 'disk',
270
+ location: this.dataDir,
271
+ danger: true,
272
+ note: '清空后卡片、对话原文、状态与日程都不在了(导入过就会重新导入旧记忆)。',
273
+ stat: () => `卡片 ${stats.total} 条 · 对话原文 ${this.raw.size} 行 · 日程 ${this.plans.length} 项`,
274
+ clear: () => {
275
+ this.store.reset();
276
+ this.raw.reset();
277
+ this.plans = [];
278
+ this.state = createInitialState(new Date(), this.tz(), this.cfg());
279
+ this.save(true);
280
+ return '已清空。';
281
+ },
282
+ },
283
+ ],
284
+ };
285
+ }
286
+
287
+ async start(host: WorldHost): Promise<void> {
288
+ this.host = host;
289
+ this.stopped = false;
290
+ ensureDir(this.dataDir);
291
+ this.importOnce();
292
+ // 归档里可能还留着老格式的明文账号,抹一次就够(热数据在 load 时已经抹了)
293
+ if (!this.state.senderScrubbedAt) {
294
+ const scrubbed = this.raw.scrubArchiveSenders();
295
+ this.state.senderScrubbedAt = new Date().toISOString();
296
+ this.save(true);
297
+ if (scrubbed) {
298
+ try {
299
+ host.log?.info?.(`[memory-core] 归档里 ${scrubbed} 条来源已脱敏`);
300
+ } catch {
301
+ // 日志失败不影响挂载
302
+ }
303
+ }
304
+ }
305
+ try {
306
+ host.log?.info?.('[memory-core] 启动', {
307
+ dataDir: this.dataDir,
308
+ cards: this.store.stats().total,
309
+ raw: this.raw.size,
310
+ });
311
+ } catch {
312
+ // 日志失败不影响挂载
313
+ }
314
+ await this.tick(true);
315
+ this.timer = setInterval(() => {
316
+ void this.tick(false);
317
+ }, TICK_MS);
318
+ this.timer.unref?.();
319
+ this.save(true);
320
+ await this.startSite();
321
+ }
322
+
323
+ async stop(): Promise<void> {
324
+ this.stopped = true;
325
+ if (this.timer) clearInterval(this.timer);
326
+ this.timer = null;
327
+ this.save(true);
328
+ this.store.save(true);
329
+ await this.site?.stop();
330
+ this.site = null;
331
+ this.siteOrigin = null;
332
+ this.host = null;
333
+ }
334
+
335
+ // ---- 记忆地图站点 ----
336
+
337
+ private async startSite(): Promise<void> {
338
+ if (!this.cfg().siteEnabled) return;
339
+ try {
340
+ this.site = new MemorySite(this.siteHooks(), WEB_DIR, Number(this.cfg().sitePort) || 7801);
341
+ this.siteOrigin = await this.site.start();
342
+ if (this.siteOrigin) {
343
+ try {
344
+ this.host?.log?.info?.('[memory-core] 记忆地图已启动', { origin: this.siteOrigin });
345
+ } catch {
346
+ // 日志失败不影响挂载
347
+ }
348
+ }
349
+ } catch (error) {
350
+ this.site = null;
351
+ try {
352
+ this.host?.log?.warn?.('[memory-core] 记忆地图启动失败', String(error));
353
+ } catch {
354
+ // ignore
355
+ }
356
+ }
357
+ }
358
+
359
+ private docs(): ReturnType<typeof loadDocs> {
360
+ const cfg = this.cfg();
361
+ if (!cfg.workspaceScanEnabled) return [];
362
+ return loadDocs({
363
+ dirs: cfg.workspaceDirs,
364
+ exts: cfg.workspaceExts,
365
+ maxFiles: Number(cfg.workspaceMaxFiles) || 300,
366
+ maxFileKB: Number(cfg.workspaceMaxFileKB) || 256,
367
+ botDir: this.ctx.botDir,
368
+ });
369
+ }
370
+
371
+ private snapshot(): Snapshot {
372
+ const all = this.store.all();
373
+ const cards = this.store.active();
374
+ const now = Date.now();
375
+ const day = (ts: string) => formatLocal(ts, this.tz()).slice(0, 10);
376
+ const today = formatLocal(new Date(now), this.tz()).slice(0, 10);
377
+ const byKind: Record<string, number> = {};
378
+ const tagCount = new Map<string, number>();
379
+ const dayCount = new Map<string, number>();
380
+ let weightSum = 0;
381
+ for (const card of cards) {
382
+ byKind[card.kind] = (byKind[card.kind] || 0) + 1;
383
+ weightSum += card.weight;
384
+ for (const tag of card.tags) tagCount.set(tag, (tagCount.get(tag) || 0) + 1);
385
+ const d = day(card.createdAt);
386
+ dayCount.set(d, (dayCount.get(d) || 0) + 1);
387
+ }
388
+ const byDay: Array<{ day: string; n: number }> = [];
389
+ for (let i = 13; i >= 0; i -= 1) {
390
+ const d = formatLocal(new Date(now - i * 86_400_000), this.tz()).slice(0, 10);
391
+ byDay.push({ day: d, n: dayCount.get(d) || 0 });
392
+ }
393
+ const open = cards.filter((c) => c.kind === 'promise' && !c.done);
394
+ const docs = this.docs();
395
+ const cfg = this.cfg();
396
+ const origin = this.site?.origin ?? this.siteOrigin ?? '';
397
+ return {
398
+ now: new Date().toISOString(),
399
+ cards: all,
400
+ turns: this.raw.all(),
401
+ plans: this.plans,
402
+ state: this.state,
403
+ proactive: {
404
+ enabled: Boolean(cfg.proactiveEnabled),
405
+ count: this.countToday(),
406
+ cap: Number(cfg.proactiveDailyCap) || 0,
407
+ dueAt: this.state.proactiveDueAt ?? null,
408
+ lastTalkAt: this.state.lastTalkAt ?? null,
409
+ },
410
+ stats: {
411
+ total: cards.length,
412
+ retired: all.length - cards.length,
413
+ byKind,
414
+ openPromises: open.length,
415
+ overdue: open.filter((c) => c.dueAt && Date.parse(c.dueAt) <= now).length,
416
+ todayNew: dayCount.get(today) || 0,
417
+ weekNew: byDay.slice(7).reduce((sum, x) => sum + x.n, 0),
418
+ avgWeight: cards.length ? weightSum / cards.length : 0,
419
+ tags: [...tagCount.entries()].sort((a, b) => b[1] - a[1]).map(([tag, n]) => ({ tag, n })).slice(0, 40),
420
+ byDay,
421
+ scopes: this.store.scopes(),
422
+ },
423
+ docs: { enabled: Boolean(cfg.workspaceScanEnabled), count: docs.length, dirs: cfg.workspaceScanEnabled ? expandDirs(cfg.workspaceDirs, this.ctx.botDir) : [] },
424
+ archive: { ...this.raw.stats(), retention: Math.max(0, Number(cfg.rawArchiveDays) || 0) },
425
+ site: { port: origin ? Number(new URL(origin).port) : 0, origin },
426
+ };
427
+ }
428
+
429
+ private siteHooks() {
430
+ return {
431
+ snapshot: () => this.snapshot(),
432
+ docs: () => this.docs(),
433
+ docRoots: () => expandDirs(this.cfg().workspaceDirs, this.ctx.botDir),
434
+ createCard: (input: Record<string, unknown>) => {
435
+ const kind = String(input.kind ?? 'note') as CardKind;
436
+ if (!CARD_KINDS.includes(kind)) throw new Error('kind 只能是 fact / self / episode / promise / note');
437
+ const text = String(input.text ?? '').replace(/\s+/g, ' ').trim();
438
+ if (!text) throw new Error('内容不能为空');
439
+ const dueAt = input.dueAt ? String(input.dueAt).replace(' ', 'T') : undefined;
440
+ const res = this.store.add({
441
+ kind,
442
+ text,
443
+ weight: num(input.weight, 0.5, 0, 1),
444
+ tags: Array.isArray(input.tags) ? (input.tags as unknown[]).map((t) => String(t)) : [],
445
+ dueAt,
446
+ source: 'map',
447
+ origin: 'map',
448
+ });
449
+ return res.card;
450
+ },
451
+ updateCard: (id: string, patch: Record<string, unknown>) => {
452
+ const current = this.store.find(id);
453
+ if (!current) return undefined;
454
+ const next: Record<string, unknown> = {};
455
+ const text = typeof patch.text === 'string' ? patch.text.replace(/\s+/g, ' ').trim().slice(0, 500) : '';
456
+ if (patch.kind !== undefined) {
457
+ const kind = String(patch.kind) as CardKind;
458
+ if (!CARD_KINDS.includes(kind)) throw new Error('kind 不合法');
459
+ next.kind = kind;
460
+ }
461
+ if (patch.weight !== undefined) next.weight = num(patch.weight, 0.5, 0, 1);
462
+ if (Array.isArray(patch.tags)) {
463
+ next.tags = (patch.tags as unknown[]).map((t) => String(t).slice(0, 20)).filter(Boolean).slice(0, 8);
464
+ }
465
+ if (patch.dueAt !== undefined) next.dueAt = patch.dueAt ? String(patch.dueAt).replace(' ', 'T') : undefined;
466
+ if (patch.done !== undefined) next.done = Boolean(patch.done);
467
+ if (patch.scope !== undefined) next.scope = String(patch.scope).slice(0, 24) || 'main';
468
+ // 内容变了不覆盖:追加一版,旧的标退休并指向新版,可回滚
469
+ if (text && text !== current.text) {
470
+ const fresh = this.store.revise(id, text, 'edit');
471
+ if (!fresh) return undefined;
472
+ return Object.keys(next).length ? this.store.update(fresh.id, next) : fresh;
473
+ }
474
+ return this.store.update(id, next);
475
+ },
476
+ deleteCard: (id: string) => this.store.retire(id, 'manual') !== undefined,
477
+ retireCard: (id: string) => this.store.retire(id, 'manual') !== undefined,
478
+ restoreCard: (id: string) => this.store.restore(id) !== undefined,
479
+ lineage: (id: string) => this.store.lineage(id),
480
+ maintenance: () => ({
481
+ dupes: this.store.duplicates().map((g) => ({ score: g.score, ids: g.cards.map((c) => c.id) })),
482
+ stale: this.store.stale().map((c) => c.id),
483
+ junk: this.store.junk().map((c) => c.id),
484
+ retired: this.store.retired().map((c) => c.id),
485
+ promises: {
486
+ noDue: this.store.promisesWithoutDue().map((c) => c.id),
487
+ overdue: this.store
488
+ .active()
489
+ .filter((c) => c.kind === 'promise' && !c.done && c.dueAt && Date.parse(c.dueAt) <= Date.now())
490
+ .map((c) => c.id),
491
+ },
492
+ }),
493
+ health: () => this.healthReport(),
494
+ importData: (payload: Record<string, unknown>) => this.importBackup(payload),
495
+ archiveSearch: (q: string, days: number, limit: number) => {
496
+ const query = String(q ?? '').trim();
497
+ if (!query) return [];
498
+ const span = Math.min(3650, Math.max(1, Number(days) || 90));
499
+ const cap = Math.min(50, Math.max(1, Number(limit) || 40));
500
+ return rankRaw(this.raw.readArchive(span, 20000), query, cap);
501
+ },
502
+ deleteTurn: (cursor: number) => this.raw.remove(cursor),
503
+ mergeCards: (keepId: string, dropIds: string[]) => this.store.merge(keepId, dropIds),
504
+ purgeCards: (ids: string[]) => this.store.purge(ids),
505
+ chillCards: (ids: string[]) =>
506
+ this.store.chill(
507
+ ids.length ? ids : this.store.chillEligible(this.chillDays(), Date.now()).map((c) => c.id),
508
+ ),
509
+ warmCards: (ids: string[]) => this.store.warm(ids.length ? ids : this.store.cold().map((c) => c.id)),
510
+ patchState: (input: Record<string, unknown>) => {
511
+ if (input.energy !== undefined) this.state.energy = num(input.energy, this.state.energy, 0, 100);
512
+ if (input.mood !== undefined) this.state.mood = num(input.mood, this.state.mood, 0, 100);
513
+ if (typeof input.activity === 'string' && input.activity.trim()) this.state.activity = clip(input.activity, 40);
514
+ if (typeof input.location === 'string') this.state.location = clip(input.location, 40);
515
+ if (input.sleeping !== undefined) {
516
+ this.state.sleeping = input.sleeping === true;
517
+ if (this.state.sleeping) this.state.activity = '睡觉';
518
+ }
519
+ this.state.updatedAt = new Date().toISOString();
520
+ this.save(true);
521
+ return this.state;
522
+ },
523
+ planAction: (input: Record<string, unknown>) => {
524
+ this.handlePlan({ action: input.action, items: input.items, id: input.id, time: input.time, title: input.title, place: input.place });
525
+ return { plans: this.plans };
526
+ },
527
+ exportAll: (fmt: string) => this.exportAll(fmt),
528
+ };
529
+ }
530
+
531
+ private exportAll(fmt: string): { body: string; mime: string; filename: string } {
532
+ const stamp = formatLocal(new Date(), this.tz()).replace(/[: ]/g, '-').slice(0, 16);
533
+ const live = [...this.store.active()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
534
+ const cards = [...this.store.all()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
535
+ if (fmt === 'md') {
536
+ const title: Record<string, string> = {
537
+ fact: '关于你',
538
+ self: '关于我',
539
+ episode: '一起经历过',
540
+ promise: '答应过的事',
541
+ note: '临时记下的',
542
+ };
543
+ const retired = this.store.stats().retired;
544
+ const lines = [`# 记忆核心 · ${live.length} 条${retired ? `(另有 ${retired} 条已退休)` : ''}`, ''];
545
+ for (const kind of CARD_KINDS) {
546
+ const group = live.filter((c) => c.kind === kind);
547
+ if (!group.length) continue;
548
+ lines.push(`## ${title[kind]}(${group.length})`, '');
549
+ for (const card of group) {
550
+ const when = formatLocal(card.createdAt, this.tz()).slice(0, 10);
551
+ const meta = [`${when}`, `权重 ${card.weight.toFixed(2)}`, card.tags.length ? card.tags.map((t) => `#${t}`).join(' ') : '']
552
+ .filter(Boolean)
553
+ .join(' · ');
554
+ const due = card.dueAt ? `(${card.done ? '已完成' : '未完成'} · 截止 ${formatLocal(card.dueAt, this.tz())})` : '';
555
+ lines.push(`- ${card.text}${due}`, ` <sub>${meta}</sub>`);
556
+ }
557
+ lines.push('');
558
+ }
559
+ return { body: lines.join('\n'), mime: 'text/markdown', filename: `memory-core-${stamp}.md` };
560
+ }
561
+ return {
562
+ body: JSON.stringify(
563
+ {
564
+ exportedAt: new Date().toISOString(),
565
+ cards,
566
+ turns: this.raw.all(),
567
+ plans: this.plans,
568
+ state: this.state,
569
+ },
570
+ null,
571
+ 2,
572
+ ),
573
+ mime: 'application/json',
574
+ filename: `memory-core-${stamp}.json`,
575
+ };
576
+ }
577
+
578
+ /** 一轮结束:对方刚说过话才把下一次主动往后推,否则内部 turn 会把 dueAt 一路推没。 */
579
+ /** 健康面板:只报事实,不猜。给的是「现在库长什么样」,不是评分。 */
580
+ private healthReport(): HealthReport {
581
+ const now = Date.now();
582
+ const all = this.store.all();
583
+ const live = this.store.active();
584
+ const day = (ts: string) => formatLocal(ts, this.tz()).slice(0, 10);
585
+ // 被用过 = 工具召回 + 每轮预激活。只算前者会把「系统主动想起过」的卡误判成死卡
586
+ const touched = (c: { uses?: number; primedCount?: number }) => (c.uses || 0) + (c.primedCount || 0);
587
+ const dead = live.filter((c) => touched(c) === 0 && now - Date.parse(c.createdAt) > 7 * 86_400_000);
588
+ const count = new Map<string, number>();
589
+ for (const c of live) {
590
+ const d = day(c.createdAt);
591
+ count.set(d, (count.get(d) || 0) + 1);
592
+ }
593
+ const perDay: Array<{ day: string; n: number }> = [];
594
+ for (let i = 13; i >= 0; i -= 1) {
595
+ const d = formatLocal(new Date(now - i * 86_400_000), this.tz()).slice(0, 10);
596
+ perDay.push({ day: d, n: count.get(d) || 0 });
597
+ }
598
+ const open = live.filter((c) => c.kind === 'promise' && !c.done);
599
+ const rawStats = this.raw.stats();
600
+ return {
601
+ generatedAt: new Date().toISOString(),
602
+ cards: { total: all.length, active: live.length, retired: all.length - live.length, dead: dead.length },
603
+ recall: {
604
+ calls: live.reduce((n, c) => n + (c.uses || 0), 0),
605
+ cardsTouched: live.filter((c) => touched(c) > 0).length,
606
+ primed: live.reduce((n, c) => n + (c.primedCount || 0), 0),
607
+ },
608
+ perDay,
609
+ promises: {
610
+ open: open.length,
611
+ overdue: open.filter((c) => c.dueAt && Date.parse(c.dueAt) <= now).length,
612
+ noDue: open.filter((c) => !c.dueAt).length,
613
+ repeating: this.promiseRepeat(),
614
+ },
615
+ raw: { lines: this.raw.size, archivedDays: rawStats.days, archivedLines: this.raw.archiveLines() },
616
+ backup: this.store.backupInfo(),
617
+ chill: {
618
+ cold: this.store.cold().length,
619
+ eligible: this.store.chillEligible(this.chillDays(), now).length,
620
+ afterDays: this.chillDays(),
621
+ },
622
+ deadIds: dead.map((c) => c.id),
623
+ coldIds: this.store.cold().map((c) => c.id),
624
+ };
625
+ }
626
+
627
+ /**
628
+ * 导入备份。只加不覆盖:已有的卡片按 id 或「同类型 + 同文本」跳过。
629
+ * state 只接 rawWatermark 而且只往前推——水位倒回去会把已经录过的原文再录一遍。
630
+ */
631
+ private importBackup(payload: Record<string, unknown>): ImportReport {
632
+ const warnings: string[] = [];
633
+ const data = (payload.data && typeof payload.data === 'object' ? payload.data : payload) as Record<string, unknown>;
634
+ if (!Array.isArray(data.cards)) warnings.push('没有 cards 字段,只导入了原文和日程。');
635
+ const cards = this.store.importCards(Array.isArray(data.cards) ? data.cards : []);
636
+
637
+ const turnsIn = Array.isArray(data.turns) ? data.turns : [];
638
+ const entries: RawEntry[] = [];
639
+ let badTurns = 0;
640
+ for (const raw of turnsIn) {
641
+ const t = (raw ?? {}) as Partial<RawEntry>;
642
+ const cursor = Number(t.cursor);
643
+ if (!Number.isFinite(cursor) || typeof t.text !== 'string' || !t.text.trim()) {
644
+ badTurns += 1;
645
+ continue;
646
+ }
647
+ entries.push({
648
+ cursor,
649
+ ts: typeof t.ts === 'string' && t.ts ? t.ts : new Date().toISOString(),
650
+ sender: maskSender(String(t.sender ?? 'import')).slice(0, 40),
651
+ text: t.text.slice(0, 200),
652
+ });
653
+ }
654
+ const addedTurns = this.raw.add(entries);
655
+
656
+ const plansIn = Array.isArray(data.plans) ? data.plans : [];
657
+ let plansAdded = 0;
658
+ let plansSkipped = 0;
659
+ for (const raw of plansIn) {
660
+ const p = (raw ?? {}) as Partial<PlanItem>;
661
+ const title = typeof p.title === 'string' ? p.title.trim() : '';
662
+ const time = typeof p.time === 'string' ? p.time.trim() : '';
663
+ if (!title || !time) {
664
+ plansSkipped += 1;
665
+ continue;
666
+ }
667
+ if (this.plans.some((x) => x.time === time && x.title === title)) {
668
+ plansSkipped += 1;
669
+ continue;
670
+ }
671
+ this.plans.push({
672
+ id: typeof p.id === 'string' && p.id ? p.id : randomUUID(),
673
+ time,
674
+ title,
675
+ place: typeof p.place === 'string' ? p.place : undefined,
676
+ done: p.done === true,
677
+ });
678
+ plansAdded += 1;
679
+ }
680
+ if (plansAdded) this.save(true);
681
+
682
+ let watermark = Number(this.state.rawWatermark ?? 0) || 0;
683
+ const st = data.state as Partial<CoreState> | undefined;
684
+ const incoming = Number(st?.rawWatermark);
685
+ if (Number.isFinite(incoming) && incoming > watermark) {
686
+ watermark = incoming;
687
+ this.state.rawWatermark = watermark;
688
+ this.save(true);
689
+ }
690
+ if (badTurns) warnings.push(`${badTurns} 行原文格式不对,已跳过。`);
691
+ if (turnsIn.length && addedTurns === 0) warnings.push('原文都是已有的,没有新增。');
692
+ return {
693
+ cards,
694
+ turns: { added: addedTurns, skipped: turnsIn.length - addedTurns },
695
+ plans: { added: plansAdded, skipped: plansSkipped },
696
+ state: { watermark },
697
+ warnings,
698
+ };
699
+ }
700
+
701
+ onTurnEnded(): void {
702
+ const now = new Date();
703
+ this.lastUserProbe = 0;
704
+ const lastUser = this.probeLastUser(now.getTime());
705
+ if (!lastUser || now.getTime() - lastUser > 10 * 60_000) return;
706
+ this.state.lastTalkAt = now.toISOString();
707
+ this.state.proactiveDueAt = this.nextDue(now).toISOString();
708
+ this.save(true);
709
+ // 回合结束时就把下一轮要用的记忆推上去:心跳 60 秒一次,短对话根本等不到它
710
+ void this.maybePreactivate(now).catch(() => {
711
+ // 推送失败不影响这一轮
712
+ });
713
+ // 夜里备好的整理材料,趁这次开口交付
714
+ void this.deliverNightly().catch(() => {
715
+ // 同上
716
+ });
717
+ }
718
+
719
+ // ---- 工具实现 ----
720
+
721
+ private async dispatch(name: string, args: Record<string, unknown>): Promise<string> {
722
+ try {
723
+ if (name === 'mcore_write') return this.handleWrite(args);
724
+ if (name === 'mcore_recall') return this.handleRecall(args);
725
+ if (name === 'mcore_state') return this.handleState(args);
726
+ if (name === 'mcore_plan') return this.handlePlan(args);
727
+ return `未知工具:${name}`;
728
+ } catch (error) {
729
+ return `执行失败:${error instanceof Error ? error.message : String(error)}`;
730
+ }
731
+ }
732
+
733
+ private handleWrite(args: Record<string, unknown>): string {
734
+ if (!this.cfg().memoryEnabled) return '记忆已关闭(设置页里可以打开)。';
735
+ const kind = String(args.kind ?? '') as CardKind;
736
+ if (!CARD_KINDS.includes(kind)) return 'kind 只能是 fact / self / episode / promise / note。';
737
+ const text = str(args.text, 500);
738
+ if (!text) return 'text 不能为空。';
739
+ const dueAtRaw = str(args.dueAt, 40).trim();
740
+ // 没有时间的承诺等于永远不提醒;但也不能逼模型编一个时间。
741
+ // 所以给一条明确出口:确实没有截止时间就写 none,当成「无截止」存下来,体检页可以补。
742
+ const undated = /^(none|null|无|没有|无截止)$/i.test(dueAtRaw);
743
+ if (kind === 'promise' && !dueAtRaw) {
744
+ return '承诺必须带 dueAt(ISO 时间,例如 2026-11-06T07:20)。不知道具体时间就问对方一句;确实没有截止时间就写 dueAt:"none"。';
745
+ }
746
+ const dueAt = undated ? undefined : dueAtRaw.replace(' ', 'T');
747
+ // 出处:写这条时最近的一句对方原话。半小时内才算,太久就对不上了
748
+ this.probeLastUser(Date.now());
749
+ const src =
750
+ this.lastTurn && Date.now() - this.lastTurn.at < 30 * 60_000
751
+ ? { cursor: this.lastTurn.cursor, ts: new Date(this.lastTurn.at).toISOString() }
752
+ : undefined;
753
+ const res = this.store.add({
754
+ kind,
755
+ text,
756
+ weight: num(args.weight, 0.5, 0, 1),
757
+ tags: Array.isArray(args.tags) ? (args.tags as unknown[]).map((t) => String(t)) : [],
758
+ dueAt,
759
+ source: 'tool',
760
+ origin: 'tool',
761
+ ...(src ? { src } : {}),
762
+ });
763
+ let extra = '';
764
+ const closes = str(args.closes, 60);
765
+ if (closes) {
766
+ const target = this.findCard(closes);
767
+ if (target && target.id !== res.card.id) {
768
+ // 旧的那条不再参与检索,但留在库里可回溯(血缘挂在「新卡接替了谁」上)
769
+ if (target.kind === 'promise') this.store.close(target.id);
770
+ this.store.supersede(target.id, res.card);
771
+ extra = ',被它替代的那条已经收起来';
772
+ } else {
773
+ extra = ',但要关的记录没找到';
774
+ }
775
+ }
776
+ // 同一话题堆了太多条时提醒一句。文本相似度靠不住——「每天发一条小黑盒」
777
+ // 换个说法 Jaccard 就掉到 0.2,所以改用「实词是不是反复出现在别的卡里」来判。
778
+ let pile = '';
779
+ if (kind === 'episode' && !res.merged) {
780
+ const top = this.topicPile(text);
781
+ if (top) {
782
+ pile = `\n(提醒:「${top.word}」这个话题已经有 ${top.count} 条了。同一次事别再记一遍——真要合并就写一条新的、用 closes 把旧的收起来;如果它其实是条长期规矩,写成 fact。)`;
783
+ }
784
+ }
785
+ return `已记下(${kind}${res.merged ? ',与已有记录合并' : ''})${extra}。共 ${this.store.stats().total} 条。${pile}`;
786
+ }
787
+
788
+ /**
789
+ * 这段话里某个实词在库里出现过几次(不含刚写进来的这条)。
790
+ * 分词只有二元组,所以「小黑」这类会先扩成「小黑盒」再数——不然提示里出现半个词很蠢。
791
+ */
792
+ private topicPile(text: string, min = 4): { word: string; count: number } | null {
793
+ const tokens = [...new Set(tokenize(text).filter(isContentToken))];
794
+ if (!tokens.length) return null;
795
+ const live = this.store.active();
796
+ const countOf = (word: string) => live.reduce((n, c) => n + (c.text.includes(word) ? 1 : 0), 0) - 1;
797
+
798
+ let best: { word: string; count: number } | null = null;
799
+ for (const token of tokens) {
800
+ const at = text.indexOf(token);
801
+ const cands = new Set<string>([token]);
802
+ if (at >= 0) {
803
+ const right = at + token.length < text.length ? text[at + token.length] : '';
804
+ const left = at > 0 ? text[at - 1] : '';
805
+ if (right) cands.add(token + right);
806
+ if (left) cands.add(left + token);
807
+ if (left && right) cands.add(left + token + right);
808
+ }
809
+ let hit: { word: string; count: number } | null = null;
810
+ for (const word of cands) {
811
+ const count = countOf(word);
812
+ if (count < min) continue;
813
+ // 同样够格的,取最长的那个(「小黑盒」比「小黑」说得清楚)
814
+ if (!hit || word.length > hit.word.length || (word.length === hit.word.length && count > hit.count)) {
815
+ hit = { word, count };
816
+ }
817
+ }
818
+ if (hit && (!best || hit.count > best.count)) best = hit;
819
+ }
820
+ return best;
821
+ }
822
+
823
+ private findCard(prefix: string): { id: string; kind: string } | undefined {
824
+ if (!prefix) return undefined;
825
+ return this.store.find(prefix) ?? this.store.all().find((c) => c.id.startsWith(prefix)) ?? undefined;
826
+ }
827
+
828
+ private handleRecall(args: Record<string, unknown>): string {
829
+ if (!this.cfg().memoryEnabled) return '记忆已关闭(设置页里可以打开)。';
830
+ const query = str(args.query, 200);
831
+ const mode = String(args.mode ?? (query ? 'search' : 'recent'));
832
+ const limit = num(args.limit, Number(this.cfg().recallLimit) || 5, 1, 12);
833
+ const maxChars = num(this.cfg().recallMaxChars, 600, 120, 2000);
834
+ const tz = this.tz();
835
+ const lines: string[] = [];
836
+ const push = (line: string) => {
837
+ if (lines.join('\n').length > maxChars) return;
838
+ lines.push(line);
839
+ };
840
+
841
+ if (mode === 'open') {
842
+ const open = this.store.openPromises(limit);
843
+ if (open.length) {
844
+ lines.push('【没做完的承诺】');
845
+ for (const c of open) {
846
+ const due = c.dueAt ? ` 截止 ${formatLocal(c.dueAt, tz)}` : '';
847
+ push(`· ${c.id.slice(0, 8)} ${clip(c.text, 90)}${due}`);
848
+ }
849
+ }
850
+ const today = this.plans.filter((p) => !p.done);
851
+ if (today.length) {
852
+ lines.push('【今天的安排】');
853
+ for (const p of today) push(`· ${p.time} ${clip(p.title, 40)}${p.place ? `(${p.place})` : ''}`);
854
+ }
855
+ return lines.length ? lines.join('\n') : '没有未完成的事。';
856
+ }
857
+
858
+ if (mode === 'archive') {
859
+ if (!query) return '翻归档要带 query,给几个关键词。';
860
+ const span = num(args.days, 30, 1, 3650);
861
+ const hits = rankRaw(this.raw.readArchive(span), query, Math.max(1, Math.min(limit, 8)));
862
+ if (!hits.length) return `归档里没找到「${clip(query, 20)}」。`;
863
+ const out: string[] = ['【归档原文】'];
864
+ for (const hit of hits) out.push(`· [${formatLocal(hit.ts, tz).slice(0, 10)}] ${clip(hit.text, 110)}`);
865
+ return out.join('\n').slice(0, maxChars + 40);
866
+ }
867
+
868
+ const ranked = rankCardsScored(mode === 'search' ? this.store.active() : this.store.recallable(), {
869
+ query: mode === 'search' ? query : undefined,
870
+ kind: str(args.kind, 20) || undefined,
871
+ days: num(args.days, 0, 0, 3650) || undefined,
872
+ limit,
873
+ useAging: this.cfg().recallUseAging !== false,
874
+ });
875
+ const cards = ranked.map((x) => x.card);
876
+ const strongIds = new Set(ranked.filter((x) => x.tier === 'strong').map((x) => x.card.id));
877
+
878
+ if (mode === 'search' && query) {
879
+ const hits = rankRaw(this.raw.all(), query, Math.max(1, Math.min(3, limit)));
880
+ for (const hit of hits) {
881
+ push(`· [对话 ${formatLocal(hit.ts, tz).slice(5)}] ${clip(hit.text, 90)}`);
882
+ }
883
+ if (this.cfg().workspaceScanEnabled && lines.join('\n').length < maxChars) {
884
+ const docHits = searchDocs(this.docs(), query, 2);
885
+ for (const hit of docHits) {
886
+ push(`· [文件 ${clip(hit.file.rel, 40)}] ${clip(hit.snippet, 90)}`);
887
+ }
888
+ }
889
+ }
890
+
891
+ const withSrc = cards.filter((c) => c.src);
892
+ if (withSrc.length) push('(↩ 是写它时最近的那句原话;卡片本身是改写的)');
893
+ if (cards.some((c) => c.coldAt)) push('(❄ 是很久没被想起的旧记忆,仅供参考)');
894
+
895
+ const cardLine = (card: (typeof cards)[number]) => {
896
+ const tag = card.kind === 'fact' ? '' : `(${card.kind})`;
897
+ const when = card.src ? formatLocal(card.src.ts, tz).slice(5, 10) : '';
898
+ const mark = when ? ` ↩${when}` : '';
899
+ const cold = card.coldAt ? '❄' : '';
900
+ // 行首这 8 位就是 id:改口/作废时要用它传给 mcore_write 的 closes
901
+ return `· ${card.id.slice(0, 8)} ${cold}${formatLocal(card.createdAt, tz).slice(5)} ${clip(card.text, 110)}${tag}${mark}`;
902
+ };
903
+
904
+ // 搜出来的分两档:真对得上的,和只是靠权重/新鲜度浮上来的。
905
+ // 不分档的话,模型会把「有点像」当成「就是」,这也是它编故事的起点。
906
+ if (mode === 'search' && query && cards.length) {
907
+ const strong = cards.filter((c) => strongIds.has(c.id));
908
+ const weak = cards.filter((c) => !strongIds.has(c.id));
909
+ if (strong.length) {
910
+ push('【对得上】');
911
+ for (const card of strong) push(cardLine(card));
912
+ if (weak.length) {
913
+ push('【可能沾边,别当准】');
914
+ for (const card of weak) push(cardLine(card));
915
+ }
916
+ } else {
917
+ // 一条都没真对上时,别拿五条沾边的充数:明说没有,最多给两条线索
918
+ push('【没有对得上的,下面只是沾边】');
919
+ for (const card of weak.slice(0, 2)) push(cardLine(card));
920
+ }
921
+ } else {
922
+ for (const card of cards) push(cardLine(card));
923
+ }
924
+ this.store.touch(cards.map((c) => c.id));
925
+ return lines.length ? lines.join('\n') : '没有找到相关的记忆。';
926
+ }
927
+
928
+ private handleState(args: Record<string, unknown>): string {
929
+ const action = String(args.action ?? 'get');
930
+ const now = new Date();
931
+ if (action === 'rest') {
932
+ this.state.sleeping = true;
933
+ this.state.activity = '睡觉';
934
+ this.state.energy = Math.min(100, this.state.energy + 4);
935
+ this.state.proactiveDueAt = new Date(now.getTime() + 90 * 60_000).toISOString();
936
+ this.save(true);
937
+ return '去睡了,精力回来一点。';
938
+ }
939
+ if (action === 'update') {
940
+ if (args.energy !== undefined) this.state.energy = num(args.energy, this.state.energy, 0, 100);
941
+ if (args.mood !== undefined) this.state.mood = num(args.mood, this.state.mood, 0, 100);
942
+ if (args.activity !== undefined) this.state.activity = str(args.activity, 40) || this.state.activity;
943
+ if (args.location !== undefined) this.state.location = str(args.location, 40) || this.state.location;
944
+ if (args.sleeping !== undefined) {
945
+ this.state.sleeping = args.sleeping === true;
946
+ if (this.state.sleeping) this.state.activity = '睡觉';
947
+ }
948
+ this.state.updatedAt = now.toISOString();
949
+ this.save(true);
950
+ }
951
+ const stats = this.store.stats();
952
+ const dueAt = this.state.proactiveDueAt ? formatLocal(this.state.proactiveDueAt, this.tz()).slice(11) : '未安排';
953
+ const count = this.countToday();
954
+ return [
955
+ `精力 ${Math.round(this.state.energy)}/100,心情 ${moodLabel(this.state.mood)},正在${this.state.activity}${this.state.location ? `,在${this.state.location}` : ''}。`,
956
+ `下次主动约 ${dueAt};今天已主动 ${count}/${this.cfg().proactiveDailyCap || '∞'} 次。`,
957
+ `记忆 ${stats.total} 条,对话原文 ${this.raw.size} 行。`,
958
+ ].join('\n');
959
+ }
960
+
961
+ private handlePlan(args: Record<string, unknown>): string {
962
+ const action = String(args.action ?? 'list');
963
+ if (action === 'add') {
964
+ // 参数是平的(time/title/place);老调用方传 items 数组也认,一次最多 8 项
965
+ const list: unknown[] = Array.isArray(args.items)
966
+ ? args.items
967
+ : args.time || args.title
968
+ ? [{ time: args.time, title: args.title, place: args.place }]
969
+ : [];
970
+ let added = 0;
971
+ for (const raw of list.slice(0, 8)) {
972
+ const item = raw as Record<string, unknown>;
973
+ const time = str(item.time, 5);
974
+ const title = str(item.title, 40);
975
+ if (!time || !title || hmToMinutes(time) === null) continue;
976
+ this.plans.push({ id: randomUUID(), time, title, place: str(item.place, 30) || undefined });
977
+ added += 1;
978
+ }
979
+ this.plans.sort((a, b) => (hmToMinutes(a.time) ?? 0) - (hmToMinutes(b.time) ?? 0));
980
+ this.save(true);
981
+ return added ? `加了 ${added} 项,今天共 ${this.plans.filter((p) => !p.done).length} 项。` : '没有有效的项(time 用 HH:MM,title 不能空)。';
982
+ }
983
+ if (action === 'done') {
984
+ const id = str(args.id, 60);
985
+ const hit = this.plans.find((p) => p.id === id || p.id.startsWith(id));
986
+ if (!hit) return '没找到这一项。';
987
+ hit.done = true;
988
+ this.save(true);
989
+ return `「${hit.title}」标成做完了。`;
990
+ }
991
+ if (action === 'clear') {
992
+ this.plans = [];
993
+ this.save(true);
994
+ return '日程清空了。';
995
+ }
996
+ if (!this.plans.length) return '今天没有安排。';
997
+ return this.plans
998
+ .map((p) => `· ${p.id.slice(0, 8)} ${p.time} ${p.done ? '✓ ' : ''}${p.title}${p.place ? `(${p.place})` : ''}`)
999
+ .join('\n');
1000
+ }
1001
+
1002
+ // ---- 内部 ----
1003
+
1004
+ private importOnce(): void {
1005
+ const marker = join(this.dataDir, 'imported.json');
1006
+ if (existsSync(marker)) return;
1007
+ try {
1008
+ const report = importLegacy({ dataDir: this.ctx.dataDir, store: this.store });
1009
+ writeJson(marker, report);
1010
+ try {
1011
+ this.host?.log?.info?.('[memory-core] 旧记忆导入完成', report.sources);
1012
+ } catch {
1013
+ // ignore
1014
+ }
1015
+ } catch (error) {
1016
+ try {
1017
+ this.host?.log?.warn?.('[memory-core] 导入失败', String(error));
1018
+ } catch {
1019
+ // ignore
1020
+ }
1021
+ }
1022
+ }
1023
+
1024
+ private async tick(force: boolean): Promise<void> {
1025
+ if (this.ticking) return;
1026
+ if (this.stopped && !force) return;
1027
+ this.ticking = true;
1028
+ try {
1029
+ const now = new Date();
1030
+ advance(this.state, now, this.tz(), this.cfg());
1031
+ this.capture(
1032
+ Boolean(this.cfg().captureBackfill)
1033
+ && (Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION || !this.state.backfillDoneAt),
1034
+ );
1035
+ await this.maybeContext(now);
1036
+ await this.maybePreactivate(now);
1037
+ await this.maybeRemind(now);
1038
+ await this.maybeProactive(now);
1039
+ await this.maybeNightly(now);
1040
+ this.maybeChill(now);
1041
+ this.save();
1042
+ } catch (error) {
1043
+ try {
1044
+ this.host?.log?.warn?.('[memory-core] tick 失败', String(error));
1045
+ } catch {
1046
+ // ignore
1047
+ }
1048
+ } finally {
1049
+ this.ticking = false;
1050
+ }
1051
+ }
1052
+
1053
+ /**
1054
+ * 白名单正则。老版本默认值 `^(starpost\.private\.|qq\.|desktop-pet\.message)` 一个真实 key 都匹配不上
1055
+ * (实际是 `private:1940008084`、`desktop-pet.chat` 这种),读到这个旧默认就换成新的,免得用户
1056
+ * 明明没动过设置却一直录不到东西。
1057
+ */
1058
+ private senderRe(cfg: MemoryCoreConfig): RegExp {
1059
+ const raw = String(cfg.captureSenders ?? '').trim();
1060
+ const legacy = '^(starpost\\.private\\.|qq\\.|desktop-pet\\.message)';
1061
+ const pattern = !raw || raw === legacy ? MEMORY_CORE_DEFAULTS.captureSenders : raw;
1062
+ try {
1063
+ return new RegExp(pattern);
1064
+ } catch {
1065
+ return new RegExp(MEMORY_CORE_DEFAULTS.captureSenders);
1066
+ }
1067
+ }
1068
+
1069
+ /**
1070
+ * 从宿主的 external 事件流里捞对方说的话。
1071
+ *
1072
+ * 宿主 `range` 的语义有两处容易踩:`limit` 是**从区间末尾取**,不是从头取;
1073
+ * 只有不传 fromCursor 时才走「倒着凑最近 N 条」的快路径。所以拿
1074
+ * `{fromCursor, limit}` 当分页会一次跳到历史末尾——v1 就是这么把 2.5 万条
1075
+ * 外对话全跳过的。这里改用 toCursor 开窗,一窗一窗往前推。
1076
+ */
1077
+ private capture(backfill = false): void {
1078
+ const cfg = this.cfg();
1079
+ const host = this.host;
1080
+ if (!cfg.captureTurns || !host?.store) return;
1081
+ const re = this.senderRe(cfg);
1082
+ // 旧版水位是按错的 limit 语义推出来的,不可信:重放一遍
1083
+ if (backfill && Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION) {
1084
+ this.state.rawWatermark = 0;
1085
+ this.state.watermarkVersion = CAPTURE_WATERMARK_VERSION;
1086
+ this.state.backfillStartedAt = new Date().toISOString();
1087
+ this.state.backfillDoneAt = undefined;
1088
+ }
1089
+ // 区间上界:只取最后一条,读一个分片就够
1090
+ let head = 0;
1091
+ try {
1092
+ const last = host.store.range({ limit: 1 });
1093
+ head = last.length ? last[0].cursor : 0;
1094
+ } catch {
1095
+ return;
1096
+ }
1097
+ let from = Number(this.state.rawWatermark ?? 0) || 0;
1098
+ if (from > head) from = 0; // 宿主换过数据目录,cursor 从头开始
1099
+ const minLen = Math.max(1, Number(cfg.captureMinLength) || 4);
1100
+ const items: RawEntry[] = [];
1101
+ const keys = new Set<string>();
1102
+ let scanned = 0;
1103
+ // 实时每拍最多追 4 窗(2000 条)防积压;回放一次最多 400 窗(20 万条)
1104
+ const budget = backfill ? 400 : 4;
1105
+ let rounds = 0;
1106
+ let drained = from >= head;
1107
+ while (!drained && rounds < budget) {
1108
+ rounds += 1;
1109
+ const to = Math.min(from + CAPTURE_BATCH, head);
1110
+ let events: readonly { cursor: number; ts: string; senderKey?: string; text: string }[] = [];
1111
+ try {
1112
+ events = host.store.range({ fromCursor: from + 1, toCursor: to, origin: 'external' });
1113
+ } catch {
1114
+ break;
1115
+ }
1116
+ scanned += events.length;
1117
+ for (const e of events) {
1118
+ const key = e.senderKey ?? '';
1119
+ if (!re.test(key)) {
1120
+ // 记几个被挡掉的 key,出问题时一眼能看出是白名单还是正文的问题
1121
+ if (key && keys.size < 6) keys.add(key);
1122
+ continue;
1123
+ }
1124
+ const text = clip(extractUserText(e.text), 200);
1125
+ // 单字、纯表情、`[取消]` 这类系统回执、图片 blob 描述,都不进原文库
1126
+ if (!text || text.length < minLen) continue;
1127
+ if (/\[blob\b/i.test(text)) continue;
1128
+ if (/^\[(表情包|CQ:|图片)/.test(text)) continue;
1129
+ if (/^[\p{P}\p{S}\s]+$/u.test(text)) continue;
1130
+ if (/^\[[^\]]{0,12}\]$/.test(text.trim())) continue;
1131
+ items.push({ cursor: e.cursor, ts: e.ts, sender: maskSender(key).slice(0, 40), text });
1132
+ }
1133
+ // 按窗口边界推进,不按「最后一个匹配到的 cursor」:窗口里可能一条 external 都没有
1134
+ from = to;
1135
+ if (from >= head) drained = true;
1136
+ }
1137
+ this.raw.add(items);
1138
+ this.state.rawWatermark = from;
1139
+ if (backfill && drained) this.state.backfillDoneAt = new Date().toISOString();
1140
+ if (scanned || items.length) {
1141
+ this.state.captureDebug = {
1142
+ at: new Date().toISOString(),
1143
+ scanned,
1144
+ kept: items.length,
1145
+ keys: items.length ? [] : [...keys],
1146
+ ...(backfill && !drained ? { backfillFrom: from, backfillTo: head } : {}),
1147
+ };
1148
+ }
1149
+ }
1150
+
1151
+ private countToday(): number {
1152
+ const day = localParts(new Date(), this.tz()).date;
1153
+ return this.state.proactiveDay === day ? Number(this.state.proactiveCount ?? 0) : 0;
1154
+ }
1155
+
1156
+ private nextDue(now: Date): Date {
1157
+ const cfg = this.cfg();
1158
+ const gap = Math.max(5, Number(cfg.proactiveMinGapMin) || 100);
1159
+ const jitter = Math.max(0, Number(cfg.proactiveJitterMin) || 0);
1160
+ const extra = Math.round(Math.random() * jitter);
1161
+ return new Date(now.getTime() + (gap + extra) * 60_000);
1162
+ }
1163
+
1164
+ private dueHint(): string {
1165
+ if (!this.state.proactiveDueAt) return '未安排';
1166
+ return `下次约 ${formatLocal(this.state.proactiveDueAt, this.tz()).slice(11)}`;
1167
+ }
1168
+
1169
+ /** 最近一次「有人跟我说话」的时间;30 秒缓存,避免每拍扫事件库。 */
1170
+ private probeLastUser(now: number): number | null {
1171
+ if (now - this.lastUserProbe < 30_000) return this.lastUserAt;
1172
+ this.lastUserProbe = now;
1173
+ try {
1174
+ let re: RegExp;
1175
+ try {
1176
+ re = new RegExp(this.cfg().captureSenders || '^(starpost\\.private\\.|qq\\.)');
1177
+ } catch {
1178
+ re = /^(starpost\.private\.|qq\.)/;
1179
+ }
1180
+ const events = this.host?.store?.range({ origin: 'external', limit: 60 }) ?? [];
1181
+ let best = 0;
1182
+ let bestText = '';
1183
+ let bestCursor = -1;
1184
+ for (const e of events) {
1185
+ if (!re.test(e.senderKey ?? '')) continue;
1186
+ const t = Date.parse(e.ts);
1187
+ if (Number.isFinite(t) && t > best) {
1188
+ best = t;
1189
+ bestText = String(e.text ?? '');
1190
+ bestCursor = Number(e.cursor ?? -1);
1191
+ }
1192
+ }
1193
+ this.lastUserAt = best ? best : null;
1194
+ // 只留最近这一句:太旧的不算「刚说的」,预激活会误触发
1195
+ this.lastTurn = best && bestText.trim()
1196
+ ? { at: best, text: bestText, cursor: Number.isFinite(bestCursor) ? bestCursor : -1 }
1197
+ : null;
1198
+ } catch {
1199
+ this.lastUserAt = null;
1200
+ this.lastTurn = null;
1201
+ }
1202
+ return this.lastUserAt;
1203
+ }
1204
+
1205
+ private async push(
1206
+ type: string,
1207
+ text: string,
1208
+ trigger: 'piggyback' | 'flush' | 'preempt',
1209
+ tags?: readonly 'snapshot'[],
1210
+ ): Promise<boolean> {
1211
+ if (!this.host) return false;
1212
+ try {
1213
+ await this.host.pushEvent(
1214
+ {
1215
+ type,
1216
+ ts: new Date().toISOString(),
1217
+ source: this.id,
1218
+ origin: 'internal',
1219
+ text,
1220
+ ...(tags ? { tags } : {}),
1221
+ },
1222
+ { trigger },
1223
+ );
1224
+ return true;
1225
+ } catch (error) {
1226
+ try {
1227
+ this.host.log?.warn?.('[memory-core] 推送失败', String(error));
1228
+ } catch {
1229
+ // ignore
1230
+ }
1231
+ return false;
1232
+ }
1233
+ }
1234
+
1235
+ private async maybeContext(now: Date): Promise<void> {
1236
+ const everyMin = Number(this.cfg().contextEveryMin) || 0;
1237
+ if (everyMin <= 0) return;
1238
+ if (now.getTime() - this.lastContextAt < everyMin * 60_000) return;
1239
+ this.lastContextAt = now.getTime();
1240
+ const line = `(你现在:${this.state.activity}${this.state.location ? `,在${this.state.location}` : ''},精力 ${Math.round(this.state.energy)},心情${moodLabel(this.state.mood)})`;
1241
+ await this.push('mcore.context', line, 'piggyback', ['snapshot']);
1242
+ }
1243
+
1244
+ /**
1245
+ * 每轮预激活:拿对方刚说的这句当线索,把 2–3 条旧记忆推到眼前。
1246
+ * 这是「不靠模型自觉」的那一环——工具召回要模型主动想起来问,预激活不用。
1247
+ * 只给一行摘要,细节仍然要它自己调 mcore_recall 来要。
1248
+ */
1249
+ private async maybePreactivate(now: Date): Promise<void> {
1250
+ const cfg = this.cfg();
1251
+ const lines = this.preactivateCount();
1252
+ if (!lines || !cfg.memoryEnabled) return;
1253
+ const turn = this.lastTurn;
1254
+ if (!turn || turn.text.trim().length < 4) return;
1255
+ if (now.getTime() - turn.at > PRIME_FRESH_MS) return;
1256
+ // 有 cursor 就用 cursor,没有就退回时间戳——不能因为宿主不给 cursor 就永远不推
1257
+ const key = turn.cursor >= 0 ? `c${turn.cursor}` : `t${turn.at}`;
1258
+ if (this.primedFor === key) return;
1259
+
1260
+ // 软加权,不硬过滤:库里大头是 episode,砍掉就没什么可推的了
1261
+ const kindBias: Record<string, number> = { fact: 1.25, promise: 1.3, self: 1.15, note: 0.9, episode: 0.8 };
1262
+ const picked = rankCardsScored(this.store.recallable(), {
1263
+ // 太长的消息会把线索稀释掉,只取开头一段当查询
1264
+ query: turn.text.slice(0, 200),
1265
+ limit: 12,
1266
+ useAging: cfg.recallUseAging !== false,
1267
+ requireHit: true,
1268
+ minBigrams: 1,
1269
+ })
1270
+ .map((x) => ({ card: x.card, adj: x.score * (kindBias[x.card.kind] ?? 1) }))
1271
+ .sort((a, b) => b.adj - a.adj)
1272
+ .filter((x) => {
1273
+ const last = Date.parse(x.card.lastPrimedAt ?? '');
1274
+ return !Number.isFinite(last) || now.getTime() - last > PRIME_COOLDOWN_MS;
1275
+ })
1276
+ .slice(0, lines)
1277
+ .map((x) => x.card);
1278
+ if (!picked.length) return;
1279
+
1280
+ const tz = this.tz();
1281
+ const body = picked.map((c) => `· ${clip(c.text, 60)}(${formatLocal(c.createdAt, tz).slice(5, 10)})`).join('\n');
1282
+ const ok = await this.push(
1283
+ 'mcore.prime',
1284
+ `(以前记下的,不是对方刚说的:\n${body})`,
1285
+ 'piggyback',
1286
+ );
1287
+ if (!ok) return;
1288
+ this.primedFor = key;
1289
+ this.store.prime(picked.map((c) => c.id));
1290
+ }
1291
+
1292
+ private async maybeRemind(now: Date): Promise<void> {
1293
+ const due = this.store.duePromises(now.getTime(), this.promiseRepeat());
1294
+ if (!due.length) return;
1295
+ const lastUser = this.probeLastUser(now.getTime());
1296
+ if (this.cfg().requireRecentUserHours > 0) {
1297
+ const hours = Number(this.cfg().requireRecentUserHours);
1298
+ if (!lastUser || now.getTime() - lastUser > hours * 3_600_000) return;
1299
+ }
1300
+ const card = due[0];
1301
+ const ok = await this.push('mcore.due', `(答应过的事到点了:${clip(card.text, 80)})该提一句了。`, 'flush');
1302
+ if (!ok) return;
1303
+ this.store.update(card.id, { remindedAt: now.toISOString() });
1304
+ }
1305
+
1306
+ private async maybeProactive(now: Date): Promise<void> {
1307
+ const cfg = this.cfg();
1308
+ if (!cfg.proactiveEnabled) return;
1309
+ const p = localParts(now, this.tz());
1310
+ const due = this.state.proactiveDueAt ? Date.parse(this.state.proactiveDueAt) : 0;
1311
+ if (Number.isFinite(due) && due > now.getTime()) return;
1312
+
1313
+ const defer = (minutes: number) => {
1314
+ this.state.proactiveDueAt = new Date(now.getTime() + minutes * 60_000).toISOString();
1315
+ this.save();
1316
+ };
1317
+
1318
+ if (this.state.sleeping || inWindow(p.minutes, cfg.sleepStart, cfg.sleepEnd)) {
1319
+ defer(45);
1320
+ return;
1321
+ }
1322
+ if (inWindow(p.minutes, cfg.quietStart, cfg.quietEnd)) {
1323
+ defer(40);
1324
+ return;
1325
+ }
1326
+ const cap = Number(cfg.proactiveDailyCap) || 0;
1327
+ const count = this.countToday();
1328
+ if (cap > 0 && count >= cap) {
1329
+ defer(60);
1330
+ return;
1331
+ }
1332
+ const lastUser = this.probeLastUser(now.getTime());
1333
+ const recentHours = Number(cfg.requireRecentUserHours) || 0;
1334
+ if (recentHours > 0 && (!lastUser || now.getTime() - lastUser > recentHours * 3_600_000)) {
1335
+ // 没人在就不开口,等下一个小时再看;这条是省 token 的关键。
1336
+ defer(30);
1337
+ return;
1338
+ }
1339
+ const gate = Number(cfg.idleGateMin) || 0;
1340
+ if (lastUser && gate > 0 && now.getTime() - lastUser < gate * 60_000) {
1341
+ defer(Math.ceil((gate * 60_000 - (now.getTime() - lastUser)) / 60_000) + 1);
1342
+ return;
1343
+ }
1344
+
1345
+ const since = lastUser ? humanSpan(now.getTime() - lastUser) : null;
1346
+ const reason = this.reasonFor(now);
1347
+ const text = `(由头:${formatLocal(now, this.tz()).slice(11)},你${this.state.activity}`
1348
+ + `${this.state.location ? `,在${this.state.location}` : ''},精力 ${Math.round(this.state.energy)}`
1349
+ + `${since ? `;上次说话是 ${since} 前` : ''}。${reason})想主动跟对方说一句,别问「在吗」,直接说你此刻的事。`;
1350
+ const ok = await this.push('mcore.wake', text, 'flush');
1351
+ if (!ok) {
1352
+ defer(15);
1353
+ return;
1354
+ }
1355
+ this.state.proactiveDay = p.date;
1356
+ this.state.proactiveCount = count + 1;
1357
+ this.state.proactiveDueAt = this.nextDue(now).toISOString();
1358
+ this.save(true);
1359
+ }
1360
+
1361
+ private reasonFor(now: Date): string {
1362
+ const p = localParts(now, this.tz());
1363
+ const open = this.store.openPromises(3);
1364
+ if (open.length) return `上次没做完:${clip(open[0].text, 60)}。`;
1365
+ const upcoming = this.plans
1366
+ .filter((item) => !item.done && (hmToMinutes(item.time) ?? 0) >= p.minutes)
1367
+ .sort((a, b) => (hmToMinutes(a.time) ?? 0) - (hmToMinutes(b.time) ?? 0))[0];
1368
+ if (upcoming) return `你打算 ${upcoming.time} ${upcoming.title}。`;
1369
+ if (p.hour >= 22) return '天晚了,你想在睡前说一句。';
1370
+ if (p.hour >= 6 && p.hour < 9) return '刚醒,你想看看对方起了没。';
1371
+ if (this.state.energy < 35) return '你有点累,想说说话缓一缓。';
1372
+ if (this.state.mood < 40) return '你心情有点低落,想被陪一会儿。';
1373
+ return '你闲下来,忽然想到对方。';
1374
+ }
1375
+
1376
+ /**
1377
+ * 夜里把当天的原文收成一份材料,等下次开口再交付。
1378
+ * 原来是在凌晨三点直接推「去整理一下」——那个点没人说话,推送就躺在历史里没人接。
1379
+ */
1380
+ private async maybeNightly(now: Date): Promise<void> {
1381
+ const cfg = this.cfg();
1382
+ if (!cfg.nightlyConsolidate) return;
1383
+ const p = localParts(now, this.tz());
1384
+ // 过了设定的小时之后的第一笔心跳就跑,不要求正好整点:进程早上才起来也能补
1385
+ if (p.hour < (Number(cfg.nightlyHour) || 3)) return;
1386
+ if (this.state.lastNightlyDay === p.date) return;
1387
+
1388
+ const done = () => {
1389
+ this.state.lastNightlyDay = p.date;
1390
+ this.save(true);
1391
+ };
1392
+
1393
+ const since = now.getTime() - 86_400_000;
1394
+ const turns = this.raw.all().filter((e) => (Date.parse(e.ts) || 0) >= since);
1395
+ // 一天不到四句,没什么可整的
1396
+ if (turns.length < 4) return done();
1397
+ // 白天已经自己写了 3 条以上,说明模型记得,别再催
1398
+ const wroteToday = this.store
1399
+ .active()
1400
+ .filter((c) => c.source === 'tool' && formatLocal(c.createdAt, this.tz()).slice(0, 10) === p.date).length;
1401
+ if (wroteToday >= 3) return done();
1402
+
1403
+ const body = turns.slice(-40).map((e) => `· ${clip(e.text, 60)}`).join('\n');
1404
+ this.state.nightlyPending = { day: p.date, text: clip(body, 1100) };
1405
+ done();
1406
+ }
1407
+
1408
+ /** 有备好的整理材料,就趁这次开口交付(回合结束时调用)。 */
1409
+ private async deliverNightly(): Promise<void> {
1410
+ const pending = this.state.nightlyPending;
1411
+ if (!pending) return;
1412
+ const today = formatLocal(new Date(), this.tz()).slice(0, 10);
1413
+ const age = (Date.parse(`${today}T00:00:00Z`) - Date.parse(`${pending.day}T00:00:00Z`)) / 86_400_000;
1414
+ // 放太久就别再翻旧账了
1415
+ if (!Number.isFinite(age) || age > 2) {
1416
+ delete this.state.nightlyPending;
1417
+ this.save();
1418
+ return;
1419
+ }
1420
+ const ok = await this.push(
1421
+ 'mcore.nightly',
1422
+ `(昨天留下的这些,顺手整理一下:最多写 3 条;能写成 fact 就别写成 episode;有承诺就带 dueAt;库里已有的别重复。\n${pending.text})`,
1423
+ 'piggyback',
1424
+ );
1425
+ if (!ok) return;
1426
+ delete this.state.nightlyPending;
1427
+ this.save(true);
1428
+ }
1429
+
1430
+ /**
1431
+ * 每天判一次冷层:只标记,不删除。
1432
+ * 按「配额」沉而不是按绝对门槛一把沉——库才几十条的时候,一次全沉会让星图直接变黑。
1433
+ */
1434
+ private maybeChill(now: Date): void {
1435
+ const days = this.chillDays();
1436
+ if (!days) return;
1437
+ const today = formatLocal(now, this.tz()).slice(0, 10);
1438
+ if (this.state.lastChillDay === today) return;
1439
+ this.state.lastChillDay = today;
1440
+
1441
+ const live = this.store.active().length;
1442
+ const floor = Math.floor(live * 0.25);
1443
+ const cold = this.store.cold().length;
1444
+ if (cold >= floor) {
1445
+ this.save();
1446
+ return;
1447
+ }
1448
+ const room = Math.min(4, floor - cold);
1449
+ const ids = this.store
1450
+ .chillEligible(days, now.getTime())
1451
+ .slice(0, room)
1452
+ .map((c) => c.id);
1453
+ if (ids.length) this.store.chill(ids);
1454
+ this.save();
1455
+ }
1456
+ }