@jokab1074/rememberme 0.22.0 → 0.22.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/profile.ts CHANGED
@@ -1,1008 +1,1095 @@
1
- // src/profile.ts
2
- // 用户画像系统(Profile)。
3
- //
4
- // v0.21 重构:抽象 + 动态分析用户人格
5
- //
6
- // profile 不再是 memory 堆积的目录视图,而是**对 memory/learner/timeline 的抽象沉淀**。
7
- //
8
- // 两个 OCEAN 严格区分:
9
- // - **session BigFivePersona.ocean**(`data/personality/{sessionId}.json`,用户 init 时 LLM 翻译的)
10
- // → 决定 LLM **该怎么说话**(行为层 / 对话风格)
11
- // - **profile ocean**(`data/profile/PROFILE.md` frontmatter,从历史/memory/learner 推算)
12
- // → 帮 LLM **理解用户是什么样的人**(认知层 / 用户画像)
13
- //
14
- // 两者独立并存,profile ocean 不替代 persona。
15
- //
16
- // 段 1/2/6 由 LLM 抽取更新(基本信息、沟通风格、近期变化)
17
- // 段 3/4/5 由 LLM 摘要更新(关注议题、已知偏好、长期情绪基线)—— 不再是机械列表
18
- // 同时 push profile.ocean 到 frontmatter
19
-
20
- import { readFile, writeFile, mkdir } from "node:fs/promises";
21
- import { existsSync } from "node:fs";
22
- import type { ModelProvider } from "./provider.ts";
23
- import type { LearnerState } from "./persona-learner.ts";
24
- import { loadLearner } from "./persona-learner.ts";
25
- import { scanMemory, type MemoryFile } from "./memory.ts";
26
- import type { Timeline } from "./timeline.ts";
27
- import {
28
- parseContextFile,
29
- serializeContextFile,
30
- PROFILE_SECTIONS as CONTEXT_PROFILE_SECTIONS,
31
- PROFILE_FILENAME,
32
- getProfilePath,
33
- type ProfileSection,
34
- type ContextFileMeta,
35
- } from "./context-file.ts";
36
- import { oceanHint } from "./bigfive.ts";
37
-
38
- // =====================================================================
39
- // 类型定义
40
- // =====================================================================
41
-
42
- export const PROFILE_SECTIONS = CONTEXT_PROFILE_SECTIONS;
43
- export { PROFILE_FILENAME, getProfilePath };
44
- export type { ProfileSection };
45
-
46
- /**
47
- * 动态推算的"用户是什么样的人"。
48
- *
49
- * 注意:这是**认知层**,跟 session BigFivePersona.ocean(行为层)独立。
50
- * profile.ocean 帮 LLM 理解用户;session persona 告诉 LLM 怎么说话。
51
- */
52
- export type ProfileOcean = {
53
- openness: number;
54
- conscientiousness: number;
55
- extraversion: number;
56
- agreeableness: number;
57
- neuroticism: number;
58
- /** 推算依据摘要(哪段 history / memory 导致这个数值) */
59
- basis: string;
60
- };
61
-
62
- export type Profile = {
63
- /** 6 段内容(key = 段落名,value = 段落正文) */
64
- sections: Record<ProfileSection, string>;
65
- /** 动态推算的"用户是什么样的人" */
66
- ocean: ProfileOcean | null;
67
- /** 最后一次 OCEAN 推算时间(ms) */
68
- oceanUpdatedAt: number;
69
- /** 文件路径 */
70
- path: string;
71
- /** 最后更新时间(ms) */
72
- updatedAt: number;
73
- /** 是否是首次初始化 */
74
- initialized: boolean;
75
- /** frontmatter 元数据 */
76
- meta: ContextFileMeta;
77
- };
78
-
79
- // =====================================================================
80
- // 默认模板
81
- // =====================================================================
82
-
83
- const DEFAULT_META: ContextFileMeta = {
84
- name: "用户画像",
85
- version: "0.7",
86
- description: "用户长期画像,v0.21 抽象 + 动态推算",
87
- author: "rememberme",
88
- kind: "profile",
89
- };
90
-
91
- const DEFAULT_BODY = `> 自动从对话中累积维护。每次对话开始前注入到 system prompt。
92
- > 段 1/2 由 LLM 抽取,段 3/4/5/6 由 LLM 摘要(v0.21 改造)。
93
- > frontmatter 的 ocean_* 字段是动态推算的"用户认知画像",与 session persona 独立。
94
-
95
- ## 1. 基本信息
96
- - 昵称:未知
97
- - 性别:未知
98
- - 年龄段:未知
99
- - 职业:未知
100
- - 所在地:未知
101
-
102
- ## 2. 沟通风格
103
- - (暂无——等用户表现出偏好后再填)
104
-
105
- ## 3. 关注议题
106
- - (暂无——从 memory/event 抽象汇总)
107
-
108
- ## 4. 已知偏好与禁忌
109
- - (暂无——从反馈学习抽象汇总)
110
-
111
- ## 5. 长期情绪基线
112
- - (暂无——从 memory/emotion 抽象汇总)
113
-
114
- ## 6. 近期变化
115
- - (暂无——从 timeline 抽象汇总)`;
116
-
117
- // =====================================================================
118
- // 加载 / 保存
119
- // =====================================================================
120
-
121
- /**
122
- * 从 frontmatter 解析 ProfileOcean 字段。
123
- */
124
- function readOceanFromMeta(meta: ContextFileMeta): ProfileOcean | null {
125
- const get = (key: string): string | undefined => {
126
- const v = (meta as Record<string, unknown>)[key];
127
- return typeof v === "string" ? v : undefined;
128
- };
129
- const o = meta as Record<string, unknown>;
130
- const openness = Number(o.ocean_openness);
131
- const conscientiousness = Number(o.ocean_conscientiousness);
132
- const extraversion = Number(o.ocean_extraversion);
133
- const agreeableness = Number(o.ocean_agreeableness);
134
- const neuroticism = Number(o.ocean_neuroticism);
135
- if (
136
- [openness, conscientiousness, extraversion, agreeableness, neuroticism].some(
137
- (n) => Number.isNaN(n),
138
- )
139
- ) {
140
- return null;
141
- }
142
- return {
143
- openness,
144
- conscientiousness,
145
- extraversion,
146
- agreeableness,
147
- neuroticism,
148
- basis: get("ocean_basis") ?? "",
149
- };
150
- }
151
-
152
- /**
153
- * 把 ProfileOcean 写入 meta。
154
- */
155
- function writeOceanToMeta(
156
- meta: ContextFileMeta,
157
- ocean: ProfileOcean,
158
- oceanUpdatedAt: number,
159
- ): void {
160
- const m = meta as Record<string, unknown>;
161
- m.ocean_openness = ocean.openness.toFixed(2);
162
- m.ocean_conscientiousness = ocean.conscientiousness.toFixed(2);
163
- m.ocean_extraversion = ocean.extraversion.toFixed(2);
164
- m.ocean_agreeableness = ocean.agreeableness.toFixed(2);
165
- m.ocean_neuroticism = ocean.neuroticism.toFixed(2);
166
- m.ocean_basis = ocean.basis;
167
- m.ocean_updated_at = new Date(oceanUpdatedAt).toISOString();
168
- }
169
-
170
- /**
171
- * 加载 profile,自动从其他数据源同步段 3/4/5/6 + 推算 ocean。
172
- *
173
- * @param dataDir data 根目录
174
- * @param options.userId 用户 ID(用于加载 learner state)
175
- * @param options.memoryDir memory 目录
176
- * @param options.timeline Timeline 实例
177
- * @param options.provider LLM provider(用于 v0.21 摘要推算;不传则用机械列表 fallback)
178
- */
179
- export async function loadProfile(
180
- dataDir: string,
181
- options?: {
182
- userId?: string;
183
- memoryDir?: string;
184
- timeline?: Timeline;
185
- provider?: ModelProvider;
186
- },
187
- ): Promise<Profile> {
188
- const path = getProfilePath(dataDir);
189
- const dir = path.replace(/[/\\][^/\\]+$/, "");
190
-
191
- if (!existsSync(path)) {
192
- await mkdir(dir, { recursive: true });
193
- const initialContent = serializeContextFile(DEFAULT_META, DEFAULT_BODY);
194
- await writeFile(path, initialContent, "utf-8");
195
- const ctx = parseContextFile(initialContent, path);
196
- const profile: Profile = {
197
- sections: ctx.structuredSections ?? emptySections(),
198
- ocean: readOceanFromMeta(ctx.meta),
199
- oceanUpdatedAt: 0,
200
- path,
201
- updatedAt: Date.now(),
202
- initialized: true,
203
- meta: ctx.meta,
204
- };
205
- await syncFromSources(profile, dataDir, options);
206
- await saveProfile(profile);
207
- return profile;
208
- }
209
-
210
- const raw = await readFile(path, "utf-8");
211
- const ctx = parseContextFile(raw, path);
212
- const stats = await import("node:fs/promises").then((fs) => fs.stat(path));
213
- const profile: Profile = {
214
- sections: ctx.structuredSections ?? emptySections(),
215
- ocean: readOceanFromMeta(ctx.meta),
216
- oceanUpdatedAt:
217
- (ctx.meta as Record<string, unknown>).ocean_updated_at &&
218
- typeof (ctx.meta as Record<string, unknown>).ocean_updated_at === "string"
219
- ? new Date(
220
- (ctx.meta as Record<string, unknown>).ocean_updated_at as string,
221
- ).getTime()
222
- : 0,
223
- path,
224
- updatedAt: stats.mtimeMs,
225
- initialized: false,
226
- meta: ctx.meta,
227
- };
228
- await syncFromSources(profile, dataDir, options);
229
- await saveProfile(profile);
230
- return profile;
231
- }
232
-
233
- /**
234
- * 把 profile 写入磁盘。
235
- */
236
- export async function saveProfile(profile: Profile): Promise<void> {
237
- // 把 ocean 写回 meta(ocean_* 字段会被 serializeContextFile 之外的逻辑处理)
238
- if (profile.ocean) {
239
- writeOceanToMeta(profile.meta, profile.ocean, profile.oceanUpdatedAt);
240
- }
241
- const body = serializeProfileBody(profile.sections);
242
- const content = serializeContextFile(profile.meta, body);
243
- // 在 serializeContextFile 之后再附加 ocean_* 字段(因为它只处理固定 5 个字段)
244
- if (profile.ocean) {
245
- const oceanLines: string[] = [];
246
- const o = profile.ocean;
247
- oceanLines.push(`- **ocean_openness**:${o.openness.toFixed(2)}`);
248
- oceanLines.push(`- **ocean_conscientiousness**:${o.conscientiousness.toFixed(2)}`);
249
- oceanLines.push(`- **ocean_extraversion**:${o.extraversion.toFixed(2)}`);
250
- oceanLines.push(`- **ocean_agreeableness**:${o.agreeableness.toFixed(2)}`);
251
- oceanLines.push(`- **ocean_neuroticism**:${o.neuroticism.toFixed(2)}`);
252
- oceanLines.push(`- **ocean_basis**:${o.basis}`);
253
- oceanLines.push(`- **ocean_updated_at**:${new Date(profile.oceanUpdatedAt).toISOString()}`);
254
- // 在 body 之后插入(frontmatter 之后,body 之前)
255
- const idx = content.indexOf("\n\n# 用户画像(Profile)");
256
- if (idx > 0) {
257
- const final = content.slice(0, idx) + "\n" + oceanLines.join("\n") + content.slice(idx);
258
- await writeFile(profile.path, final, "utf-8");
259
- } else {
260
- await writeFile(profile.path, content, "utf-8");
261
- }
262
- } else {
263
- await writeFile(profile.path, content, "utf-8");
264
- }
265
- profile.updatedAt = Date.now();
266
- }
267
-
268
- function serializeProfileBody(
269
- sections: Record<ProfileSection, string>,
270
- ): string {
271
- const lines: string[] = [
272
- "# 用户画像(Profile)",
273
- "",
274
- "> 自动从对话中累积维护。每次对话开始前注入到 system prompt。",
275
- "> 段 1/2 由 LLM 抽取,段 3/4/5/6 由 LLM 摘要(v0.21 改造)。",
276
- "> frontmatter 的 ocean_* 字段是动态推算的『用户认知画像』,与 session persona 独立。",
277
- "",
278
- ];
279
- PROFILE_SECTIONS.forEach((name, i) => {
280
- const content = sections[name]?.trim() || "(暂无)";
281
- lines.push(`## ${i + 1}. ${name}`);
282
- lines.push(content);
283
- lines.push("");
284
- });
285
- return lines.join("\n");
286
- }
287
-
288
- function emptySections(): Record<ProfileSection, string> {
289
- const out = {} as Record<ProfileSection, string>;
290
- for (const s of PROFILE_SECTIONS) out[s] = "";
291
- return out;
292
- }
293
-
294
- function joinSafe(parent: string, child: string): string {
295
- return parent.endsWith("/") || parent.endsWith("\\")
296
- ? parent + child
297
- : parent + "/" + child;
298
- }
299
-
300
- // =====================================================================
301
- // v0.21 摘要:调 LLM 把所有数据消化成结构化输出
302
- // =====================================================================
303
-
304
- /**
305
- * summarizeForProfile 输入。
306
- */
307
- export type ProfileSources = {
308
- memories: MemoryFile[];
309
- learner: LearnerState;
310
- timelineSummary: string;
311
- };
312
-
313
- /**
314
- * summarizeForProfile 输出(LLM JSON)。
315
- */
316
- export type ProfileSummary = {
317
- ocean: ProfileOcean | null;
318
- abstractTopics: string[];
319
- persistentPreferences: string[];
320
- persistentEmotionPatterns: string[];
321
- recentChanges: string[];
322
- };
323
-
324
- const SUMMARY_SYSTEM_PROMPT = `你是用户认知分析师。下面是用户的所有历史记忆、反馈学习观察、近期情绪时间线。
325
-
326
- **任务**:抽象、归并、聚类出"用户是什么样的人",**不是** LLM 该怎么说话。
327
-
328
- **v0.21 输出严格按以下 JSON**(不要 Markdown 代码块):
329
-
330
- {
331
- "ocean": {
332
- "openness": 0.0-1.0,
333
- "conscientiousness": 0.0-1.0,
334
- "extraversion": 0.0-1.0,
335
- "agreeableness": 0.0-1.0,
336
- "neuroticism": 0.0-1.0,
337
- "basis": "推算依据(哪段对话 / 哪些 memory 导致这个数值,1-2 句话)"
338
- },
339
- "abstractTopics": [
340
- "主题级抽象议题 1(不是文件名,是归纳出的主题)",
341
- "主题级抽象议题 2"
342
- ],
343
- "persistentPreferences": [
344
- "持久偏好 1(从反馈学习观察归纳,不是单条原话)",
345
- "持久偏好 2"
346
- ],
347
- "persistentEmotionPatterns": [
348
- "情绪模式名 → 触发:xxx → 表现:xxx",
349
- "情绪模式名 → 触发:xxx → 表现:xxx"
350
- ],
351
- "recentChanges": [
352
- "最近变化趋势 1(不超过 7 天)",
353
- "最近变化趋势 2"
354
- ]
355
- }
356
-
357
- **严格要求**:
358
-
359
- 1. **抽象,不堆积**:
360
- - 10 条 emotion memory → 总结为 2-3 个情绪模式(不列文件名)
361
- - 20 条 learner pattern → 总结为 3-5 条持久偏好(去重、合并、归纳)
362
- - 5 条 event memory → 总结为 2-4 个议题主题
363
-
364
- 2. **OCEAN 数值要基于实际行为信号**:
365
- - 用户反复提到哲学/文学/跨领域话题 → openness 高
366
- - 用户对话题回避、转移 → 可能在某些维度低
367
- - 不猜测;信号不足就 0.5(中性)
368
-
369
- 3. **basis 必须引用证据**:不要凭空给数字,说"基于 X、Y"
370
-
371
- 4. **空数组合法**:没有信号时该段就是空数组(不要硬凑)
372
-
373
- 5. **不要重复**同样的事情到不同段
374
-
375
- 下面是用户的全部数据:
376
-
377
- === Memory 文件清单 ===
378
- {memoryList}
379
-
380
- === Memory 文件正文(仅情绪模式 + 生活事件)===
381
- {memoryBodies}
382
-
383
- === 反馈学习观察 ===
384
- {learnerPatterns}
385
-
386
- === 近期情绪时间线 ===
387
- {timelineSummary}`;
388
-
389
- /**
390
- * 调 LLM 把所有数据源消化成结构化摘要。
391
- * 失败容错:返回空摘要。
392
- */
393
- export async function summarizeForProfile(
394
- provider: ModelProvider,
395
- sources: ProfileSources,
396
- ): Promise<ProfileSummary> {
397
- const empty: ProfileSummary = {
398
- ocean: null,
399
- abstractTopics: [],
400
- persistentPreferences: [],
401
- persistentEmotionPatterns: [],
402
- recentChanges: [],
403
- };
404
-
405
- try {
406
- const memList = sources.memories
407
- .map((m) => `[${m.subtype}] ${m.name} — ${m.description || "(无描述)"}`)
408
- .join("\n");
409
- const memBodies = sources.memories
410
- .filter((m) => m.subtype === "emotion" || m.subtype === "event")
411
- .map(
412
- (m) =>
413
- `### [${m.subtype}] ${m.name}\ntrigger: ${(m.fields as Record<string, unknown>).trigger ?? ""}\nmanifestation: ${(m.fields as Record<string, unknown>).manifestation ?? ""}\nemotional_impact: ${(m.fields as Record<string, unknown>).emotional_impact ?? ""}\nbody: ${m.body.slice(0, 300)}`,
414
- )
415
- .join("\n\n");
416
- const learnerPatterns = [
417
- ...((sources.learner.positivePatterns ?? []).slice(-15).map((p) => `+ ${p}`)),
418
- ...((sources.learner.negativePatterns ?? []).slice(-15).map((p) => `- ${p}`)),
419
- ].join("\n");
420
-
421
- const userPrompt = SUMMARY_SYSTEM_PROMPT
422
- .replace("{memoryList}", memList || "(无)")
423
- .replace("{memoryBodies}", memBodies || "(无)")
424
- .replace("{learnerPatterns}", learnerPatterns || "(无)")
425
- .replace("{timelineSummary}", sources.timelineSummary || "(无)");
426
-
427
- const raw = await provider.complete({
428
- model: provider.model,
429
- params: {
430
- system: "你是用户认知分析师,输出严格 JSON。",
431
- messages: [{ role: "user", content: userPrompt }],
432
- maxTokens: 1500,
433
- temperature: 0.3,
434
- },
435
- });
436
-
437
- const cleaned = raw
438
- .trim()
439
- .replace(/^```(?:json)?\n?/i, "")
440
- .replace(/\n?```\s*$/, "")
441
- .trim();
442
-
443
- if (process.env.EC_DEBUG_PROFILE) {
444
- console.log("[profile.summarize] cleaned:", cleaned.slice(0, 200));
445
- }
446
-
447
- const match = cleaned.match(/\{[\s\S]*\}/);
448
- if (!match) return empty;
449
-
450
- const parsed = JSON.parse(match[0]);
451
-
452
- // 校验 OCEAN
453
- let ocean: ProfileOcean | null = null;
454
- const o = parsed.ocean;
455
- if (o && typeof o === "object") {
456
- const vals = [o.openness, o.conscientiousness, o.extraversion, o.agreeableness, o.neuroticism];
457
- if (vals.every((v) => typeof v === "number" && v >= 0 && v <= 1)) {
458
- ocean = {
459
- openness: vals[0],
460
- conscientiousness: vals[1],
461
- extraversion: vals[2],
462
- agreeableness: vals[3],
463
- neuroticism: vals[4],
464
- basis: typeof o.basis === "string" ? o.basis.slice(0, 300) : "",
465
- };
466
- }
467
- }
468
-
469
- return {
470
- ocean,
471
- abstractTopics: Array.isArray(parsed.abstractTopics)
472
- ? parsed.abstractTopics.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
473
- : [],
474
- persistentPreferences: Array.isArray(parsed.persistentPreferences)
475
- ? parsed.persistentPreferences.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
476
- : [],
477
- persistentEmotionPatterns: Array.isArray(parsed.persistentEmotionPatterns)
478
- ? parsed.persistentEmotionPatterns.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
479
- : [],
480
- recentChanges: Array.isArray(parsed.recentChanges)
481
- ? parsed.recentChanges.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
482
- : [],
483
- };
484
- } catch {
485
- return empty;
486
- }
487
- }
488
-
489
- // =====================================================================
490
- // 同步:从其他数据源填充段 3/4/5/6 + 推算 profile.ocean
491
- // =====================================================================
492
-
493
- /**
494
- * v0.21:从数据源同步。
495
- * - 有 provider:调 summarizeForProfile 摘要(推荐路径)
496
- * - 无 provider:fallback 到 v0.20 机械列表
497
- */
498
- export async function syncFromSources(
499
- profile: Profile,
500
- dataDir: string,
501
- options?: {
502
- userId?: string;
503
- memoryDir?: string;
504
- timeline?: Timeline;
505
- provider?: ModelProvider;
506
- },
507
- ): Promise<void> {
508
- const memoryDir = options?.memoryDir ?? joinSafe(dataDir, "memory");
509
- const userId = options?.userId ?? "default";
510
- const learner = loadLearner(dataDir, userId);
511
- const memories = await scanMemory(memoryDir);
512
- const timelineSummary = options?.timeline
513
- ? await options.timeline.renderSummary(10)
514
- : "";
515
-
516
- // v0.21 推荐路径:调 LLM 摘要
517
- if (options?.provider) {
518
- try {
519
- const summary = await summarizeForProfile(options.provider, {
520
- memories,
521
- learner,
522
- timelineSummary,
523
- });
524
-
525
- if (summary.ocean) {
526
- profile.ocean = summary.ocean;
527
- profile.oceanUpdatedAt = Date.now();
528
- }
529
- if (summary.abstractTopics.length > 0) {
530
- profile.sections["关注议题"] = summary.abstractTopics
531
- .map((t) => `- ${t}`)
532
- .join("\n");
533
- }
534
- if (summary.persistentPreferences.length > 0) {
535
- profile.sections["已知偏好与禁忌"] = [
536
- "**用户持久偏好(从反馈学习总结):**",
537
- ...summary.persistentPreferences.map((p) => `- ${p}`),
538
- ].join("\n");
539
- }
540
- if (summary.persistentEmotionPatterns.length > 0) {
541
- profile.sections["长期情绪基线"] = summary.persistentEmotionPatterns
542
- .map((p) => `- ${p}`)
543
- .join("\n");
544
- }
545
- if (summary.recentChanges.length > 0) {
546
- profile.sections["近期变化"] = [
547
- "**最近变化趋势:**",
548
- ...summary.recentChanges.map((c) => `- ${c}`),
549
- ].join("\n");
550
- }
551
- return;
552
- } catch {
553
- // fall through to fallback
554
- }
555
- }
556
-
557
- // Fallback:v0.20 机械列表(用于无 provider 或 LLM 调用失败)
558
- await syncFromSourcesFallback(profile, memories, learner, timelineSummary);
559
- }
560
-
561
- async function syncFromSourcesFallback(
562
- profile: Profile,
563
- memories: MemoryFile[],
564
- learner: LearnerState,
565
- timelineSummary: string,
566
- ): Promise<void> {
567
- // 段 3:从 memory/event/*.md 聚合
568
- const events = memories.filter((m) => m.subtype === "event");
569
- if (events.length > 0) {
570
- const lines = events
571
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
572
- .map((e) => `- **${e.name}** — ${e.description || e.body.slice(0, 80)}`);
573
- profile.sections["关注议题"] = lines.join("\n");
574
- }
575
-
576
- // 段 4:从 learner.positivePatterns + negativePatterns 聚合
577
- const prefLines: string[] = [];
578
- if (learner.positivePatterns.length > 0) {
579
- prefLines.push("**用户喜欢的:**");
580
- for (const p of learner.positivePatterns.slice(-10)) {
581
- prefLines.push(`- ${p}`);
582
- }
583
- }
584
- if (learner.negativePatterns.length > 0) {
585
- prefLines.push("");
586
- prefLines.push("**用户不喜欢的:**");
587
- for (const p of learner.negativePatterns.slice(-10)) {
588
- prefLines.push(`- ${p}`);
589
- }
590
- }
591
- if (prefLines.length > 0) {
592
- profile.sections["已知偏好与禁忌"] = prefLines.join("\n");
593
- }
594
-
595
- // 段 5:从 memory/emotion/*.md 聚合 trigger + manifestation
596
- const emotions = memories.filter((m) => m.subtype === "emotion");
597
- if (emotions.length > 0) {
598
- const lines = emotions
599
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
600
- .map((e) => {
601
- const trigger = e.fields.trigger;
602
- const manifest = e.fields.manifestation;
603
- const parts = [`**${e.name}**`];
604
- if (trigger) parts.push(`触发:${trigger}`);
605
- if (manifest) parts.push(`表现:${manifest}`);
606
- return `- ${parts.join(";")}`;
607
- });
608
- profile.sections["长期情绪基线"] = lines.join("\n");
609
- }
610
-
611
- // 段 6:从 timeline
612
- if (timelineSummary) {
613
- profile.sections["近期变化"] = timelineSummary;
614
- }
615
- }
616
-
617
- // =====================================================================
618
- // 渲染(注入到 system prompt)
619
- // =====================================================================
620
-
621
- /**
622
- * 把 profile 渲染成紧凑 markdown 文本(用于 system prompt 注入)。
623
- *
624
- * v0.21:附加"用户认知画像"段(profile.ocean)
625
- * 明确说明这是"理解用户是什么样的人",不影响"对话风格"。
626
- */
627
- export function renderProfileForPrompt(profile: Profile): string {
628
- const lines: string[] = [];
629
- lines.push("## 用户画像(Profile)");
630
- lines.push("");
631
- lines.push("> 用户长期画像,多数据源整合视图(v0.21+)。**这是历史快照,不是当前状态。**");
632
- lines.push("> 用户当下的情绪/态度以本轮 side-query 识别结果为准,不要被画像里的旧印象绑架。");
633
- lines.push("");
634
-
635
- let hasContent = false;
636
- for (const name of PROFILE_SECTIONS) {
637
- const body = profile.sections[name]?.trim();
638
- if (!body || body === "(暂无)" || body.startsWith("(暂无")) continue;
639
-
640
- lines.push(`### ${name}`);
641
- lines.push(body);
642
- lines.push("");
643
- hasContent = true;
644
- }
645
-
646
- if (!hasContent) {
647
- lines.push("(暂无内容——首次使用,等用户透露更多信息后会自动填充)");
648
- lines.push("");
649
- }
650
-
651
- // v0.21 新增:用户认知画像
652
- if (profile.ocean) {
653
- const o = profile.ocean;
654
- lines.push("### 用户认知画像(动态推算的大五人格)");
655
- lines.push("");
656
- lines.push("> LLM 用以**理解用户是什么样的人**,**不影响对话风格**(风格由 session persona 控制)。");
657
- lines.push(`> 推算依据:${o.basis || "(暂无)"}`);
658
- lines.push("");
659
- lines.push(`- Openness: ${o.openness.toFixed(2)}(${oceanHint("openness", o.openness)})`);
660
- lines.push(`- Conscientiousness: ${o.conscientiousness.toFixed(2)}(${oceanHint("conscientiousness", o.conscientiousness)})`);
661
- lines.push(`- Extraversion: ${o.extraversion.toFixed(2)}(${oceanHint("extraversion", o.extraversion)})`);
662
- lines.push(`- Agreeableness: ${o.agreeableness.toFixed(2)}(${oceanHint("agreeableness", o.agreeableness)})`);
663
- lines.push(`- Neuroticism: ${o.neuroticism.toFixed(2)}(${oceanHint("neuroticism", o.neuroticism)})`);
664
- lines.push("");
665
- }
666
-
667
- return lines.join("\n");
668
- }
669
-
670
- // =====================================================================
671
- // 隐式识别 + 融合更新(v0.21:只更新段 1/2/6)
672
- // =====================================================================
673
-
674
- /**
675
- * v0.21:PROFILE_EXTRACT_PROMPT 只让 LLM 写段 1/2/6。
676
- * 段 3/4/5 由 summarizeForProfile 摘要。
677
- */
678
- const PROFILE_EXTRACT_PROMPT = `你是用户画像更新助手。下面是一段对话历史。
679
-
680
- **v0.21:只更新三段**(其他段由系统摘要,不需你写):
681
-
682
- {
683
- "基本信息": "结构化字段,用「字段:值」格式。多行用 \\n 分隔。例:'职业:前端工程师\\n所在地:上海'",
684
- "沟通风格": "新增/变化的偏好,例如 '喜欢简洁回复(≤3句)' 或 '讨厌被总结教训'",
685
- "近期变化": "最近 N 天的新趋势,例如 '最近一周睡眠变差'"
686
- }
687
-
688
- 要求:
689
- 1. **严格只输出这三段**,不要输出"关注议题"、"已知偏好"、"长期情绪基线"
690
- 2. **基本信息必须用「字段:值」格式**,不要写叙述句
691
- 3. **只输出有把握的**——没有明确信号就输出空字符串
692
- 4. **保留用户原话片段**(≤ 30 字)作为证据
693
- 5. 用第三人称叙述
694
- 6. 严格 JSON 输出,不要 Markdown 代码块
695
-
696
- 特别注意(confidence 高):
697
- - 用户说"我喜欢 X" / "我讨厌 Y" / "别 Z" → 沟通风格
698
- - 用户说"叫我 XX" / "我叫 XX" / "我名字是 XX" → 基本信息(昵称)
699
- - 用户聊到具体职业、地点、年龄段 → 基本信息
700
- - 用户纠正你 / 否定你 → 沟通风格
701
- - 用户提到近期生活变化 → 近期变化
702
-
703
- 对话如下:
704
-
705
- {conversation}`;
706
-
707
- export type ProfileUpdate = {
708
- 基本信息?: string;
709
- 沟通风格?: string;
710
- 关注议题?: string[];
711
- 已知偏好与禁忌?: string[];
712
- 长期情绪基线?: string;
713
- 近期变化?: string;
714
- };
715
-
716
- function buildConversationText(
717
- messages: { role: string; content: string }[],
718
- ): string {
719
- return messages
720
- .slice(-20)
721
- .map((m, i) => `${i + 1}. [${m.role}] ${m.content}`)
722
- .join("\n\n");
723
- }
724
-
725
- export async function extractProfileUpdate(
726
- provider: ModelProvider,
727
- recentMessages: { role: string; content: string }[],
728
- ): Promise<ProfileUpdate> {
729
- if (recentMessages.length === 0) return {};
730
-
731
- const conversation = buildConversationText(recentMessages);
732
- const prompt = PROFILE_EXTRACT_PROMPT.replace("{conversation}", conversation);
733
-
734
- let raw: string;
735
- try {
736
- raw = await provider.complete({
737
- model: provider.model,
738
- params: {
739
- system: "你是结构化信息抽取助手,严格输出 JSON。",
740
- messages: [{ role: "user", content: prompt }],
741
- maxTokens: 600,
742
- temperature: 0.2,
743
- },
744
- });
745
- if (process.env.EC_DEBUG_PROFILE) {
746
- console.log("[profile.extract] raw:", raw.slice(0, 200));
747
- }
748
- } catch {
749
- return {};
750
- }
751
-
752
- const cleaned = raw
753
- .trim()
754
- .replace(/^```(?:json)?\n?/, "")
755
- .replace(/\n?```$/, "");
756
- try {
757
- const parsed = JSON.parse(cleaned) as ProfileUpdate;
758
- return parsed;
759
- } catch {
760
- return {};
761
- }
762
- }
763
-
764
- // =====================================================================
765
- // 融合策略(v0.21:段 3/4/5 由 syncFromSources 摘要,不在这里处理)
766
- // =====================================================================
767
-
768
- function parseFieldLines(text: string): Map<string, string> {
769
- const map = new Map<string, string>();
770
- for (const line of text.split("\n")) {
771
- const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
772
- if (m) map.set(m[1].trim(), m[2].trim());
773
- }
774
- return map;
775
- }
776
-
777
- /** 段 1 的模板字段(顺序 = 展示顺序) */
778
- const BASIC_TEMPLATE_KEYS = ["昵称", "性别", "年龄段", "职业", "所在地"] as const;
779
-
780
- /**
781
- * 段 1 的字段别名。
782
- *
783
- * LLM / 用户说的叫法五花八门("我叫小李" → 名字、"我在上海" → 城市),
784
- * 收敛到模板字段上,避免同一个人被记成两个字段。
785
- */
786
- const BASIC_FIELD_ALIASES: Record<string, string> = {
787
- 昵称: "昵称",
788
- 名字: "昵称",
789
- 姓名: "昵称",
790
- 称呼: "昵称",
791
- 性别: "性别",
792
- 年龄段: "年龄段",
793
- 年龄: "年龄段",
794
- 职业: "职业",
795
- 工作: "职业",
796
- 职位: "职业",
797
- 所在地: "所在地",
798
- 城市: "所在地",
799
- 地区: "所在地",
800
- 住址: "所在地",
801
- 居住地: "所在地",
802
- };
803
-
804
- function canonicalBasicKey(key: string): string {
805
- const k = key.trim();
806
- return BASIC_FIELD_ALIASES[k] ?? BASIC_FIELD_ALIASES[k.toLowerCase()] ?? k;
807
- }
808
-
809
- /**
810
- * 段 1 的合并策略:**保留式合并**(v0.21.1 修复)。
811
- *
812
- * 旧实现是 parseFieldLines(current) → 按模板 5 个字段 rebuild 整段。
813
- * 而 parseFieldLines 要求每行都有 ":" / ":",
814
- * 于是段 1 里那些 "- (日期) 用户……" 的自由文本观察行全被丢弃
815
- * —— 实测一次 merge 丢 27 行历史(这条路径有回归测试覆盖)。
816
- *
817
- * 现在改成:
818
- * - 已有的行**一行都不删**
819
- * - 新内容能对上某个模板字段(含别名)→ **就地替换那一行**
820
- * - 对不上 → **追加**(模板字段插到模板字段区的位置,其余追加到末尾)
821
- * - 新内容不是「键:值」格式 → 当作自由文本追加
822
- */
823
- function mergeBasicSection(
824
- current: string,
825
- incoming: string,
826
- ): { text: string; changed: boolean } {
827
- const lines = current ? current.split("\n").filter((l) => l.trim()) : [];
828
- const incomingFields = parseFieldLines(incoming);
829
-
830
- // 新内容不是「键:值」格式 —— 当自由文本追加
831
- if (incomingFields.size === 0) {
832
- const add = incoming.trim();
833
- if (!add) return { text: current, changed: false };
834
- return { text: [...lines, add].join("\n"), changed: true };
835
- }
836
-
837
- const keyOf = (line: string): string | null => {
838
- const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
839
- return m ? canonicalBasicKey(m[1]) : null;
840
- };
841
- const valueOf = (line: string): string => {
842
- const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
843
- return m ? m[2].trim() : "";
844
- };
845
-
846
- let changed = false;
847
- for (const [rawKey, rawValue] of incomingFields) {
848
- const value = rawValue.trim();
849
- if (!value || value === "未知" || value === "(暂无)") continue;
850
-
851
- const key = canonicalBasicKey(rawKey);
852
- const idx = lines.findIndex((l) => keyOf(l) === key);
853
-
854
- if (idx >= 0) {
855
- // 已有同名字段 → 就地替换(不改动其它行)
856
- if (valueOf(lines[idx]) !== value) {
857
- lines[idx] = `- ${key}:${value}`;
858
- changed = true;
859
- }
860
- continue;
861
- }
862
-
863
- // 新字段
864
- const newLine = `- ${key}:${value}`;
865
- if ((BASIC_TEMPLATE_KEYS as readonly string[]).includes(key)) {
866
- // 模板字段插到模板字段区的末尾(保持模板顺序);一个都没有就插最前面
867
- let insertAt = 0;
868
- for (let i = 0; i < lines.length; i++) {
869
- const k = keyOf(lines[i]);
870
- if (k && (BASIC_TEMPLATE_KEYS as readonly string[]).includes(k)) {
871
- insertAt = i + 1;
872
- }
873
- }
874
- lines.splice(insertAt, 0, newLine);
875
- } else {
876
- lines.push(newLine);
877
- }
878
- changed = true;
879
- }
880
-
881
- return { text: lines.join("\n"), changed };
882
- }
883
-
884
- /**
885
- * v0.21 融合策略:
886
- * - 段 1 基本信息:结构化字段更新
887
- * - 段 2 沟通风格:append + 日期 + 滚动上限 30
888
- * - 段 6 近期变化:append + 日期 + 滚动上限 30
889
- * - 段 3/4/5:syncFromSources 摘要(这里不动)
890
- */
891
- export function mergeProfileUpdate(
892
- profile: Profile,
893
- update: ProfileUpdate,
894
- now: Date = new Date(),
895
- ): boolean {
896
- let changed = false;
897
- const dateStr = now.toISOString().slice(0, 10);
898
-
899
- // 段 1 基本信息 —— 保留式合并,不丢任何已有行(v0.21.1 修复)
900
- const basicIncoming = update["基本信息"];
901
- if (basicIncoming && basicIncoming.trim()) {
902
- const current = profile.sections["基本信息"] ?? "";
903
- const { text, changed: basicChanged } = mergeBasicSection(
904
- current,
905
- basicIncoming,
906
- );
907
- if (basicChanged) {
908
- profile.sections["基本信息"] = text;
909
- changed = true;
910
- }
911
- }
912
-
913
- // 段 2 沟通风格
914
- const styleIncoming = update["沟通风格"];
915
- if (styleIncoming && styleIncoming.trim()) {
916
- const current = profile.sections["沟通风格"] ?? "";
917
- const incoming = styleIncoming.trim();
918
- const isEmpty = !current.trim() || current === "(暂无)" || current.startsWith("(暂无");
919
- const isDup = current.replace(/\s+/g, "").includes(incoming.replace(/\s+/g, "").slice(0, 30));
920
- if (!isEmpty && isDup) {
921
- // dup
922
- } else {
923
- const lines = isEmpty ? [] : current.split("\n").filter((l) => l.trim());
924
- lines.push(`- (${dateStr}) ${incoming}`);
925
- profile.sections["沟通风格"] = lines.slice(-30).join("\n");
926
- changed = true;
927
- }
928
- }
929
-
930
- // 段 6 近期变化
931
- const recentIncoming = update["近期变化"];
932
- if (recentIncoming && recentIncoming.trim()) {
933
- const current = profile.sections["近期变化"] ?? "";
934
- const incoming = recentIncoming.trim();
935
- const isEmpty = !current.trim() || current === "(暂无)" || current.startsWith("(暂无");
936
- const isDup = current.replace(/\s+/g, "").includes(incoming.replace(/\s+/g, "").slice(0, 30));
937
- if (!isEmpty && isDup) {
938
- // dup
939
- } else {
940
- const lines = isEmpty ? [] : current.split("\n").filter((l) => l.trim());
941
- lines.push(`- (${dateStr}) ${incoming}`);
942
- profile.sections["近期变化"] = lines.slice(-30).join("\n");
943
- changed = true;
944
- }
945
- }
946
-
947
- return changed;
948
- }
949
-
950
- // =====================================================================
951
- // 一站式入口
952
- // =====================================================================
953
-
954
- export async function maybeUpdateProfile(
955
- dataDir: string,
956
- provider: ModelProvider,
957
- recentMessages: { role: string; content: string }[],
958
- options?: {
959
- userId?: string;
960
- memoryDir?: string;
961
- timeline?: Timeline;
962
- },
963
- ): Promise<{
964
- updated: boolean;
965
- profile: Profile;
966
- changes?: { section: ProfileSection; value: string }[];
967
- }> {
968
- try {
969
- const profile = await loadProfile(dataDir, { ...options, provider });
970
- const update = await extractProfileUpdate(provider, recentMessages);
971
-
972
- const sectionsBefore = new Map<ProfileSection, string>();
973
- for (const s of ["基本信息", "沟通风格", "近期变化"] as ProfileSection[]) {
974
- sectionsBefore.set(s, profile.sections[s] ?? "");
975
- }
976
-
977
- let changed = false;
978
- if (Object.keys(update).length > 0) {
979
- changed = mergeProfileUpdate(profile, update);
980
- }
981
-
982
- // sync 已由 loadProfile 触发,再触发一次确保最新 LLM 摘要
983
- await syncFromSources(profile, dataDir, { ...options, provider });
984
-
985
- await saveProfile(profile);
986
-
987
- const changes: { section: ProfileSection; value: string }[] = [];
988
- for (const s of ["基本信息", "沟通风格", "近期变化"] as ProfileSection[]) {
989
- const after = profile.sections[s] ?? "";
990
- const before = sectionsBefore.get(s) ?? "";
991
- if (after !== before) {
992
- const newLines = after
993
- .split("\n")
994
- .map((l) => l.trim())
995
- .filter((l) => l && !before.includes(l));
996
- if (newLines.length > 0) {
997
- changes.push({ section: s, value: newLines.join(" | ") });
998
- }
999
- }
1000
- }
1001
-
1002
- return { updated: changed, profile, changes };
1003
- } catch (e) {
1004
- console.error(`[profile] 更新失败:`, (e as Error).message);
1005
- const profile = await loadProfile(dataDir, options);
1006
- return { updated: false, profile };
1007
- }
1008
- }
1
+ // src/profile.ts
2
+ // 用户画像系统(Profile)。
3
+ //
4
+ // v0.21 重构:抽象 + 动态分析用户人格
5
+ //
6
+ // profile 不再是 memory 堆积的目录视图,而是**对 memory/learner/timeline 的抽象沉淀**。
7
+ //
8
+ // 两个 OCEAN 严格区分:
9
+ // - **session BigFivePersona.ocean**(`data/personality/{sessionId}.json`,用户 init 时 LLM 翻译的)
10
+ // → 决定 LLM **该怎么说话**(行为层 / 对话风格)
11
+ // - **profile ocean**(`data/profile/PROFILE.md` frontmatter,从历史/memory/learner 推算)
12
+ // → 帮 LLM **理解用户是什么样的人**(认知层 / 用户画像)
13
+ //
14
+ // 两者独立并存,profile ocean 不替代 persona。
15
+ //
16
+ // 段 1/2/6 由 LLM 抽取更新(基本信息、沟通风格、近期变化)
17
+ // 段 3/4/5 由 LLM 摘要更新(关注议题、已知偏好、长期情绪基线)—— 不再是机械列表
18
+ // 同时 push profile.ocean 到 frontmatter
19
+
20
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
21
+ import { existsSync } from "node:fs";
22
+ import type { ModelProvider } from "./provider.ts";
23
+ import type { LearnerState } from "./persona-learner.ts";
24
+ import { loadLearner } from "./persona-learner.ts";
25
+ import { scanMemory, type MemoryFile } from "./memory.ts";
26
+ import type { Timeline } from "./timeline.ts";
27
+ import {
28
+ parseContextFile,
29
+ serializeContextFile,
30
+ PROFILE_SECTIONS as CONTEXT_PROFILE_SECTIONS,
31
+ PROFILE_FILENAME,
32
+ getProfilePath,
33
+ type ProfileSection,
34
+ type ContextFileMeta,
35
+ } from "./context-file.ts";
36
+ import { oceanHint } from "./bigfive.ts";
37
+
38
+ // =====================================================================
39
+ // 类型定义
40
+ // =====================================================================
41
+
42
+ export const PROFILE_SECTIONS = CONTEXT_PROFILE_SECTIONS;
43
+ export { PROFILE_FILENAME, getProfilePath };
44
+ export type { ProfileSection };
45
+
46
+ /**
47
+ * 动态推算的"用户是什么样的人"。
48
+ *
49
+ * 注意:这是**认知层**,跟 session BigFivePersona.ocean(行为层)独立。
50
+ * profile.ocean 帮 LLM 理解用户;session persona 告诉 LLM 怎么说话。
51
+ */
52
+ export type ProfileOcean = {
53
+ openness: number;
54
+ conscientiousness: number;
55
+ extraversion: number;
56
+ agreeableness: number;
57
+ neuroticism: number;
58
+ /** 推算依据摘要(哪段 history / memory 导致这个数值) */
59
+ basis: string;
60
+ };
61
+
62
+ export type Profile = {
63
+ /** 6 段内容(key = 段落名,value = 段落正文) */
64
+ sections: Record<ProfileSection, string>;
65
+ /** 动态推算的"用户是什么样的人" */
66
+ ocean: ProfileOcean | null;
67
+ /** 最后一次 OCEAN 推算时间(ms) */
68
+ oceanUpdatedAt: number;
69
+ /** 文件路径 */
70
+ path: string;
71
+ /** 最后更新时间(ms) */
72
+ updatedAt: number;
73
+ /** 是否是首次初始化 */
74
+ initialized: boolean;
75
+ /** frontmatter 元数据 */
76
+ meta: ContextFileMeta;
77
+ };
78
+
79
+ // =====================================================================
80
+ // 默认模板
81
+ // =====================================================================
82
+
83
+ const DEFAULT_META: ContextFileMeta = {
84
+ name: "用户画像",
85
+ version: "0.7",
86
+ description: "用户长期画像,v0.21 抽象 + 动态推算",
87
+ author: "rememberme",
88
+ kind: "profile",
89
+ };
90
+
91
+ const DEFAULT_BODY = `> 自动从对话中累积维护。每次对话开始前注入到 system prompt。
92
+ > 段 1/2 由 LLM 抽取,段 3/4/5/6 由 LLM 摘要(v0.21 改造)。
93
+ > frontmatter 的 ocean_* 字段是动态推算的"用户认知画像",与 session persona 独立。
94
+
95
+ ## 1. 基本信息
96
+ - 昵称:未知
97
+ - 性别:未知
98
+ - 年龄段:未知
99
+ - 职业:未知
100
+ - 所在地:未知
101
+
102
+ ## 2. 沟通风格
103
+ - (暂无——等用户表现出偏好后再填)
104
+
105
+ ## 3. 关注议题
106
+ - (暂无——从 memory/event 抽象汇总)
107
+
108
+ ## 4. 已知偏好与禁忌
109
+ - (暂无——从反馈学习抽象汇总)
110
+
111
+ ## 5. 长期情绪基线
112
+ - (暂无——从 memory/emotion 抽象汇总)
113
+
114
+ ## 6. 近期变化
115
+ - (暂无——从 timeline 抽象汇总)`;
116
+
117
+ // =====================================================================
118
+ // 加载 / 保存
119
+ // =====================================================================
120
+
121
+ /**
122
+ * 从 frontmatter 解析 ProfileOcean 字段。
123
+ */
124
+ function readOceanFromMeta(meta: ContextFileMeta): ProfileOcean | null {
125
+ const get = (key: string): string | undefined => {
126
+ const v = (meta as Record<string, unknown>)[key];
127
+ return typeof v === "string" ? v : undefined;
128
+ };
129
+ const o = meta as Record<string, unknown>;
130
+ const openness = Number(o.ocean_openness);
131
+ const conscientiousness = Number(o.ocean_conscientiousness);
132
+ const extraversion = Number(o.ocean_extraversion);
133
+ const agreeableness = Number(o.ocean_agreeableness);
134
+ const neuroticism = Number(o.ocean_neuroticism);
135
+ if (
136
+ [openness, conscientiousness, extraversion, agreeableness, neuroticism].some(
137
+ (n) => Number.isNaN(n),
138
+ )
139
+ ) {
140
+ return null;
141
+ }
142
+ return {
143
+ openness,
144
+ conscientiousness,
145
+ extraversion,
146
+ agreeableness,
147
+ neuroticism,
148
+ basis: get("ocean_basis") ?? "",
149
+ };
150
+ }
151
+
152
+ /**
153
+ * 把 ProfileOcean 写入 meta。
154
+ */
155
+ function writeOceanToMeta(
156
+ meta: ContextFileMeta,
157
+ ocean: ProfileOcean,
158
+ oceanUpdatedAt: number,
159
+ ): void {
160
+ const m = meta as Record<string, unknown>;
161
+ m.ocean_openness = ocean.openness.toFixed(2);
162
+ m.ocean_conscientiousness = ocean.conscientiousness.toFixed(2);
163
+ m.ocean_extraversion = ocean.extraversion.toFixed(2);
164
+ m.ocean_agreeableness = ocean.agreeableness.toFixed(2);
165
+ m.ocean_neuroticism = ocean.neuroticism.toFixed(2);
166
+ m.ocean_basis = ocean.basis;
167
+ m.ocean_updated_at = new Date(oceanUpdatedAt).toISOString();
168
+ }
169
+
170
+ /**
171
+ * 加载 profile,自动从其他数据源同步段 3/4/5/6 + 推算 ocean。
172
+ *
173
+ * @param dataDir data 根目录
174
+ * @param options.userId 用户 ID(用于加载 learner state)
175
+ * @param options.memoryDir memory 目录
176
+ * @param options.timeline Timeline 实例
177
+ * @param options.provider LLM provider(用于 v0.21 摘要推算;不传则用机械列表 fallback)
178
+ */
179
+ export async function loadProfile(
180
+ dataDir: string,
181
+ options?: {
182
+ userId?: string;
183
+ memoryDir?: string;
184
+ timeline?: Timeline;
185
+ provider?: ModelProvider;
186
+ },
187
+ ): Promise<Profile> {
188
+ const path = getProfilePath(dataDir);
189
+ const dir = path.replace(/[/\\][^/\\]+$/, "");
190
+
191
+ if (!existsSync(path)) {
192
+ await mkdir(dir, { recursive: true });
193
+ const initialContent = serializeContextFile(DEFAULT_META, DEFAULT_BODY);
194
+ await writeFile(path, initialContent, "utf-8");
195
+ const ctx = parseContextFile(initialContent, path);
196
+ const profile: Profile = {
197
+ sections: ctx.structuredSections ?? emptySections(),
198
+ ocean: readOceanFromMeta(ctx.meta),
199
+ oceanUpdatedAt: 0,
200
+ path,
201
+ updatedAt: Date.now(),
202
+ initialized: true,
203
+ meta: ctx.meta,
204
+ };
205
+ await syncFromSources(profile, dataDir, options);
206
+ await saveProfile(profile);
207
+ return profile;
208
+ }
209
+
210
+ const raw = await readFile(path, "utf-8");
211
+ const ctx = parseContextFile(raw, path);
212
+ const stats = await import("node:fs/promises").then((fs) => fs.stat(path));
213
+ const profile: Profile = {
214
+ sections: ctx.structuredSections ?? emptySections(),
215
+ ocean: readOceanFromMeta(ctx.meta),
216
+ oceanUpdatedAt:
217
+ (ctx.meta as Record<string, unknown>).ocean_updated_at &&
218
+ typeof (ctx.meta as Record<string, unknown>).ocean_updated_at === "string"
219
+ ? new Date(
220
+ (ctx.meta as Record<string, unknown>).ocean_updated_at as string,
221
+ ).getTime()
222
+ : 0,
223
+ path,
224
+ updatedAt: stats.mtimeMs,
225
+ initialized: false,
226
+ meta: ctx.meta,
227
+ };
228
+ await syncFromSources(profile, dataDir, options);
229
+ await saveProfile(profile);
230
+ return profile;
231
+ }
232
+
233
+ /**
234
+ * 把 profile 写入磁盘。
235
+ */
236
+ export async function saveProfile(profile: Profile): Promise<void> {
237
+ // 把 ocean 写回 meta(ocean_* 字段会被 serializeContextFile 之外的逻辑处理)
238
+ if (profile.ocean) {
239
+ writeOceanToMeta(profile.meta, profile.ocean, profile.oceanUpdatedAt);
240
+ }
241
+ const body = serializeProfileBody(profile.sections);
242
+ const content = serializeContextFile(profile.meta, body);
243
+ // 在 serializeContextFile 之后再附加 ocean_* 字段(因为它只处理固定 5 个字段)
244
+ if (profile.ocean) {
245
+ const oceanLines: string[] = [];
246
+ const o = profile.ocean;
247
+ oceanLines.push(`- **ocean_openness**:${o.openness.toFixed(2)}`);
248
+ oceanLines.push(`- **ocean_conscientiousness**:${o.conscientiousness.toFixed(2)}`);
249
+ oceanLines.push(`- **ocean_extraversion**:${o.extraversion.toFixed(2)}`);
250
+ oceanLines.push(`- **ocean_agreeableness**:${o.agreeableness.toFixed(2)}`);
251
+ oceanLines.push(`- **ocean_neuroticism**:${o.neuroticism.toFixed(2)}`);
252
+ oceanLines.push(`- **ocean_basis**:${o.basis}`);
253
+ oceanLines.push(`- **ocean_updated_at**:${new Date(profile.oceanUpdatedAt).toISOString()}`);
254
+ // 在 body 之后插入(frontmatter 之后,body 之前)
255
+ const idx = content.indexOf("\n\n# 用户画像(Profile)");
256
+ if (idx > 0) {
257
+ const final = content.slice(0, idx) + "\n" + oceanLines.join("\n") + content.slice(idx);
258
+ await writeFile(profile.path, final, "utf-8");
259
+ } else {
260
+ await writeFile(profile.path, content, "utf-8");
261
+ }
262
+ } else {
263
+ await writeFile(profile.path, content, "utf-8");
264
+ }
265
+ profile.updatedAt = Date.now();
266
+ }
267
+
268
+ function serializeProfileBody(
269
+ sections: Record<ProfileSection, string>,
270
+ ): string {
271
+ const lines: string[] = [
272
+ "# 用户画像(Profile)",
273
+ "",
274
+ "> 自动从对话中累积维护。每次对话开始前注入到 system prompt。",
275
+ "> 段 1/2 由 LLM 抽取,段 3/4/5/6 由 LLM 摘要(v0.21 改造)。",
276
+ "> frontmatter 的 ocean_* 字段是动态推算的『用户认知画像』,与 session persona 独立。",
277
+ "",
278
+ ];
279
+ PROFILE_SECTIONS.forEach((name, i) => {
280
+ const content = sections[name]?.trim() || "(暂无)";
281
+ lines.push(`## ${i + 1}. ${name}`);
282
+ lines.push(content);
283
+ lines.push("");
284
+ });
285
+ return lines.join("\n");
286
+ }
287
+
288
+ function emptySections(): Record<ProfileSection, string> {
289
+ const out = {} as Record<ProfileSection, string>;
290
+ for (const s of PROFILE_SECTIONS) out[s] = "";
291
+ return out;
292
+ }
293
+
294
+ function joinSafe(parent: string, child: string): string {
295
+ return parent.endsWith("/") || parent.endsWith("\\")
296
+ ? parent + child
297
+ : parent + "/" + child;
298
+ }
299
+
300
+ // =====================================================================
301
+ // v0.21 摘要:调 LLM 把所有数据消化成结构化输出
302
+ // =====================================================================
303
+
304
+ /**
305
+ * summarizeForProfile 输入。
306
+ */
307
+ export type ProfileSources = {
308
+ memories: MemoryFile[];
309
+ learner: LearnerState;
310
+ timelineSummary: string;
311
+ };
312
+
313
+ /**
314
+ * summarizeForProfile 输出(LLM JSON)。
315
+ */
316
+ export type ProfileSummary = {
317
+ ocean: ProfileOcean | null;
318
+ abstractTopics: string[];
319
+ persistentPreferences: string[];
320
+ persistentEmotionPatterns: string[];
321
+ recentChanges: string[];
322
+ };
323
+
324
+ const SUMMARY_SYSTEM_PROMPT = `你是用户认知分析师。下面是用户的所有历史记忆、反馈学习观察、近期情绪时间线。
325
+
326
+ **任务**:抽象、归并、聚类出"用户是什么样的人",**不是** LLM 该怎么说话。
327
+
328
+ **v0.21 输出严格按以下 JSON**(不要 Markdown 代码块):
329
+
330
+ {
331
+ "ocean": {
332
+ "openness": 0.0-1.0,
333
+ "conscientiousness": 0.0-1.0,
334
+ "extraversion": 0.0-1.0,
335
+ "agreeableness": 0.0-1.0,
336
+ "neuroticism": 0.0-1.0,
337
+ "basis": "推算依据(哪段对话 / 哪些 memory 导致这个数值,1-2 句话)"
338
+ },
339
+ "abstractTopics": [
340
+ "主题级抽象议题 1(不是文件名,是归纳出的主题)",
341
+ "主题级抽象议题 2"
342
+ ],
343
+ "persistentPreferences": [
344
+ "持久偏好 1(从反馈学习观察归纳,不是单条原话)",
345
+ "持久偏好 2"
346
+ ],
347
+ "persistentEmotionPatterns": [
348
+ "情绪模式名 → 触发:xxx → 表现:xxx",
349
+ "情绪模式名 → 触发:xxx → 表现:xxx"
350
+ ],
351
+ "recentChanges": [
352
+ "最近变化趋势 1(不超过 7 天)",
353
+ "最近变化趋势 2"
354
+ ]
355
+ }
356
+
357
+ **严格要求**:
358
+
359
+ 1. **抽象,不堆积**:
360
+ - 10 条 emotion memory → 总结为 2-3 个情绪模式(不列文件名)
361
+ - 20 条 learner pattern → 总结为 3-5 条持久偏好(去重、合并、归纳)
362
+ - 5 条 event memory → 总结为 2-4 个议题主题
363
+
364
+ 2. **OCEAN 数值要基于实际行为信号**:
365
+ - 用户反复提到哲学/文学/跨领域话题 → openness 高
366
+ - 用户对话题回避、转移 → 可能在某些维度低
367
+ - 不猜测;信号不足就 0.5(中性)
368
+
369
+ 3. **basis 必须引用证据**:不要凭空给数字,说"基于 X、Y"
370
+
371
+ 4. **空数组合法**:没有信号时该段就是空数组(不要硬凑)
372
+
373
+ 5. **不要重复**同样的事情到不同段
374
+
375
+ 下面是用户的全部数据:
376
+
377
+ === Memory 文件清单 ===
378
+ {memoryList}
379
+
380
+ === Memory 文件正文(仅情绪模式 + 生活事件)===
381
+ {memoryBodies}
382
+
383
+ === 反馈学习观察 ===
384
+ {learnerPatterns}
385
+
386
+ === 近期情绪时间线 ===
387
+ {timelineSummary}`;
388
+
389
+ /**
390
+ * 调 LLM 把所有数据源消化成结构化摘要。
391
+ * 失败容错:返回空摘要。
392
+ */
393
+ export async function summarizeForProfile(
394
+ provider: ModelProvider,
395
+ sources: ProfileSources,
396
+ ): Promise<ProfileSummary> {
397
+ const empty: ProfileSummary = {
398
+ ocean: null,
399
+ abstractTopics: [],
400
+ persistentPreferences: [],
401
+ persistentEmotionPatterns: [],
402
+ recentChanges: [],
403
+ };
404
+
405
+ try {
406
+ const memList = sources.memories
407
+ .map((m) => `[${m.subtype}] ${m.name} — ${m.description || "(无描述)"}`)
408
+ .join("\n");
409
+ const memBodies = sources.memories
410
+ .filter((m) => m.subtype === "emotion" || m.subtype === "event")
411
+ .map(
412
+ (m) =>
413
+ `### [${m.subtype}] ${m.name}\ntrigger: ${(m.fields as Record<string, unknown>).trigger ?? ""}\nmanifestation: ${(m.fields as Record<string, unknown>).manifestation ?? ""}\nemotional_impact: ${(m.fields as Record<string, unknown>).emotional_impact ?? ""}\nbody: ${m.body.slice(0, 300)}`,
414
+ )
415
+ .join("\n\n");
416
+ const learnerPatterns = [
417
+ ...((sources.learner.positivePatterns ?? []).slice(-15).map((p) => `+ ${p}`)),
418
+ ...((sources.learner.negativePatterns ?? []).slice(-15).map((p) => `- ${p}`)),
419
+ ].join("\n");
420
+
421
+ const userPrompt = SUMMARY_SYSTEM_PROMPT
422
+ .replace("{memoryList}", memList || "(无)")
423
+ .replace("{memoryBodies}", memBodies || "(无)")
424
+ .replace("{learnerPatterns}", learnerPatterns || "(无)")
425
+ .replace("{timelineSummary}", sources.timelineSummary || "(无)");
426
+
427
+ const raw = await provider.complete({
428
+ model: provider.model,
429
+ params: {
430
+ system: "你是用户认知分析师,输出严格 JSON。",
431
+ messages: [{ role: "user", content: userPrompt }],
432
+ maxTokens: 1500,
433
+ temperature: 0.3,
434
+ },
435
+ });
436
+
437
+ const cleaned = raw
438
+ .trim()
439
+ .replace(/^```(?:json)?\n?/i, "")
440
+ .replace(/\n?```\s*$/, "")
441
+ .trim();
442
+
443
+ if (process.env.EC_DEBUG_PROFILE) {
444
+ console.log("[profile.summarize] cleaned:", cleaned.slice(0, 200));
445
+ }
446
+
447
+ const match = cleaned.match(/\{[\s\S]*\}/);
448
+ if (!match) return empty;
449
+
450
+ const parsed = JSON.parse(match[0]);
451
+
452
+ // 校验 OCEAN
453
+ let ocean: ProfileOcean | null = null;
454
+ const o = parsed.ocean;
455
+ if (o && typeof o === "object") {
456
+ const vals = [o.openness, o.conscientiousness, o.extraversion, o.agreeableness, o.neuroticism];
457
+ if (vals.every((v) => typeof v === "number" && v >= 0 && v <= 1)) {
458
+ ocean = {
459
+ openness: vals[0],
460
+ conscientiousness: vals[1],
461
+ extraversion: vals[2],
462
+ agreeableness: vals[3],
463
+ neuroticism: vals[4],
464
+ basis: typeof o.basis === "string" ? o.basis.slice(0, 300) : "",
465
+ };
466
+ }
467
+ }
468
+
469
+ return {
470
+ ocean,
471
+ abstractTopics: Array.isArray(parsed.abstractTopics)
472
+ ? parsed.abstractTopics.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
473
+ : [],
474
+ persistentPreferences: Array.isArray(parsed.persistentPreferences)
475
+ ? parsed.persistentPreferences.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
476
+ : [],
477
+ persistentEmotionPatterns: Array.isArray(parsed.persistentEmotionPatterns)
478
+ ? parsed.persistentEmotionPatterns.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
479
+ : [],
480
+ recentChanges: Array.isArray(parsed.recentChanges)
481
+ ? parsed.recentChanges.filter((x: unknown) => typeof x === "string").map((x: string) => x.slice(0, 200))
482
+ : [],
483
+ };
484
+ } catch {
485
+ return empty;
486
+ }
487
+ }
488
+
489
+ // =====================================================================
490
+ // 同步:从其他数据源填充段 3/4/5/6 + 推算 profile.ocean
491
+ // =====================================================================
492
+
493
+ /**
494
+ * v0.21:从数据源同步。
495
+ * - 有 provider:调 summarizeForProfile 摘要(推荐路径)
496
+ * - 无 provider:fallback 到 v0.20 机械列表
497
+ */
498
+ export async function syncFromSources(
499
+ profile: Profile,
500
+ dataDir: string,
501
+ options?: {
502
+ userId?: string;
503
+ memoryDir?: string;
504
+ timeline?: Timeline;
505
+ provider?: ModelProvider;
506
+ },
507
+ ): Promise<void> {
508
+ const memoryDir = options?.memoryDir ?? joinSafe(dataDir, "memory");
509
+ const userId = options?.userId ?? "default";
510
+ const learner = loadLearner(dataDir, userId);
511
+ const memories = await scanMemory(memoryDir);
512
+ const timelineSummary = options?.timeline
513
+ ? await options.timeline.renderSummary(10)
514
+ : "";
515
+
516
+ // v0.21 推荐路径:调 LLM 摘要
517
+ if (options?.provider) {
518
+ try {
519
+ const summary = await summarizeForProfile(options.provider, {
520
+ memories,
521
+ learner,
522
+ timelineSummary,
523
+ });
524
+
525
+ if (summary.ocean) {
526
+ profile.ocean = summary.ocean;
527
+ profile.oceanUpdatedAt = Date.now();
528
+ }
529
+ if (summary.abstractTopics.length > 0) {
530
+ profile.sections["关注议题"] = summary.abstractTopics
531
+ .map((t) => `- ${t}`)
532
+ .join("\n");
533
+ }
534
+ if (summary.persistentPreferences.length > 0) {
535
+ profile.sections["已知偏好与禁忌"] = [
536
+ "**用户持久偏好(从反馈学习总结):**",
537
+ ...summary.persistentPreferences.map((p) => `- ${p}`),
538
+ ].join("\n");
539
+ }
540
+ if (summary.persistentEmotionPatterns.length > 0) {
541
+ profile.sections["长期情绪基线"] = summary.persistentEmotionPatterns
542
+ .map((p) => `- ${p}`)
543
+ .join("\n");
544
+ }
545
+ // 段 6:只刷新「趋势」部分,**保留带日期的事件行**。
546
+ // 早期实现是整段覆盖,把 mergeProfileUpdate 追加的 "- (日期) ..." 行一起冲掉,
547
+ // 导致段 6 永远留不下累积记录(v0.22.1 修复)。
548
+ if (summary.recentChanges.length > 0) {
549
+ const { text, changed: recentChanged } = refreshRecentTrends(
550
+ profile.sections["近期变化"] ?? "",
551
+ [
552
+ "**最近变化趋势:**",
553
+ ...summary.recentChanges.map((c) => `- ${c}`),
554
+ ].join("\n"),
555
+ );
556
+ if (recentChanged) {
557
+ profile.sections["近期变化"] = text;
558
+ }
559
+ }
560
+ return;
561
+ } catch {
562
+ // fall through to fallback
563
+ }
564
+ }
565
+
566
+ // Fallback:v0.20 机械列表(用于无 provider 或 LLM 调用失败)
567
+ await syncFromSourcesFallback(profile, memories, learner, timelineSummary);
568
+ }
569
+
570
+ async function syncFromSourcesFallback(
571
+ profile: Profile,
572
+ memories: MemoryFile[],
573
+ learner: LearnerState,
574
+ timelineSummary: string,
575
+ ): Promise<void> {
576
+ // 段 3:从 memory/event/*.md 聚合
577
+ const events = memories.filter((m) => m.subtype === "event");
578
+ if (events.length > 0) {
579
+ const lines = events
580
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
581
+ .map((e) => `- **${e.name}** — ${e.description || e.body.slice(0, 80)}`);
582
+ profile.sections["关注议题"] = lines.join("\n");
583
+ }
584
+
585
+ // 段 4:从 learner.positivePatterns + negativePatterns 聚合
586
+ const prefLines: string[] = [];
587
+ if (learner.positivePatterns.length > 0) {
588
+ prefLines.push("**用户喜欢的:**");
589
+ for (const p of learner.positivePatterns.slice(-10)) {
590
+ prefLines.push(`- ${p}`);
591
+ }
592
+ }
593
+ if (learner.negativePatterns.length > 0) {
594
+ prefLines.push("");
595
+ prefLines.push("**用户不喜欢的:**");
596
+ for (const p of learner.negativePatterns.slice(-10)) {
597
+ prefLines.push(`- ${p}`);
598
+ }
599
+ }
600
+ if (prefLines.length > 0) {
601
+ profile.sections["已知偏好与禁忌"] = prefLines.join("\n");
602
+ }
603
+
604
+ // 段 5:从 memory/emotion/*.md 聚合 trigger + manifestation
605
+ const emotions = memories.filter((m) => m.subtype === "emotion");
606
+ if (emotions.length > 0) {
607
+ const lines = emotions
608
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
609
+ .map((e) => {
610
+ const trigger = e.fields.trigger;
611
+ const manifest = e.fields.manifestation;
612
+ const parts = [`**${e.name}**`];
613
+ if (trigger) parts.push(`触发:${trigger}`);
614
+ if (manifest) parts.push(`表现:${manifest}`);
615
+ return `- ${parts.join(";")}`;
616
+ });
617
+ profile.sections["长期情绪基线"] = lines.join("\n");
618
+ }
619
+
620
+ // 段 6:从 timeline —— 同样只刷新趋势部分,保留带日期的事件行(v0.22.1 修复)
621
+ if (timelineSummary) {
622
+ const { text, changed: recentChanged } = refreshRecentTrends(
623
+ profile.sections["近期变化"] ?? "",
624
+ timelineSummary,
625
+ );
626
+ if (recentChanged) {
627
+ profile.sections["近期变化"] = text;
628
+ }
629
+ }
630
+ }
631
+
632
+ // =====================================================================
633
+ // 渲染(注入到 system prompt)
634
+ // =====================================================================
635
+
636
+ /**
637
+ * 把 profile 渲染成紧凑 markdown 文本(用于 system prompt 注入)。
638
+ *
639
+ * v0.21:附加"用户认知画像"段(profile.ocean)
640
+ * 明确说明这是"理解用户是什么样的人",不影响"对话风格"。
641
+ */
642
+ export function renderProfileForPrompt(profile: Profile): string {
643
+ const lines: string[] = [];
644
+ lines.push("## 用户画像(Profile)");
645
+ lines.push("");
646
+ lines.push("> 用户长期画像,多数据源整合视图(v0.21+)。**这是历史快照,不是当前状态。**");
647
+ lines.push("> 用户当下的情绪/态度以本轮 side-query 识别结果为准,不要被画像里的旧印象绑架。");
648
+ lines.push("");
649
+
650
+ let hasContent = false;
651
+ for (const name of PROFILE_SECTIONS) {
652
+ const body = profile.sections[name]?.trim();
653
+ if (!body || body === "(暂无)" || body.startsWith("(暂无")) continue;
654
+
655
+ lines.push(`### ${name}`);
656
+ lines.push(body);
657
+ lines.push("");
658
+ hasContent = true;
659
+ }
660
+
661
+ if (!hasContent) {
662
+ lines.push("(暂无内容——首次使用,等用户透露更多信息后会自动填充)");
663
+ lines.push("");
664
+ }
665
+
666
+ // v0.21 新增:用户认知画像
667
+ if (profile.ocean) {
668
+ const o = profile.ocean;
669
+ lines.push("### 用户认知画像(动态推算的大五人格)");
670
+ lines.push("");
671
+ lines.push("> LLM 用以**理解用户是什么样的人**,**不影响对话风格**(风格由 session persona 控制)。");
672
+ lines.push(`> 推算依据:${o.basis || "(暂无)"}`);
673
+ lines.push("");
674
+ lines.push(`- Openness: ${o.openness.toFixed(2)}(${oceanHint("openness", o.openness)})`);
675
+ lines.push(`- Conscientiousness: ${o.conscientiousness.toFixed(2)}(${oceanHint("conscientiousness", o.conscientiousness)})`);
676
+ lines.push(`- Extraversion: ${o.extraversion.toFixed(2)}(${oceanHint("extraversion", o.extraversion)})`);
677
+ lines.push(`- Agreeableness: ${o.agreeableness.toFixed(2)}(${oceanHint("agreeableness", o.agreeableness)})`);
678
+ lines.push(`- Neuroticism: ${o.neuroticism.toFixed(2)}(${oceanHint("neuroticism", o.neuroticism)})`);
679
+ lines.push("");
680
+ }
681
+
682
+ return lines.join("\n");
683
+ }
684
+
685
+ // =====================================================================
686
+ // 隐式识别 + 融合更新(v0.21:只更新段 1/2/6)
687
+ // =====================================================================
688
+
689
+ /**
690
+ * v0.21:PROFILE_EXTRACT_PROMPT 只让 LLM 写段 1/2/6。
691
+ * 段 3/4/5 由 summarizeForProfile 摘要。
692
+ */
693
+ const PROFILE_EXTRACT_PROMPT = `你是用户画像更新助手。下面是一段对话历史。
694
+
695
+ **v0.21:只更新三段**(其他段由系统摘要,不需你写):
696
+
697
+ {
698
+ "基本信息": "结构化字段,用「字段:值」格式。多行用 \\n 分隔。例:'职业:前端工程师\\n所在地:上海'",
699
+ "沟通风格": "新增/变化的偏好,例如 '喜欢简洁回复(≤3句)' 或 '讨厌被总结教训'",
700
+ "近期变化": "最近 N 天的新趋势,例如 '最近一周睡眠变差'"
701
+ }
702
+
703
+ 要求:
704
+ 1. **严格只输出这三段**,不要输出"关注议题"、"已知偏好"、"长期情绪基线"
705
+ 2. **基本信息必须用「字段:值」格式**,不要写叙述句
706
+ 3. **只输出有把握的**——没有明确信号就输出空字符串
707
+ 4. **保留用户原话片段**(≤ 30 字)作为证据
708
+ 5. 用第三人称叙述
709
+ 6. 严格 JSON 输出,不要 Markdown 代码块
710
+
711
+ 特别注意(confidence 高):
712
+ - 用户说"我喜欢 X" / "我讨厌 Y" / "别 Z" → 沟通风格
713
+ - 用户说"叫我 XX" / "我叫 XX" / "我名字是 XX" → 基本信息(昵称)
714
+ - 用户聊到具体职业、地点、年龄段 → 基本信息
715
+ - 用户纠正你 / 否定你 → 沟通风格
716
+ - 用户提到近期生活变化 → 近期变化
717
+
718
+ 对话如下:
719
+
720
+ {conversation}`;
721
+
722
+ export type ProfileUpdate = {
723
+ 基本信息?: string;
724
+ 沟通风格?: string;
725
+ 关注议题?: string[];
726
+ 已知偏好与禁忌?: string[];
727
+ 长期情绪基线?: string;
728
+ 近期变化?: string;
729
+ };
730
+
731
+ function buildConversationText(
732
+ messages: { role: string; content: string }[],
733
+ ): string {
734
+ return messages
735
+ .slice(-20)
736
+ .map((m, i) => `${i + 1}. [${m.role}] ${m.content}`)
737
+ .join("\n\n");
738
+ }
739
+
740
+ export async function extractProfileUpdate(
741
+ provider: ModelProvider,
742
+ recentMessages: { role: string; content: string }[],
743
+ ): Promise<ProfileUpdate> {
744
+ if (recentMessages.length === 0) return {};
745
+
746
+ const conversation = buildConversationText(recentMessages);
747
+ const prompt = PROFILE_EXTRACT_PROMPT.replace("{conversation}", conversation);
748
+
749
+ let raw: string;
750
+ try {
751
+ raw = await provider.complete({
752
+ model: provider.model,
753
+ params: {
754
+ system: "你是结构化信息抽取助手,严格输出 JSON。",
755
+ messages: [{ role: "user", content: prompt }],
756
+ maxTokens: 600,
757
+ temperature: 0.2,
758
+ },
759
+ });
760
+ if (process.env.EC_DEBUG_PROFILE) {
761
+ console.log("[profile.extract] raw:", raw.slice(0, 200));
762
+ }
763
+ } catch {
764
+ return {};
765
+ }
766
+
767
+ const cleaned = raw
768
+ .trim()
769
+ .replace(/^```(?:json)?\n?/, "")
770
+ .replace(/\n?```$/, "");
771
+ try {
772
+ const parsed = JSON.parse(cleaned) as ProfileUpdate;
773
+ return parsed;
774
+ } catch {
775
+ return {};
776
+ }
777
+ }
778
+
779
+ // =====================================================================
780
+ // 融合策略(v0.21:段 3/4/5 由 syncFromSources 摘要,不在这里处理)
781
+ // =====================================================================
782
+
783
+ function parseFieldLines(text: string): Map<string, string> {
784
+ const map = new Map<string, string>();
785
+ for (const line of text.split("\n")) {
786
+ const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
787
+ if (m) map.set(m[1].trim(), m[2].trim());
788
+ }
789
+ return map;
790
+ }
791
+
792
+ /** 段 1 的模板字段(顺序 = 展示顺序) */
793
+ const BASIC_TEMPLATE_KEYS = ["昵称", "性别", "年龄段", "职业", "所在地"] as const;
794
+
795
+ /**
796
+ * 段 1 的字段别名。
797
+ *
798
+ * LLM / 用户说的叫法五花八门("我叫小李" → 名字、"我在上海" → 城市),
799
+ * 收敛到模板字段上,避免同一个人被记成两个字段。
800
+ */
801
+ const BASIC_FIELD_ALIASES: Record<string, string> = {
802
+ 昵称: "昵称",
803
+ 名字: "昵称",
804
+ 姓名: "昵称",
805
+ 称呼: "昵称",
806
+ 性别: "性别",
807
+ 年龄段: "年龄段",
808
+ 年龄: "年龄段",
809
+ 职业: "职业",
810
+ 工作: "职业",
811
+ 职位: "职业",
812
+ 所在地: "所在地",
813
+ 城市: "所在地",
814
+ 地区: "所在地",
815
+ 住址: "所在地",
816
+ 居住地: "所在地",
817
+ };
818
+
819
+ function canonicalBasicKey(key: string): string {
820
+ const k = key.trim();
821
+ return BASIC_FIELD_ALIASES[k] ?? BASIC_FIELD_ALIASES[k.toLowerCase()] ?? k;
822
+ }
823
+
824
+ /**
825
+ * 段 1 的合并策略:**保留式合并**(v0.21.1 修复)。
826
+ *
827
+ * 旧实现是 parseFieldLines(current) → 按模板 5 个字段 rebuild 整段。
828
+ * 而 parseFieldLines 要求每行都有 ":" / ":",
829
+ * 于是段 1 里那些 "- (日期) 用户……" 的自由文本观察行全被丢弃
830
+ * —— 实测一次 merge 丢 27 行历史(这条路径有回归测试覆盖)。
831
+ *
832
+ * 现在改成:
833
+ * - 已有的行**一行都不删**
834
+ * - 新内容能对上某个模板字段(含别名)→ **就地替换那一行**
835
+ * - 对不上 → **追加**(模板字段插到模板字段区的位置,其余追加到末尾)
836
+ * - 新内容不是「键:值」格式 → 当作自由文本追加
837
+ */
838
+ function mergeBasicSection(
839
+ current: string,
840
+ incoming: string,
841
+ ): { text: string; changed: boolean } {
842
+ const lines = current ? current.split("\n").filter((l) => l.trim()) : [];
843
+ const incomingFields = parseFieldLines(incoming);
844
+
845
+ // 新内容不是「键:值」格式 —— 当自由文本追加
846
+ if (incomingFields.size === 0) {
847
+ const add = incoming.trim();
848
+ if (!add) return { text: current, changed: false };
849
+ return { text: [...lines, add].join("\n"), changed: true };
850
+ }
851
+
852
+ const keyOf = (line: string): string | null => {
853
+ const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
854
+ return m ? canonicalBasicKey(m[1]) : null;
855
+ };
856
+ const valueOf = (line: string): string => {
857
+ const m = line.match(/^-?\s*(\S+?)\s*[::]\s*(.+)$/);
858
+ return m ? m[2].trim() : "";
859
+ };
860
+
861
+ let changed = false;
862
+ for (const [rawKey, rawValue] of incomingFields) {
863
+ const value = rawValue.trim();
864
+ if (!value || value === "未知" || value === "(暂无)") continue;
865
+
866
+ const key = canonicalBasicKey(rawKey);
867
+ const idx = lines.findIndex((l) => keyOf(l) === key);
868
+
869
+ if (idx >= 0) {
870
+ // 已有同名字段 → 就地替换(不改动其它行)
871
+ if (valueOf(lines[idx]) !== value) {
872
+ lines[idx] = `- ${key}:${value}`;
873
+ changed = true;
874
+ }
875
+ continue;
876
+ }
877
+
878
+ // 新字段
879
+ const newLine = `- ${key}:${value}`;
880
+ if ((BASIC_TEMPLATE_KEYS as readonly string[]).includes(key)) {
881
+ // 模板字段插到模板字段区的末尾(保持模板顺序);一个都没有就插最前面
882
+ let insertAt = 0;
883
+ for (let i = 0; i < lines.length; i++) {
884
+ const k = keyOf(lines[i]);
885
+ if (k && (BASIC_TEMPLATE_KEYS as readonly string[]).includes(k)) {
886
+ insertAt = i + 1;
887
+ }
888
+ }
889
+ lines.splice(insertAt, 0, newLine);
890
+ } else {
891
+ lines.push(newLine);
892
+ }
893
+ changed = true;
894
+ }
895
+
896
+ return { text: lines.join("\n"), changed };
897
+ }
898
+
899
+ /**
900
+ * v0.21 融合策略:
901
+ * - 段 1 基本信息:结构化字段更新
902
+ * - 段 2 沟通风格:append + 日期 + 滚动上限 30
903
+ * - 段 6 近期变化:append + 日期 + 滚动上限 30
904
+ * - 段 3/4/5:syncFromSources 摘要(这里不动)
905
+ */
906
+ /** 段 6 里「带日期的事件行」长什么样:`- (2026-11-17) xxx` */
907
+ const DATED_LINE_RE = /^\s*-\s*\(\d{4}-\d{2}-\d{2}\)/;
908
+
909
+ /**
910
+ * 段 6 的**保留式合并**(v0.22.1 修复)。
911
+ *
912
+ * 背景 —— 段 6 有两个写入者,语义互相打架:
913
+ * - mergeProfileUpdate:追加 `- (日期) 内容` 行
914
+ * - syncFromSources:用 LLM 摘要**整段覆盖**
915
+ * 结果是这里追加的行活不过下一次画像加载(被 sync 抹掉),
916
+ * 段 6 里从来留不下任何累积记录。
917
+ *
918
+ * 这与 v0.21.1 修的「段 1 一次 merge 丢 27 行历史」是同一类问题,
919
+ * 只是段 1 当初改成了保留式合并,段 6 一直没改。
920
+ *
921
+ * 现在:
922
+ * - 已有的行**一行都不删**
923
+ * - 新内容按 `- (日期) 内容` 追加到末尾
924
+ * - 内容(忽略空白)已存在 → 不重复追加
925
+ * - 上限 40 行,防止无限增长
926
+ */
927
+ function mergeRecentSection(
928
+ current: string,
929
+ incoming: string,
930
+ dateStr: string,
931
+ ): { text: string; changed: boolean } {
932
+ const isEmpty =
933
+ !current.trim() ||
934
+ current === "(暂无)" ||
935
+ current.startsWith("(暂无");
936
+ const lines = isEmpty
937
+ ? []
938
+ : current.split("\n").filter((l) => l.trim());
939
+
940
+ const content = incoming.trim();
941
+ if (!content) return { text: current, changed: false };
942
+
943
+ // 去重:内容(忽略空白)已经出现在某一行里 → 不重复追加
944
+ const norm = (s: string) => s.replace(/\s+/g, "");
945
+ const key = norm(content).slice(0, 30);
946
+ if (key && lines.some((l) => norm(l).includes(key))) {
947
+ return { text: current, changed: false };
948
+ }
949
+
950
+ lines.push(`- (${dateStr}) ${content}`);
951
+ return { text: lines.slice(-40).join("\n"), changed: true };
952
+ }
953
+
954
+ /**
955
+ * 用新的摘要刷新段 6 的「趋势部分」,但**保留带日期的事件行**。
956
+ *
957
+ * 段 6 里其实混着两类内容:
958
+ * - `**最近变化趋势:**` 下面的趋势 bullet → LLM 摘要,可以刷新
959
+ * - `- (YYYY-MM-DD) ...` 的事件行 → merge 逐次追加,**不能丢**
960
+ *
961
+ * 早期实现是整段覆盖,把两类一起冲掉(v0.22.1 修复)。
962
+ * 这里拆开处理:趋势部分整块替换,日期行原样留在后面。
963
+ */
964
+ function refreshRecentTrends(
965
+ current: string,
966
+ newBody: string,
967
+ ): { text: string; changed: boolean } {
968
+ const dated = current
969
+ .split("\n")
970
+ .filter((l) => DATED_LINE_RE.test(l));
971
+ const body = newBody.split("\n").filter((l) => l.trim());
972
+ const next = [...body, ...dated].join("\n");
973
+ return { text: next, changed: next !== current };
974
+ }
975
+
976
+ export function mergeProfileUpdate(
977
+ profile: Profile,
978
+ update: ProfileUpdate,
979
+ now: Date = new Date(),
980
+ ): boolean {
981
+ let changed = false;
982
+ const dateStr = now.toISOString().slice(0, 10);
983
+
984
+ // 段 1 基本信息 —— 保留式合并,不丢任何已有行(v0.21.1 修复)
985
+ const basicIncoming = update["基本信息"];
986
+ if (basicIncoming && basicIncoming.trim()) {
987
+ const current = profile.sections["基本信息"] ?? "";
988
+ const { text, changed: basicChanged } = mergeBasicSection(
989
+ current,
990
+ basicIncoming,
991
+ );
992
+ if (basicChanged) {
993
+ profile.sections["基本信息"] = text;
994
+ changed = true;
995
+ }
996
+ }
997
+
998
+ // 段 2 沟通风格
999
+ const styleIncoming = update["沟通风格"];
1000
+ if (styleIncoming && styleIncoming.trim()) {
1001
+ const current = profile.sections["沟通风格"] ?? "";
1002
+ const incoming = styleIncoming.trim();
1003
+ const isEmpty = !current.trim() || current === "(暂无)" || current.startsWith("(暂无");
1004
+ const isDup = current.replace(/\s+/g, "").includes(incoming.replace(/\s+/g, "").slice(0, 30));
1005
+ if (!isEmpty && isDup) {
1006
+ // dup
1007
+ } else {
1008
+ const lines = isEmpty ? [] : current.split("\n").filter((l) => l.trim());
1009
+ lines.push(`- (${dateStr}) ${incoming}`);
1010
+ profile.sections["沟通风格"] = lines.slice(-30).join("\n");
1011
+ changed = true;
1012
+ }
1013
+ }
1014
+
1015
+ // 段 6 近期变化 —— 保留式合并,不丢任何已有行(v0.22.1 修复)
1016
+ const recentIncoming = update["近期变化"];
1017
+ if (recentIncoming && recentIncoming.trim()) {
1018
+ const current = profile.sections["近期变化"] ?? "";
1019
+ const { text, changed: recentChanged } = mergeRecentSection(
1020
+ current,
1021
+ recentIncoming,
1022
+ dateStr,
1023
+ );
1024
+ if (recentChanged) {
1025
+ profile.sections["近期变化"] = text;
1026
+ changed = true;
1027
+ }
1028
+ }
1029
+
1030
+ return changed;
1031
+ }
1032
+
1033
+ // =====================================================================
1034
+ // 一站式入口
1035
+ // =====================================================================
1036
+
1037
+ export async function maybeUpdateProfile(
1038
+ dataDir: string,
1039
+ provider: ModelProvider,
1040
+ recentMessages: { role: string; content: string }[],
1041
+ options?: {
1042
+ userId?: string;
1043
+ memoryDir?: string;
1044
+ timeline?: Timeline;
1045
+ },
1046
+ ): Promise<{
1047
+ updated: boolean;
1048
+ profile: Profile;
1049
+ changes?: { section: ProfileSection; value: string }[];
1050
+ }> {
1051
+ try {
1052
+ const profile = await loadProfile(dataDir, { ...options, provider });
1053
+ const update = await extractProfileUpdate(provider, recentMessages);
1054
+
1055
+ const sectionsBefore = new Map<ProfileSection, string>();
1056
+ for (const s of ["基本信息", "沟通风格", "近期变化"] as ProfileSection[]) {
1057
+ sectionsBefore.set(s, profile.sections[s] ?? "");
1058
+ }
1059
+
1060
+ let changed = false;
1061
+ if (Object.keys(update).length > 0) {
1062
+ changed = mergeProfileUpdate(profile, update);
1063
+ }
1064
+
1065
+ // sync 已由上面的 loadProfile 触发过(它内部就会调 syncFromSources),
1066
+ // 这里**不再重复调**:
1067
+ // - 重复调不会带来更新的摘要(merge 期间没有新记忆产生,段 3/4/5 的输入没变)
1068
+ // - 反而多花一次 LLM 调用
1069
+ // - 而且它会覆盖段 6 —— 早期实现里就是这一步把 mergeProfileUpdate
1070
+ // 刚追加的 "- (日期) ..." 行当场抹掉的(v0.22.1 修复)
1071
+
1072
+ await saveProfile(profile);
1073
+
1074
+ const changes: { section: ProfileSection; value: string }[] = [];
1075
+ for (const s of ["基本信息", "沟通风格", "近期变化"] as ProfileSection[]) {
1076
+ const after = profile.sections[s] ?? "";
1077
+ const before = sectionsBefore.get(s) ?? "";
1078
+ if (after !== before) {
1079
+ const newLines = after
1080
+ .split("\n")
1081
+ .map((l) => l.trim())
1082
+ .filter((l) => l && !before.includes(l));
1083
+ if (newLines.length > 0) {
1084
+ changes.push({ section: s, value: newLines.join(" | ") });
1085
+ }
1086
+ }
1087
+ }
1088
+
1089
+ return { updated: changed, profile, changes };
1090
+ } catch (e) {
1091
+ console.error(`[profile] 更新失败:`, (e as Error).message);
1092
+ const profile = await loadProfile(dataDir, options);
1093
+ return { updated: false, profile };
1094
+ }
1095
+ }