@jokab1074/rememberme 0.0.0-stage → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/ARCHITECTURE.md +787 -0
  2. package/LICENSE +201 -0
  3. package/README.en.md +441 -0
  4. package/README.md +459 -2
  5. package/dist/mcp/index.js +37287 -0
  6. package/package.json +67 -4
  7. package/server.json +38 -0
  8. package/settings.json.example +7 -0
  9. package/src/bigfive.ts +163 -0
  10. package/src/bootstrap.ts +104 -0
  11. package/src/classify.ts +186 -0
  12. package/src/compact.ts +225 -0
  13. package/src/context-file.ts +305 -0
  14. package/src/embedded-proactive.ts +214 -0
  15. package/src/evolution/access-tracker.ts +118 -0
  16. package/src/evolution/curator.ts +220 -0
  17. package/src/evolution/lifecycle.ts +175 -0
  18. package/src/feedback-detector.ts +177 -0
  19. package/src/i18n.ts +89 -0
  20. package/src/index.ts +1479 -0
  21. package/src/loop.ts +396 -0
  22. package/src/mcp/build.ts +64 -0
  23. package/src/mcp/config.ts +108 -0
  24. package/src/mcp/index.ts +66 -0
  25. package/src/mcp/instructions.ts +43 -0
  26. package/src/mcp/logger.ts +32 -0
  27. package/src/mcp/provider.ts +142 -0
  28. package/src/mcp/server.ts +52 -0
  29. package/src/mcp/tools/memory.ts +126 -0
  30. package/src/mcp/tools/profile.ts +67 -0
  31. package/src/mcp/tools/record-turn.ts +239 -0
  32. package/src/memory-extract.ts +390 -0
  33. package/src/memory.ts +790 -0
  34. package/src/persona-init.ts +153 -0
  35. package/src/persona-learner.ts +349 -0
  36. package/src/proactive.ts +557 -0
  37. package/src/profile.ts +1008 -0
  38. package/src/prompt.ts +288 -0
  39. package/src/provider.ts +292 -0
  40. package/src/reflection.ts +552 -0
  41. package/src/sessions.ts +140 -0
  42. package/src/timeline.ts +208 -0
  43. package/src/utils.ts +91 -0
  44. package/src/web.ts +624 -0
package/src/memory.ts ADDED
@@ -0,0 +1,790 @@
1
+ // src/memory.ts
2
+ // 情绪 + 事件 双主类记忆系统。
3
+ //
4
+ // 设计原则(来自用户反馈):
5
+ // - 模拟朋友面对用户时的思维方式
6
+ // - 记那些改变理解的瞬间,不是机械日志
7
+ // - 两大主类:
8
+ // * emotion —— 反复出现的情绪模式(必须有 ≥2 次证据)
9
+ // * event —— 对用户有情感意义的生活事件
10
+ // - 一小类:
11
+ // * reference —— 外部资源(医生/咨询师/家人联系方式)
12
+ // - 两类互相印证:事件解释情绪,情绪暗示事件
13
+ //
14
+ // 目录结构:
15
+ // data/memory/
16
+ // emotion/<slug>.md
17
+ // event/<slug>.md
18
+ // reference/<slug>.md
19
+ // MEMORY.md (索引)
20
+ //
21
+ // 与其他系统的边界:
22
+ // - profile.ts:用户身份背景(不是 emotion 也不是 event)
23
+ // - timeline.ts:当下情绪快照(单轮,不是模式)
24
+ // - reflection.ts:跨源洞察(meta-analysis)
25
+
26
+ import { readFile, readdir, writeFile, mkdir, stat } from "node:fs/promises";
27
+ import { join, basename } from "node:path";
28
+ import { estimateTokens } from "./utils.ts";
29
+
30
+ // =====================================================================
31
+ // Schema
32
+ // =====================================================================
33
+
34
+ /**
35
+ * 两主类 + 一小类。
36
+ */
37
+ export const MEMORY_TYPES = ["emotion", "event", "reference"] as const;
38
+
39
+ export type MemoryType = (typeof MEMORY_TYPES)[number];
40
+
41
+ /** 类型中文标签(显示用) */
42
+ export const MEMORY_TYPE_LABEL: Record<MemoryType, string> = {
43
+ emotion: "情绪模式",
44
+ event: "生活事件",
45
+ reference: "外部资源",
46
+ };
47
+
48
+ /** 类型子目录名 */
49
+ const TYPE_DIR: Record<MemoryType, string> = {
50
+ emotion: "emotion",
51
+ event: "event",
52
+ reference: "reference",
53
+ };
54
+
55
+ /**
56
+ * 情绪模式文件的 frontmatter 字段(解析后扁平化为 Record)。
57
+ * 关键字段:trigger, manifestation, evidence[], confidence
58
+ */
59
+ export type EmotionMemoryFields = {
60
+ /** 触发条件(用户原话片段或模式描述) */
61
+ trigger?: string;
62
+ /** 表现(情绪类型 + 强度描述 + 行为反应) */
63
+ manifestation?: string;
64
+ /** 证据数组(≥2 条;可以是日期-描述或用户原话片段) */
65
+ evidence?: string[];
66
+ /** 首次观察到(YYYY-MM-DD) */
67
+ first_observed?: string;
68
+ /** 最近观察到(YYYY-MM-DD) */
69
+ last_observed?: string;
70
+ /** high | medium | low */
71
+ confidence?: string;
72
+ /** 如何在对话中应用 */
73
+ how_to_apply?: string;
74
+ /** 关联的 event slug 列表 */
75
+ linked_events?: string[];
76
+ };
77
+
78
+ /**
79
+ * 事件文件的 frontmatter 字段。
80
+ */
81
+ export type EventMemoryFields = {
82
+ /** 发生时间(YYYY-MM-DD 或相对描述) */
83
+ occurred_at?: string;
84
+ /** 情感影响(持续悲伤/回避/...) */
85
+ emotional_impact?: string;
86
+ /** high | medium | low */
87
+ significance?: string;
88
+ /** 预期持续时间(4-8 weeks 等) */
89
+ duration_expectation?: string;
90
+ /** 如何在对话中应用 */
91
+ how_to_apply?: string;
92
+ /** 关联的 emotion slug 列表 */
93
+ linked_emotions?: string[];
94
+ };
95
+
96
+ /**
97
+ * 外部资源文件的 frontmatter 字段。
98
+ */
99
+ export type ReferenceMemoryFields = {
100
+ /** 联系方式或资源类型 */
101
+ resource_type?: string;
102
+ /** 用途说明 */
103
+ purpose?: string;
104
+ /** 紧急程度 */
105
+ urgency?: string;
106
+ };
107
+
108
+ export type MemoryFile = {
109
+ /** 文件路径(绝对) */
110
+ path: string;
111
+ /** 文件名(不含 .md 和子目录,如 "deadline-anxiety") */
112
+ filename: string;
113
+ /** 子目录(emotion/event/reference) */
114
+ subtype: MemoryType;
115
+ /** frontmatter name */
116
+ name: string;
117
+ /** frontmatter description */
118
+ description: string;
119
+ /** 正文(不含 frontmatter) */
120
+ body: string;
121
+ /** mtime ms */
122
+ mtimeMs: number;
123
+ /** 字节数 */
124
+ sizeBytes: number;
125
+ /** 原始 frontmatter 字段(供类型化访问) */
126
+ fields: EmotionMemoryFields & EventMemoryFields & ReferenceMemoryFields;
127
+ };
128
+
129
+ export type MemoryIndexEntry = {
130
+ /** 显示名称 */
131
+ title: string;
132
+ /** 子目录 */
133
+ subtype: MemoryType;
134
+ /** 文件名(不含子目录) */
135
+ filename: string;
136
+ /** 一句话钩子 */
137
+ hook: string;
138
+ };
139
+
140
+ export type AnyMemoryCandidate = {
141
+ type: MemoryType;
142
+ /** 文件名 slug(kebab-case) */
143
+ name: string;
144
+ /** 一句话描述 */
145
+ description: string;
146
+ /** 记忆正文 */
147
+ body: string;
148
+ /** LLM 置信度 */
149
+ confidence: number;
150
+ /** 类型化 frontmatter 字段(emotion 必填 trigger/manifestation/evidence;event 必填 occurred_at/emotional_impact) */
151
+ fields: EmotionMemoryFields & EventMemoryFields & ReferenceMemoryFields;
152
+ };
153
+
154
+ // MEMORY.md 索引的注入预算。
155
+ //
156
+ // 口径用 token 而不是字节:索引整份都会进 system prompt,真正的成本是 token。
157
+ // 而本项目索引以中文为主,CJK 的字节/token 比和英文差一个量级——同样一份
158
+ // 25KB 的索引,纯英文约 6k token,纯中文约 12k token。用字节做上限会在
159
+ // 中英混排下失真,token 预算才是稳定的口径。
160
+ const INDEX_TOKEN_BUDGET = 4_000;
161
+
162
+ // =====================================================================
163
+ // frontmatter 解析 / 序列化
164
+ // =====================================================================
165
+
166
+ /**
167
+ * 解析 frontmatter(复用 personality.ts 的逻辑)。
168
+ * 单行 `key: value` 格式。
169
+ *
170
+ * 对 array 字段(evidence / linked_events / linked_emotions)的特殊处理:
171
+ * - 支持 `key: [a, b, c]` 数组字面量
172
+ * - 支持 `key:\n - a\n - b` YAML 列表
173
+ */
174
+ function parseFrontmatter(
175
+ raw: string,
176
+ ): { frontmatter: Record<string, unknown>; body: string } {
177
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
178
+ if (!match) return { frontmatter: {}, body: raw };
179
+
180
+ const [, yamlBlock, body] = match;
181
+ const frontmatter: Record<string, unknown> = {};
182
+ const lines = yamlBlock.split("\n");
183
+
184
+ let i = 0;
185
+ while (i < lines.length) {
186
+ const line = lines[i];
187
+ const colonIdx = line.indexOf(":");
188
+ if (colonIdx === -1) {
189
+ i++;
190
+ continue;
191
+ }
192
+
193
+ const key = line.slice(0, colonIdx).trim();
194
+ let value: unknown = line.slice(colonIdx + 1).trim();
195
+
196
+ // 数组字面量:[a, b, c]
197
+ if (typeof value === "string" && value.startsWith("[") && value.endsWith("]")) {
198
+ try {
199
+ value = JSON.parse(value);
200
+ } catch {
201
+ const v = value as string;
202
+ value = v.slice(1, -1).split(",").map((s: string) => s.trim().replace(/^["']|["']$/g, ""));
203
+ }
204
+ frontmatter[key] = value;
205
+ i++;
206
+ continue;
207
+ }
208
+
209
+ // 去引号
210
+ if (
211
+ typeof value === "string" &&
212
+ ((value.startsWith('"') && value.endsWith('"')) ||
213
+ (value.startsWith("'") && value.endsWith("'")))
214
+ ) {
215
+ value = value.slice(1, -1);
216
+ }
217
+
218
+ // YAML 列表:key: \n - a \n - b
219
+ if (value === "") {
220
+ const items: string[] = [];
221
+ let j = i + 1;
222
+ while (j < lines.length && /^\s+-\s+/.test(lines[j])) {
223
+ items.push(lines[j].replace(/^\s+-\s+/, "").trim());
224
+ j++;
225
+ }
226
+ if (items.length > 0) {
227
+ frontmatter[key] = items;
228
+ i = j;
229
+ continue;
230
+ }
231
+ }
232
+
233
+ frontmatter[key] = value;
234
+ i++;
235
+ }
236
+
237
+ return { frontmatter, body: body.trim() };
238
+ }
239
+
240
+ /**
241
+ * 把 frontmatter 序列化为 YAML。
242
+ * array 字段用 `[a, b, c]` 内联格式(更紧凑,side-query 解析也方便)。
243
+ */
244
+ function buildFrontmatter(fields: Record<string, unknown>): string {
245
+ const lines: string[] = ["---"];
246
+ for (const [k, v] of Object.entries(fields)) {
247
+ if (v === undefined || v === null) continue;
248
+ if (Array.isArray(v)) {
249
+ if (v.length === 0) continue;
250
+ lines.push(`${k}: [${v.map((x) => JSON.stringify(String(x))).join(", ")}]`);
251
+ } else {
252
+ lines.push(`${k}: ${JSON.stringify(String(v))}`);
253
+ }
254
+ }
255
+ lines.push("---", "");
256
+ return lines.join("\n");
257
+ }
258
+
259
+ // =====================================================================
260
+ // 文件路径工具
261
+ // =====================================================================
262
+
263
+ /**
264
+ * 把文件名 slug 解析为子目录路径。
265
+ * 接受 "emotion/deadline-anxiety" 或纯 "deadline-anxiety"。
266
+ */
267
+ export function resolveMemoryPath(
268
+ memoryDir: string,
269
+ filename: string,
270
+ ): { subtype: MemoryType; path: string } | null {
271
+ // 形式 1: "emotion/foo"
272
+ const slashIdx = filename.indexOf("/");
273
+ if (slashIdx > 0) {
274
+ const maybeType = filename.slice(0, slashIdx);
275
+ if ((MEMORY_TYPES as readonly string[]).includes(maybeType)) {
276
+ return {
277
+ subtype: maybeType as MemoryType,
278
+ // 必须带 .md 后缀:scanMemory() 存的是带 .md 的绝对路径,
279
+ // 少了它 readMemoryFile() 里的 f.path === resolved.path 永远不成立
280
+ // (带子目录前缀的查找 100% 落空 —— 这条路径有回归测试覆盖)。
281
+ path: join(
282
+ memoryDir,
283
+ filename.endsWith(".md") ? filename : `${filename}.md`,
284
+ ),
285
+ };
286
+ }
287
+ }
288
+ return null;
289
+ }
290
+
291
+ /**
292
+ * 把 MemoryType 转为子目录前缀。
293
+ */
294
+ export function prefixByType(
295
+ subtype: MemoryType,
296
+ filename: string,
297
+ ): string {
298
+ return `${TYPE_DIR[subtype]}/${filename}`;
299
+ }
300
+
301
+ // =====================================================================
302
+ // 扫描 / 读取
303
+ // =====================================================================
304
+
305
+ /**
306
+ * 扫描记忆目录,按子目录分类返回所有 MemoryFile。
307
+ */
308
+ export async function scanMemory(memoryDir: string): Promise<MemoryFile[]> {
309
+ const all: MemoryFile[] = [];
310
+
311
+ for (const subtype of MEMORY_TYPES) {
312
+ const subdir = join(memoryDir, TYPE_DIR[subtype]);
313
+ let entries: string[];
314
+ try {
315
+ entries = await readdir(subdir);
316
+ } catch {
317
+ continue;
318
+ }
319
+ for (const filename of entries) {
320
+ if (!filename.endsWith(".md")) continue;
321
+ const path = join(subdir, filename);
322
+ try {
323
+ const raw = await readFile(path, "utf-8");
324
+ const { frontmatter, body } = parseFrontmatter(raw);
325
+ const stats = await stat(path);
326
+ all.push({
327
+ path,
328
+ filename: filename.replace(/\.md$/, ""),
329
+ subtype,
330
+ name: String(frontmatter.name ?? filename.replace(/\.md$/, "")),
331
+ description: String(frontmatter.description ?? ""),
332
+ body,
333
+ mtimeMs: stats.mtimeMs,
334
+ sizeBytes: stats.size,
335
+ fields: frontmatter as EmotionMemoryFields &
336
+ EventMemoryFields &
337
+ ReferenceMemoryFields,
338
+ });
339
+ } catch {
340
+ continue;
341
+ }
342
+ }
343
+ }
344
+
345
+ // 按 mtime 降序
346
+ all.sort((a, b) => b.mtimeMs - a.mtimeMs);
347
+ return all;
348
+ }
349
+
350
+ /**
351
+ * 按 subtype 过滤。
352
+ */
353
+ export async function readMemoriesByType(
354
+ memoryDir: string,
355
+ subtype: MemoryType,
356
+ ): Promise<MemoryFile[]> {
357
+ const all = await scanMemory(memoryDir);
358
+ return all.filter((f) => f.subtype === subtype);
359
+ }
360
+
361
+ /**
362
+ * 读单个记忆文件。filename 可以是 "emotion/foo" 或 "foo"。
363
+ */
364
+ export async function readMemoryFile(
365
+ memoryDir: string,
366
+ filename: string,
367
+ ): Promise<MemoryFile | null> {
368
+ const resolved = resolveMemoryPath(memoryDir, filename);
369
+ if (resolved) {
370
+ // 显式带子目录
371
+ const all = await scanMemory(memoryDir);
372
+ const found = all.find(
373
+ (f) => f.subtype === resolved.subtype && f.path === resolved.path,
374
+ );
375
+ return found ?? null;
376
+ }
377
+ // 纯文件名:全局搜
378
+ const all = await scanMemory(memoryDir);
379
+ return all.find((f) => f.filename === filename) ?? null;
380
+ }
381
+
382
+ /**
383
+ * 格式化 manifest(side-query 选择用)。
384
+ *
385
+ * 按类型分组而不是拉平成一串:召回 side-query 要判断的是"这次该看情绪模式还是
386
+ * 生活事件",分组后模型先选类型再选文件,比在混排列表里逐条比对更稳。
387
+ * 类型作为组标题出现,条目行里就不用再重复类型标签了。
388
+ */
389
+ export function formatManifest(files: MemoryFile[]): string {
390
+ if (files.length === 0) return "(没有记忆文件)";
391
+
392
+ const blocks: string[] = [];
393
+ for (const subtype of MEMORY_TYPES) {
394
+ const group = files.filter((f) => f.subtype === subtype);
395
+ if (group.length === 0) continue;
396
+
397
+ const rows = group.map((f) => {
398
+ const day = new Date(f.mtimeMs).toISOString().slice(0, 10);
399
+ const desc = f.description ? `:${f.description}` : "";
400
+ return ` ${f.filename}(${day})${desc}`;
401
+ });
402
+
403
+ blocks.push(
404
+ ` ${subtype} / ${MEMORY_TYPE_LABEL[subtype]}(${group.length} 条)\n` +
405
+ rows.join("\n"),
406
+ );
407
+ }
408
+
409
+ return blocks.join("\n\n");
410
+ }
411
+
412
+ /**
413
+ * 把索引裁剪到 token 预算内。
414
+ *
415
+ * 逐行累加、整行取舍,不做字符级切断:索引每行都是一条指向真实文件的指针,
416
+ * 从中间切开会留下半截路径,模型会拿着它去读不存在的文件。
417
+ */
418
+ function fitIndexToBudget(raw: string): {
419
+ text: string;
420
+ truncated: boolean;
421
+ droppedEntries: number;
422
+ } {
423
+ const lines = raw.split("\n");
424
+ const kept: string[] = [];
425
+ let used = 0;
426
+ let cutFrom = -1;
427
+
428
+ for (let i = 0; i < lines.length; i++) {
429
+ const cost = estimateTokens(lines[i]) + 1; // +1 约当换行本身的开销
430
+ if (used + cost > INDEX_TOKEN_BUDGET) {
431
+ cutFrom = i;
432
+ break;
433
+ }
434
+ kept.push(lines[i]);
435
+ used += cost;
436
+ }
437
+
438
+ if (cutFrom < 0) return { text: raw, truncated: false, droppedEntries: 0 };
439
+
440
+ const droppedEntries = lines
441
+ .slice(cutFrom)
442
+ .filter((l) => l.trimStart().startsWith("- ")).length;
443
+
444
+ return {
445
+ text: kept.join("\n").trimEnd(),
446
+ truncated: true,
447
+ droppedEntries,
448
+ };
449
+ }
450
+
451
+ /**
452
+ * 读 MEMORY.md 索引(裁剪到 token 预算内)。
453
+ */
454
+ export async function readMemoryIndex(memoryDir: string): Promise<string> {
455
+ const path = join(memoryDir, "MEMORY.md");
456
+
457
+ let raw: string;
458
+ try {
459
+ raw = await readFile(path, "utf-8");
460
+ } catch {
461
+ return "";
462
+ }
463
+
464
+ const { text, truncated, droppedEntries } = fitIndexToBudget(raw);
465
+ if (!truncated) return text;
466
+
467
+ const tail =
468
+ droppedEntries > 0 ? `末尾 ${droppedEntries} 条未载入` : "末尾内容未载入";
469
+ return (
470
+ text +
471
+ `\n\n> ⚠️ 索引已用满 ${INDEX_TOKEN_BUDGET} token 预算,${tail}。请合并或清理旧条目。`
472
+ );
473
+ }
474
+
475
+ // =====================================================================
476
+ // 写入
477
+ // =====================================================================
478
+
479
+ /**
480
+ * 写一个主题文件到对应子目录。
481
+ */
482
+ export async function writeMemoryFile(
483
+ memoryDir: string,
484
+ file: {
485
+ name: string;
486
+ description: string;
487
+ subtype: MemoryType;
488
+ body: string;
489
+ fields?: Partial<
490
+ EmotionMemoryFields & EventMemoryFields & ReferenceMemoryFields
491
+ >;
492
+ },
493
+ filename: string,
494
+ ): Promise<string> {
495
+ const subdir = join(memoryDir, TYPE_DIR[file.subtype]);
496
+ await mkdir(subdir, { recursive: true });
497
+ const path = join(subdir, filename);
498
+ const frontmatter = {
499
+ name: file.name,
500
+ description: file.description,
501
+ type: file.subtype,
502
+ ...(file.fields ?? {}),
503
+ };
504
+ const content = buildFrontmatter(frontmatter) + file.body.trim() + "\n";
505
+ await writeFile(path, content, "utf-8");
506
+ return path;
507
+ }
508
+
509
+ /**
510
+ * 追加一条索引到 MEMORY.md。
511
+ */
512
+ export async function appendIndexEntry(
513
+ memoryDir: string,
514
+ entry: MemoryIndexEntry,
515
+ ): Promise<void> {
516
+ const path = join(memoryDir, "MEMORY.md");
517
+ await mkdir(memoryDir, { recursive: true });
518
+
519
+ let current = "";
520
+ try {
521
+ current = await readFile(path, "utf-8");
522
+ } catch {
523
+ // 表头顺带说明行格式:模型自己往索引里补条目时照这个格式写。
524
+ current =
525
+ `# 记忆索引\n\n` +
526
+ `按类型组织:emotion(情绪模式)/ event(生活事件)/ reference(外部资源)。\n` +
527
+ `每行一条,竖线分隔:\`- 类型/文件名.md | 标题 | 一句话线索\`\n\n`;
528
+ }
529
+
530
+ // 路径放在行首:这是唯一机器要用的字段(hasIndexEntry 按它判重,
531
+ // 模型按它读文件),标题和线索都是给人和模型看的补充。
532
+ const line = `- ${entry.subtype}/${entry.filename}.md | ${entry.title} | ${entry.hook}`;
533
+ const updated = current.trimEnd() + "\n" + line + "\n";
534
+
535
+ const usedTokens = estimateTokens(updated);
536
+ if (usedTokens > INDEX_TOKEN_BUDGET * 0.8) {
537
+ console.warn(
538
+ `[memory] 索引已用 ${usedTokens}/${INDEX_TOKEN_BUDGET} token,接近预算,考虑合并旧条目`,
539
+ );
540
+ }
541
+
542
+ await writeFile(path, updated, "utf-8");
543
+ }
544
+
545
+ /**
546
+ * 检查 MEMORY.md 索引里是否已有某条目。
547
+ */
548
+ export async function hasIndexEntry(
549
+ memoryDir: string,
550
+ subtype: MemoryType,
551
+ filename: string,
552
+ ): Promise<boolean> {
553
+ const index = await readMemoryIndex(memoryDir);
554
+ return index.includes(`${subtype}/${filename}.md`);
555
+ }
556
+
557
+ // =====================================================================
558
+ // 追加 / 融合(v0.3.5 沿用)
559
+ // =====================================================================
560
+
561
+ /**
562
+ * 简单 tokenizer:英文按空格分词;中文按字符 1-gram + 2-gram。
563
+ */
564
+ function tokenize(text: string): Set<string> {
565
+ const tokens = new Set<string>();
566
+ if (!text) return tokens;
567
+ for (const word of text.split(/\s+/)) {
568
+ const w = word.replace(/[^a-z0-9一-鿿]/g, "");
569
+ if (w.length >= 2) tokens.add(w);
570
+ }
571
+ for (const ch of text) {
572
+ if (/[一-鿿]/.test(ch)) tokens.add(ch);
573
+ }
574
+ const chars = text.match(/[一-鿿]+/g)?.[0] ?? "";
575
+ for (let i = 0; i < chars.length - 1; i++) {
576
+ tokens.add(chars.slice(i, i + 2));
577
+ }
578
+ return tokens;
579
+ }
580
+
581
+ /**
582
+ * Jaccard 相似度:intersection / union。
583
+ */
584
+ function jaccard(a: Set<string>, b: Set<string>): number {
585
+ if (a.size === 0 && b.size === 0) return 0;
586
+ let intersection = 0;
587
+ for (const x of a) if (b.has(x)) intersection++;
588
+ const union = a.size + b.size - intersection;
589
+ return union > 0 ? intersection / union : 0;
590
+ }
591
+
592
+ /**
593
+ * 安全追加内容到已有记忆文件。
594
+ */
595
+ export async function appendToMemoryFile(
596
+ memoryDir: string,
597
+ subtype: MemoryType,
598
+ filename: string,
599
+ addition: string,
600
+ dateStr?: string,
601
+ ): Promise<{ path: string; content: string; appended: boolean }> {
602
+ const subdir = join(memoryDir, TYPE_DIR[subtype]);
603
+ const path = join(subdir, `${filename}.md`);
604
+ const raw = await readFile(path, "utf-8");
605
+ const { frontmatter, body } = parseFrontmatter(raw);
606
+
607
+ const normalizedAdd = addition.replace(/\s+/g, "");
608
+ const normalizedBody = body.replace(/\s+/g, "");
609
+ if (normalizedAdd.length >= 3 && normalizedBody.includes(normalizedAdd)) {
610
+ return { path, content: raw, appended: false };
611
+ }
612
+
613
+ const stamp = dateStr ?? new Date().toISOString().slice(0, 10);
614
+ const newBody = body.trim()
615
+ ? `${body.trim()}\n\n---\n\n**自动补充 (${stamp})**:\n\n${addition.trim()}`
616
+ : addition.trim();
617
+
618
+ const content = buildFrontmatter(frontmatter) + newBody + "\n";
619
+ await writeFile(path, content, "utf-8");
620
+ return { path, content, appended: true };
621
+ }
622
+
623
+ // =====================================================================
624
+ // 相似度查找
625
+ // =====================================================================
626
+
627
+ /**
628
+ * 在已有记忆里找最相似的(同 subtype 内匹配)。
629
+ */
630
+ export async function findSimilarMemory(
631
+ memoryDir: string,
632
+ candidate: {
633
+ subtype: MemoryType;
634
+ name: string;
635
+ description: string;
636
+ },
637
+ ): Promise<MemoryFile | null> {
638
+ const files = await readMemoriesByType(memoryDir, candidate.subtype);
639
+ if (files.length === 0) return null;
640
+
641
+ const candName = candidate.name.toLowerCase().trim();
642
+ const candDesc = candidate.description.toLowerCase().trim();
643
+
644
+ // 1. name 完全一致
645
+ const exactName = files.find(
646
+ (f) => f.name.toLowerCase().trim() === candName,
647
+ );
648
+ if (exactName) return exactName;
649
+
650
+ // 2. name Jaccard ≥ 0.5
651
+ const candNameTokens = tokenize(candName);
652
+ let bestNameScore = 0;
653
+ let bestNameMatch: MemoryFile | null = null;
654
+ for (const f of files) {
655
+ const fNameTokens = tokenize(f.name.toLowerCase());
656
+ const score = jaccard(candNameTokens, fNameTokens);
657
+ if (score > bestNameScore) {
658
+ bestNameScore = score;
659
+ bestNameMatch = f;
660
+ }
661
+ }
662
+ if (bestNameMatch && bestNameScore >= 0.5) return bestNameMatch;
663
+
664
+ // 3. description token Jaccard ≥ 0.3
665
+ const candDescTokens = tokenize(candDesc);
666
+ let bestDescScore = 0;
667
+ let bestDescMatch: MemoryFile | null = null;
668
+ for (const f of files) {
669
+ const fDescTokens = tokenize(f.description.toLowerCase());
670
+ const score = jaccard(candDescTokens, fDescTokens);
671
+ if (score > bestDescScore) {
672
+ bestDescScore = score;
673
+ bestDescMatch = f;
674
+ }
675
+ }
676
+ if (bestDescMatch && bestDescScore >= 0.3) return bestDescMatch;
677
+
678
+ return null;
679
+ }
680
+
681
+ // =====================================================================
682
+ // 跨印证(事件 ↔ 情绪)
683
+ // =====================================================================
684
+
685
+ /**
686
+ * 给定一个 event,找可能解释它的 emotion(基于时间 + 影响相似度)。
687
+ */
688
+ export async function findRelatedEmotions(
689
+ memoryDir: string,
690
+ eventFields: EventMemoryFields,
691
+ eventDate: string,
692
+ ): Promise<string[]> {
693
+ if (!eventDate || !eventFields.emotional_impact) return [];
694
+
695
+ const emotions = await readMemoriesByType(memoryDir, "emotion");
696
+ const impactTokens = tokenize(eventFields.emotional_impact.toLowerCase());
697
+ const eventTs = parseDate(eventDate);
698
+
699
+ const matches: { name: string; score: number }[] = [];
700
+
701
+ for (const e of emotions) {
702
+ const triggerTokens = tokenize(
703
+ (e.fields.trigger ?? "").toLowerCase(),
704
+ );
705
+ const manifestTokens = tokenize(
706
+ (e.fields.manifestation ?? "").toLowerCase(),
707
+ );
708
+
709
+ // 时间对齐:emotion 的 last_observed 在 event 附近
710
+ let timeScore = 0;
711
+ if (eventTs && e.fields.last_observed) {
712
+ const lastTs = parseDate(e.fields.last_observed);
713
+ if (lastTs) {
714
+ const days = Math.abs(eventTs - lastTs) / (24 * 60 * 60 * 1000);
715
+ timeScore = days <= 14 ? 0.5 : days <= 30 ? 0.2 : 0;
716
+ }
717
+ }
718
+
719
+ // 内容对齐:trigger 或 manifestation 与 emotional_impact 相似
720
+ const contentScore =
721
+ Math.max(
722
+ jaccard(impactTokens, triggerTokens),
723
+ jaccard(impactTokens, manifestTokens),
724
+ ) * 0.5;
725
+
726
+ const score = timeScore + contentScore;
727
+ if (score >= 0.4) matches.push({ name: e.filename, score });
728
+ }
729
+
730
+ matches.sort((a, b) => b.score - a.score);
731
+ return matches.slice(0, 3).map((m) => m.name);
732
+ }
733
+
734
+ /**
735
+ * 给定一个 emotion,找可能的事件(基于时间范围 + trigger 相似)。
736
+ */
737
+ export async function findRelatedEvents(
738
+ memoryDir: string,
739
+ emotionFields: EmotionMemoryFields,
740
+ ): Promise<string[]> {
741
+ const events = await readMemoriesByType(memoryDir, "event");
742
+ if (events.length === 0) return [];
743
+
744
+ const triggerTokens = tokenize((emotionFields.trigger ?? "").toLowerCase());
745
+ const firstTs = parseDate(emotionFields.first_observed ?? "");
746
+ const lastTs = parseDate(emotionFields.last_observed ?? "");
747
+
748
+ const matches: { name: string; score: number }[] = [];
749
+
750
+ for (const ev of events) {
751
+ const evTs = parseDate(ev.fields.occurred_at ?? "");
752
+ let timeScore = 0;
753
+ if (evTs && (firstTs || lastTs)) {
754
+ const start = firstTs ?? lastTs!;
755
+ const end = lastTs ?? firstTs!;
756
+ const lo = Math.min(start, end);
757
+ const hi = Math.max(start, end);
758
+ if (evTs >= lo - 30 * 86400000 && evTs <= hi + 14 * 86400000) {
759
+ timeScore = 0.5;
760
+ }
761
+ }
762
+
763
+ const impactTokens = tokenize(
764
+ (ev.fields.emotional_impact ?? "").toLowerCase(),
765
+ );
766
+ const manifestTokens = tokenize(
767
+ (emotionFields.manifestation ?? "").toLowerCase(),
768
+ );
769
+ const contentScore = jaccard(impactTokens, manifestTokens) * 0.5;
770
+
771
+ const score = timeScore + contentScore;
772
+ if (score >= 0.3) matches.push({ name: ev.filename, score });
773
+ }
774
+
775
+ matches.sort((a, b) => b.score - a.score);
776
+ return matches.slice(0, 3).map((m) => m.name);
777
+ }
778
+
779
+ /**
780
+ * 简易日期解析:YYYY-MM-DD 优先;"约 3 天前" / "上周" 等返回 null。
781
+ */
782
+ function parseDate(s: string): number | null {
783
+ if (!s) return null;
784
+ const m = s.match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
785
+ if (m) {
786
+ const [, y, mo, d] = m;
787
+ return new Date(Number(y), Number(mo) - 1, Number(d)).getTime();
788
+ }
789
+ return null;
790
+ }