feiyu-brain 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -10,7 +10,7 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import crypto from 'node:crypto';
12
12
 
13
- import { birthFromCard } from './core/extract.js';
13
+ import { birthFromCard, lintCard } from './core/extract.js';
14
14
  import { brief, decay, evolve, shed, weightReport } from './core/persona.js';
15
15
  import { styleVector, flowLevel, flowName, hashTraits, mulberry32 } from './core/derive.js';
16
16
  import { createBody, chooseBody, bodyLine, canDo, hasCapability, CAPABILITY, BODY_KINDS, BODY_PROFILES, recordAction } from './core/body.js';
@@ -21,6 +21,8 @@ import { check } from './core/invariants.js';
21
21
  import { toCue, toObservation, shouldObserve, normalizeEvent } from './core/event.js';
22
22
  import * as emotion from './core/emotion.js';
23
23
  import { makeCard, addCard, shouldCompact } from './core/memory.js';
24
+ import { parseAny, dedupe, MIGRATE_FORMATS } from './core/migrate.js';
25
+ import { dayKey, dayDigest } from './core/diary.js';
24
26
  import { driverFor } from './core/driver.js';
25
27
  import {
26
28
  recordSeen, recallApp, appTaste, appSummary, similarSeen, emptyApps,
@@ -28,12 +30,17 @@ import {
28
30
  } from './core/apps.js';
29
31
  import {
30
32
  ROOT, loadBrain, saveBrain, appendAudit, readAudit, listBrains,
31
- setDataDir, setRoleDir, dataDir, roleDir,
33
+ setDataDir, setRoleDir, dataDir, roleDir, brainDir, dataDirSource, isDataDirInsidePackage,
32
34
  } from './store.js';
33
35
 
34
36
  const DEFAULT_ID = 'default';
35
37
  const cache = new Map();
36
38
 
39
+ /* 全局开关(configure 改) */
40
+ let shadowMode = false; // 影子模式:只写 audit,不动权重、不落盘
41
+ let ttlPolicy = 'hard'; // hard | summarize | archive | off
42
+ let moodPolicy = 'brain'; // 情绪双源:brain(脑说了算)| host(宿主说了算)| blend(各一半)
43
+
37
44
  function nowMs() {
38
45
  return Date.now();
39
46
  }
@@ -46,10 +53,67 @@ function logOnce(msg) {
46
53
  try { console.warn(msg); } catch { /* 没有 console 也不影响 */ }
47
54
  }
48
55
 
49
- /** 宿主初始化:指定数据目录和角色卡目录 */
50
- export function configure({ dataDir: d, roleDir: r } = {}) {
56
+ /**
57
+ * 宿主初始化:指定数据目录和角色卡目录。
58
+ *
59
+ * configure({ dataDir, roleDir })
60
+ * configure({ shadow: true }) 影子模式:observe 只留审计,不动人设、不落盘
61
+ * configure({ ttlPolicy: 'off' }) hard(默认) | summarize(过期前压卡片) | off(永不遗忘)
62
+ */
63
+ export function configure({ dataDir: d, roleDir: r, shadow, ttl, mood } = {}) {
51
64
  if (d) setDataDir(d);
52
65
  if (r) setRoleDir(r);
66
+ if (typeof shadow === 'boolean') shadowMode = shadow;
67
+ if (ttl && ['hard', 'summarize', 'archive', 'off'].includes(ttl)) ttlPolicy = ttl;
68
+ if (mood && ['brain', 'host', 'blend'].includes(mood)) moodPolicy = mood;
69
+ }
70
+
71
+ export function runtimeOptions() {
72
+ return {
73
+ shadow: shadowMode,
74
+ ttlPolicy,
75
+ moodPolicy,
76
+ dataDir: dataDir(),
77
+ dataDirSource: dataDirSource(),
78
+ dataDirInsidePackage: isDataDirInsidePackage(),
79
+ roleDir: roleDir(),
80
+ };
81
+ }
82
+
83
+ /**
84
+ * 情绪双源仲裁。
85
+ *
86
+ * 宿主往往已经有自己的情绪系统(比如 state/emotion.json)。两边都能改情绪时必须定个优先级:
87
+ *
88
+ * brain (默认) 宿主推过来的直接忽略,脑说了算
89
+ * host 情绪以宿主为准,`feel()` 只算不写
90
+ * blend 各占一半
91
+ */
92
+ export function syncMood(id = DEFAULT_ID, pad = [], { policy } = {}) {
93
+ const brain = ensureBrain(id);
94
+ const p = ['brain', 'host', 'blend'].includes(policy) ? policy : moodPolicy;
95
+ const host = [0, 1, 2].map((i) => {
96
+ const v = Number(pad?.[i]);
97
+ return Number.isFinite(v) ? Math.max(-1, Math.min(1, v)) : 0;
98
+ });
99
+
100
+ if (p === 'brain') {
101
+ return { ok: true, ignored: true, policy: p, affect: brain.affect };
102
+ }
103
+
104
+ const cur = [Number(brain.affect?.p) || 0, Number(brain.affect?.a) || 0, Number(brain.affect?.d) || 0];
105
+ const next = p === 'host' ? host : cur.map((c, i) => Number(((c + host[i]) / 2).toFixed(4)));
106
+
107
+ brain.affect = {
108
+ ...brain.affect,
109
+ p: next[0],
110
+ a: next[1],
111
+ d: next[2],
112
+ moodSource: p,
113
+ };
114
+ saveBrain(brain);
115
+ appendAudit(id, { kind: 'mood-sync', policy: p, pad: next });
116
+ return { ok: true, ignored: false, policy: p, affect: brain.affect };
53
117
  }
54
118
 
55
119
  /** 读角色卡:优先显式名字,否则读 state/current-role.json。 */
@@ -138,7 +202,13 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
138
202
  // 身体:手机 / 平板 / 电脑。没指定就按人设算——好动的摸手机,爱折腾的开电脑。
139
203
  body: createBody({ kind: body ?? chooseBody(traits, {}, mulberry32(hashTraits(traits))) }),
140
204
  patience: 1,
141
- meta: { lastSettle: nowMs(), observations: 0, version: '1.1.0' },
205
+ meta: {
206
+ lastSettle: nowMs(),
207
+ observations: 0,
208
+ version: '1.5.0',
209
+ shadow: shadowMode,
210
+ contractWarnings: [],
211
+ },
142
212
  };
143
213
 
144
214
  brain.self.styleName = dominantStyle(brain.self.style);
@@ -171,39 +241,77 @@ export function getBrief(id = DEFAULT_ID) {
171
241
  * 接受两种入参:
172
242
  * - 通用事件 { sender, text, ... }
173
243
  * - 线索 { who, words }
244
+ *
245
+ * 第三参数用来"点菜"——叠加到别人已有的系统里时,只取你要的那几段:
246
+ *
247
+ * wakeLine(id, cue) // 全给(默认)
248
+ * wakeLine(id, cue, { sections: ['mood'] }) // 只要心情,约 20 字
249
+ * wakeLine(id, cue, { sections: ['mood','memory'], budget: 300 })
250
+ *
251
+ * sections 可选:persona / flow / body / mood / memory / search
252
+ * budget 是**总字数上限**,超了就从低优先级的段开始砍(persona 保底不砍)。
174
253
  */
175
- export function wakeLine(id = DEFAULT_ID, eventOrCue = null) {
254
+ export const WAKE_SECTIONS = ['persona', 'flow', 'body', 'mood', 'memory', 'search'];
255
+ /** 预算不够时的砍法:越靠后越先砍 */
256
+ const WAKE_PRIORITY = ['persona', 'mood', 'flow', 'memory', 'body', 'search'];
257
+
258
+ export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
176
259
  const brain = ensureBrain(id);
177
260
  if (!brain.persona.brief) refreshBrief(brain);
178
261
 
262
+ const want = Array.isArray(opts?.sections) && opts.sections.length
263
+ ? new Set(opts.sections.filter((s) => WAKE_SECTIONS.includes(s)))
264
+ : new Set(WAKE_SECTIONS);
265
+ const budget = Number.isFinite(opts?.budget) ? Number(opts.budget) : Infinity;
266
+
179
267
  const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
180
268
  brain.state.flow = level;
181
- const parts = [`【此刻的她】${brain.persona.brief}`];
269
+
270
+ const seg = { persona: `【此刻的她】${brain.persona.brief}` };
271
+ if (level !== 1) seg.flow = `【意识流】${flowName(level)}`;
272
+
182
273
  const bodyText = bodyLine(brain.body);
183
- if (bodyText) parts.push(`【手上的东西】${bodyText}`);
274
+ if (bodyText) seg.body = `【手上的东西】${bodyText}`;
184
275
 
185
- if (level !== 1) parts.push(`【意识流】${flowName(level)}`);
276
+ // 心情段:还没学会词的时候不能说"不知道",要给出身体感受——
277
+ // 否则只要心情的宿主会拿到一个空段。
186
278
  const mood = brain.affect?.mood;
187
- if (mood && mood !== '平静' && mood !== '说不上来') parts.push(`【心情】${mood}`);
279
+ if (mood && mood !== '平静') {
280
+ seg.mood = mood === '说不上来'
281
+ ? `【心情】${emotion.describeSensation([brain.affect.p ?? 0, brain.affect.a ?? 0, brain.affect.d ?? 0])}`
282
+ : `【心情】${mood}`;
283
+ }
188
284
 
189
285
  const cue = eventOrCue?.who !== undefined ? eventOrCue : toCue(eventOrCue);
190
286
  if (cue) {
191
287
  const hit = retrieve(cue, brain.memory);
192
- if (hit.text) parts.push(`【想到的】\n${hit.text}`);
288
+ if (hit.text) seg.memory = `【想到的】\n${hit.text}`;
193
289
 
194
290
  // 外部检索器(向量/图谱):同步读缓存,不 await
195
291
  if (extraRetriever) {
196
292
  try {
197
293
  const extra = extraRetriever(cue, brain.memory) ?? [];
198
294
  const lines = (Array.isArray(extra) ? extra : []).filter(Boolean).slice(0, 3);
199
- if (lines.length) parts.push(`【搜到的】\n${lines.join('\n')}`);
295
+ if (lines.length) seg.search = `【搜到的】\n${lines.join('\n')}`;
200
296
  } catch (e) {
201
297
  // 检索器坏了不能拖垮唤醒
202
298
  logOnce(`[brain] 外部检索器出错(已忽略):${e?.message ?? e}`);
203
299
  }
204
300
  }
205
301
  }
206
- return parts.join('\n');
302
+
303
+ const out = [];
304
+ let used = 0;
305
+ for (const key of WAKE_PRIORITY) {
306
+ if (!want.has(key)) continue;
307
+ const text = seg[key];
308
+ if (!text) continue;
309
+ // persona 是根,再穷也得给;其余按预算砍
310
+ if (key !== 'persona' && used + text.length > budget) continue;
311
+ out.push(text);
312
+ used += text.length;
313
+ }
314
+ return out.join('\n');
207
315
  }
208
316
 
209
317
  /**
@@ -211,10 +319,18 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null) {
211
319
  *
212
320
  * event = { sender, text, ... } ← 适配器直接传
213
321
  * event = { consistent, conflicting, ... } ← 高级用法
322
+ *
323
+ * 第三参数 opts:
324
+ * evolve = true 记经历的同时,改人设权重(默认)
325
+ * = false **只记经历,不碰人设** —— 叠加到别人已有的人格系统时用这个,
326
+ * 免得两套各说各话、token 翻倍
327
+ * remember = true 写进记忆(默认)
214
328
  */
215
- export function observe(id = DEFAULT_ID, event = {}) {
329
+ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
216
330
  const brain = ensureBrain(id);
217
331
  const at = nowMs();
332
+ const doEvolve = opts?.evolve !== false;
333
+ const doRemember = opts?.remember !== false;
218
334
 
219
335
  const ev = event.consistent || event.conflicting || !event.sender
220
336
  ? event
@@ -223,17 +339,57 @@ export function observe(id = DEFAULT_ID, event = {}) {
223
339
  const consistent = ev.consistent ?? matchUnits(brain.persona.units, ev.text ?? '').consistent;
224
340
  const conflicting = ev.conflicting ?? matchUnits(brain.persona.units, ev.text ?? '').conflicting;
225
341
 
342
+ // ── 影子模式 ──
343
+ // 只写审计,不动人设、不进记忆、不落盘。
344
+ // 宿主可以拿它试跑一百次,确认"会长成什么样",再决定要不要真接。
345
+ // 全局开关和这条鱼自己的标记都算数——生下来之后才打开 shadow 也应该生效。
346
+ if (shadowMode || brain.meta.shadow) {
347
+ const would = brain.persona.units
348
+ .filter((u) => consistent.includes(u.id) || conflicting.includes(u.id))
349
+ .map((u) => ({
350
+ id: u.id,
351
+ from: Number(u.weight.toFixed(3)),
352
+ to: Number(Math.max(0, Math.min(1, u.weight + (consistent.includes(u.id) ? 1 : -1) * 0.01)).toFixed(3)),
353
+ }));
354
+ appendAudit(id, {
355
+ kind: 'shadow',
356
+ shadow: true,
357
+ at,
358
+ text: String(ev.text ?? ev.what ?? '').slice(0, 80),
359
+ wouldChange: would,
360
+ });
361
+ return {
362
+ brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would,
363
+ };
364
+ }
365
+
226
366
  // step:默认 1(每次 ±0.01)。只有传了 magnitude(重大转折)才放大,上限 5。
227
367
  const step = Math.max(1, Math.min(5, Number(ev.magnitude) || 1));
228
- brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
229
-
230
- // 蜕皮
231
- const sh = shed(brain.persona.units, { at });
232
- if (sh.formerSelves.length) {
233
- brain.persona.units = sh.units;
234
- brain.memory.formerSelves.push(...sh.formerSelves);
235
- for (const f of sh.formerSelves) {
236
- appendAudit(id, { kind: 'shed', id: f.id, weight: Number(f.weight.toFixed(3)), memoir: f.memoir });
368
+ if (doEvolve) {
369
+ brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
370
+
371
+ // 蜕皮
372
+ const sh = shed(brain.persona.units, { at });
373
+ if (sh.formerSelves.length) {
374
+ brain.persona.units = sh.units;
375
+ brain.memory.formerSelves.push(...sh.formerSelves);
376
+ for (const f of sh.formerSelves) {
377
+ appendAudit(id, { kind: 'shed', id: f.id, weight: Number(f.weight.toFixed(3)), memoir: f.memoir });
378
+ }
379
+ }
380
+ }
381
+
382
+ // 带情绪的事件:先让她有感受,再记下来。
383
+ // 否则 episode 记的是"这件事之前"的心情,日记里就变成时间错位。
384
+ if (doRemember && Number.isFinite(Number(ev.valence))) {
385
+ try {
386
+ feel(id, {
387
+ valence: Math.max(-1, Math.min(1, Number(ev.valence))),
388
+ intensity: Number.isFinite(Number(ev.intensity)) ? Math.max(0, Math.min(1, Number(ev.intensity))) : 0.5,
389
+ what: ev.what ?? ev.text ?? '',
390
+ });
391
+ } catch (e) {
392
+ logOnce(`[brain] 事件自带情绪但算失败(已忽略):${e?.message ?? e}`);
237
393
  }
238
394
  }
239
395
 
@@ -241,7 +397,7 @@ export function observe(id = DEFAULT_ID, event = {}) {
241
397
  const obs = ev.what
242
398
  ? ev
243
399
  : (ev.text ? { who: ev.who ?? ev.sender ?? '', what: String(ev.text).slice(0, 80), feel: ev.feel ?? '', via: ev.via ?? 'api' } : null);
244
- if (obs?.what) {
400
+ if (doRemember && obs?.what) {
245
401
  addEpisode(brain.memory, {
246
402
  who: obs.who ?? '',
247
403
  what: obs.what,
@@ -252,10 +408,11 @@ export function observe(id = DEFAULT_ID, event = {}) {
252
408
  context: ev.context ?? null,
253
409
  strategy: ev.action?.strategy ?? null,
254
410
  evidence: obs.via ?? 'chat',
411
+ source: 'live',
255
412
  }, at);
256
413
  }
257
414
 
258
- if (ev.action) {
415
+ if (doRemember && ev.action) {
259
416
  const label = attribute(ev.action, brain.memory);
260
417
  appendAudit(id, { kind: 'attribution', label, strategy: ev.action.strategy });
261
418
  brain.meta.lastLabel = label;
@@ -266,7 +423,7 @@ export function observe(id = DEFAULT_ID, event = {}) {
266
423
  }
267
424
 
268
425
  // 平台记忆:她刷到过什么(有 app 才记)
269
- if (ev.app && (ev.title || ev.text)) {
426
+ if (doRemember && ev.app && (ev.title || ev.text)) {
270
427
  recordSeen(brain.memory, ev.app, {
271
428
  title: ev.title ?? String(ev.text).slice(0, 60),
272
429
  kind: ev.kind ?? '',
@@ -277,18 +434,21 @@ export function observe(id = DEFAULT_ID, event = {}) {
277
434
 
278
435
  // ── 闭环:刷到的东西反过来改人设 ──
279
436
  // 看的解压视频多了,"懒"这条特质就真的涨一点;人设变了,下次爱看的就不一样。
280
- const { traits: nextTraits, delta } = nudgeTraits(brain.persona.traits, ev.kind ?? '', Number(ev.reaction) || 0);
281
- if (Object.keys(delta).length) {
282
- brain.persona.traits = nextTraits;
283
- brain.self.style = styleVector(nextTraits);
284
- brain.self.styleName = dominantStyle(brain.self.style);
285
- appendAudit(id, { kind: 'trait-drift', app: ev.app, contentKind: ev.kind, delta });
437
+ // evolve:false 时这条也关掉——只当记忆库用,就不该偷偷改人设。
438
+ if (doEvolve) {
439
+ const { traits: nextTraits, delta } = nudgeTraits(brain.persona.traits, ev.kind ?? '', Number(ev.reaction) || 0);
440
+ if (Object.keys(delta).length) {
441
+ brain.persona.traits = nextTraits;
442
+ brain.self.style = styleVector(nextTraits);
443
+ brain.self.styleName = dominantStyle(brain.self.style);
444
+ appendAudit(id, { kind: 'trait-drift', app: ev.app, contentKind: ev.kind, delta });
445
+ }
286
446
  }
287
447
  }
288
448
 
289
449
  // 关系记忆:互动次数
290
450
  const who = ev.who ?? ev.sender;
291
- if (who) {
451
+ if (doRemember && who) {
292
452
  const im = brain.memory.impressions[who] ?? { traits: [], count: 0, lastAt: at };
293
453
  im.count += 1;
294
454
  im.lastAt = at;
@@ -300,7 +460,7 @@ export function observe(id = DEFAULT_ID, event = {}) {
300
460
  brain.meta.lastObservationAt = at;
301
461
  refreshBrief(brain);
302
462
  saveBrain(brain);
303
- return { brain, consistent, conflicting, label: brain.meta.lastLabel };
463
+ return { brain, consistent, conflicting, label: brain.meta.lastLabel, evolved: doEvolve, remembered: doRemember };
304
464
  }
305
465
 
306
466
  /** 关键词匹配:粗但确定(中文按二元组)。 */
@@ -338,7 +498,33 @@ export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
338
498
  brain.persona.units = sh.units;
339
499
  brain.memory.formerSelves.push(...sh.formerSelves);
340
500
  }
341
- settle(brain.memory, now);
501
+
502
+ if (ttlPolicy === 'summarize' || ttlPolicy === 'archive') {
503
+ // 过期前先压一张卡片——"忘了细节,但记得大概"
504
+ const card = makeCard(brain.memory.episodes.slice(-12));
505
+ if (card) addCard(brain.memory, card);
506
+ }
507
+
508
+ const before = brain.memory.forgotten.length;
509
+ if (ttlPolicy !== 'off') settle(brain.memory, now);
510
+
511
+ // archive:过期的不算真丢,摊到 archive.jsonl 里备查,免得 brain.json 越滚越大
512
+ if (ttlPolicy === 'archive' && brain.memory.forgotten.length > before) {
513
+ try {
514
+ const newly = brain.memory.forgotten.slice(before);
515
+ fs.appendFileSync(
516
+ path.join(brainDir(id), 'archive.jsonl'),
517
+ `${newly.map((x) => JSON.stringify(x)).join('\n')}\n`,
518
+ 'utf8',
519
+ );
520
+ } catch (e) {
521
+ logOnce(`[brain] 归档写入失败(已忽略):${e?.message ?? e}`);
522
+ }
523
+ }
524
+ if (brain.memory.forgotten.length > 500) {
525
+ brain.memory.forgotten = brain.memory.forgotten.slice(-500);
526
+ }
527
+
342
528
  brain.meta.lastSettle = now;
343
529
  refreshBrief(brain);
344
530
  saveBrain(brain);
@@ -346,6 +532,100 @@ export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
346
532
  return brain;
347
533
  }
348
534
 
535
+ /* ── 快照 / 回滚 ─────────────────────────────────────────────── */
536
+
537
+ /** 给现在的她存个档,坏了能退回来。 */
538
+ export function snapshotBrain(id = DEFAULT_ID, name = '') {
539
+ const brain = ensureBrain(id);
540
+ const dir = path.join(brainDir(id), 'snapshots');
541
+ fs.mkdirSync(dir, { recursive: true });
542
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
543
+ const file = path.join(dir, `${name || stamp}.json`);
544
+ fs.writeFileSync(file, JSON.stringify(brain, null, 2), 'utf8');
545
+ appendAudit(id, { kind: 'snapshot', name: path.basename(file, '.json') });
546
+ return { ok: true, name: path.basename(file, '.json'), file };
547
+ }
548
+
549
+ /** 退回到某个快照。权重逐条还原。 */
550
+ export function restoreBrain(id = DEFAULT_ID, name = '') {
551
+ if (!name) return { ok: false, reason: '要说退回到哪个快照' };
552
+ const dir = path.join(brainDir(id), 'snapshots');
553
+ const file = name.endsWith('.json') ? path.join(dir, name) : path.join(dir, `${name}.json`);
554
+ if (!fs.existsSync(file)) {
555
+ const list = listSnapshots(id).map((s) => s.name);
556
+ return { ok: false, reason: `没有这个快照:${name}`, available: list };
557
+ }
558
+ const data = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
559
+ data.id = id;
560
+ saveBrain(data);
561
+ cache.set(id, data);
562
+ appendAudit(id, { kind: 'restore', name });
563
+ return { ok: true, restored: name, check: identityCheck(id) };
564
+ }
565
+
566
+ export function listSnapshots(id = DEFAULT_ID) {
567
+ const dir = path.join(brainDir(id), 'snapshots');
568
+ if (!fs.existsSync(dir)) return [];
569
+ return fs.readdirSync(dir)
570
+ .filter((f) => f.endsWith('.json'))
571
+ .map((f) => ({
572
+ name: f.replace(/\.json$/, ''),
573
+ size: fs.statSync(path.join(dir, f)).size,
574
+ at: fs.statSync(path.join(dir, f)).mtimeMs,
575
+ }))
576
+ .sort((a, b) => b.at - a.at);
577
+ }
578
+
579
+ /* ── 导入历史 ───────────────────────────────────────────────── */
580
+
581
+ /**
582
+ * 把宿主已有的历史经历灌进来。
583
+ *
584
+ * 宿主那边往往已经有日记/经验库,不导进来就是"两套记忆各记一套",
585
+ * 用户问「你记得吗」会出现两个答案。
586
+ *
587
+ * @param {Array} list [{ who, text|what, at, feel, mood, emotion }]
588
+ */
589
+ export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' } = {}) {
590
+ const brain = ensureBrain(id);
591
+ let imported = 0;
592
+ let skipped = 0;
593
+ const touched = new Map(); // who → 次数
594
+
595
+ for (const it of Array.isArray(list) ? list : []) {
596
+ const what = String(it?.text ?? it?.what ?? '').trim();
597
+ if (!what) { skipped += 1; continue; }
598
+ const at = Number(it?.at) || nowMs();
599
+ addEpisode(brain.memory, {
600
+ who: it.who ?? '',
601
+ what: what.slice(0, 140),
602
+ feel: it.feel ?? '',
603
+ mood: it.mood ?? '',
604
+ emotion: Number(it.emotion) || 0,
605
+ outcome: it.outcome ?? null,
606
+ context: it.context ?? null,
607
+ strategy: it.strategy ?? null,
608
+ evidence: it.via ?? source,
609
+ source, // live | import
610
+ }, at);
611
+ imported += 1;
612
+ const who = String(it.who ?? '').trim();
613
+ if (who) touched.set(who, (touched.get(who) ?? 0) + 1);
614
+ }
615
+
616
+ // 搬进来的也要"认识这个人"——否则检索里永远"还不熟"
617
+ for (const [who, n] of touched) {
618
+ const im = brain.memory.impressions[who] ?? { traits: [], count: 0, lastAt: 0 };
619
+ im.count += n;
620
+ im.lastAt = Math.max(Number(im.lastAt) || 0, nowMs());
621
+ brain.memory.impressions[who] = im;
622
+ }
623
+
624
+ saveBrain(brain);
625
+ appendAudit(id, { kind: 'import-episodes', imported, skipped, source, people: touched.size });
626
+ return { ok: true, imported, skipped, people: touched.size, total: brain.memory.episodes.length };
627
+ }
628
+
349
629
  /** 记一次"想起"(续命)。 */
350
630
  export function touch(id, key, { pool = 'facts' } = {}) {
351
631
  const brain = ensureBrain(id);
@@ -405,11 +685,20 @@ export function feel(id = DEFAULT_ID, event = {}, { blend = 0.65 } = {}) {
405
685
  // 情绪有余温:新感受占 65%,上一次剩 35%。
406
686
  // 否则每件事都把心情冲成新的,人会像开关而不是像有情绪惯性的活物。
407
687
  const k = Math.max(0, Math.min(1, Number(blend)));
688
+
689
+ // 双源仲裁:宿主说了算时,只算不写——免得两套情绪系统互相覆盖
690
+ if (moodPolicy === 'host') {
691
+ brain.meta.lastFeel = { at: Date.now(), pad: r.pad, label: r.label, stage: r.stage, text: r.text, applied: false };
692
+ saveBrain(brain);
693
+ return { ...r, applied: false, reason: 'moodPolicy=host,情绪以宿主为准,这里只算不写' };
694
+ }
695
+
408
696
  const prev = brain.affect ?? {};
697
+ const effBlend = moodPolicy === 'blend' ? Math.min(k, 0.5) : k;
409
698
  const mix = (next, before) => {
410
699
  const old = Number(before);
411
700
  const base = Number.isFinite(old) ? old : 0;
412
- return Number((next * k + base * (1 - k)).toFixed(4));
701
+ return Number((next * effBlend + base * (1 - effBlend)).toFixed(4));
413
702
  };
414
703
 
415
704
  brain.affect = {
@@ -419,11 +708,12 @@ export function feel(id = DEFAULT_ID, event = {}, { blend = 0.65 } = {}) {
419
708
  // 名字按**这次**的感受叫:旧的余温不该拖住命名
420
709
  mood: r.label.kind === 'word' ? r.label.word : (r.label.kind === 'variant' ? `${r.label.word}(变体)` : '说不上来'),
421
710
  // 余温多少,方便调试时看"她还没缓过来"
422
- carryover: Number((1 - k).toFixed(2)),
711
+ carryover: Number((1 - effBlend).toFixed(2)),
712
+ moodSource: moodPolicy,
423
713
  };
424
- brain.meta.lastFeel = { at: Date.now(), pad: r.pad, blended: [brain.affect.p, brain.affect.a, brain.affect.d], label: r.label, stage: r.stage, text: r.text };
714
+ brain.meta.lastFeel = { at: Date.now(), pad: r.pad, blended: [brain.affect.p, brain.affect.a, brain.affect.d], label: r.label, stage: r.stage, text: r.text, applied: true };
425
715
  saveBrain(brain);
426
- return { ...r, blended: [brain.affect.p, brain.affect.a, brain.affect.d] };
716
+ return { ...r, applied: true, blended: [brain.affect.p, brain.affect.a, brain.affect.d] };
427
717
  }
428
718
 
429
719
  /**
@@ -703,6 +993,391 @@ export function seenBefore(id = DEFAULT_ID, text = '') {
703
993
  return similarSeen(ensureBrain(id).memory, text);
704
994
  }
705
995
 
996
+ /* ── 身份体检:换脑之后还是不是她 ─────────────────────────────── */
997
+
998
+ /**
999
+ * 「我还是我吗」不用哲学,查三样东西在不在:
1000
+ * ① 记忆 跟谁发生过什么
1001
+ * ② 自我叙事 她以为的自己
1002
+ * ③ 关系 认谁、怎么称呼
1003
+ *
1004
+ * 三个都在 → 是她;缺一个 → 像她但不是她;全没有 → 只是同名。
1005
+ */
1006
+ export function identityCheck(id = DEFAULT_ID) {
1007
+ const b = ensureBrain(id);
1008
+ const episodes = b.memory.episodes.length;
1009
+ const people = Object.keys(b.memory.impressions ?? {}).length;
1010
+ const cards = (b.memory.cards ?? []).length;
1011
+ const narrative = Boolean(b.self?.narrative);
1012
+ const relation = Boolean(b.relation?.type);
1013
+
1014
+ const marks = [episodes + people > 0, narrative, relation];
1015
+ const verdict = marks.every(Boolean)
1016
+ ? '是她'
1017
+ : marks.some(Boolean) ? '像她,但不是她' : '同名而已';
1018
+
1019
+ return {
1020
+ id,
1021
+ memory: { episodes, people, cards },
1022
+ narrative,
1023
+ narrativeText: b.self?.narrative ?? '',
1024
+ relation: relation ? { type: b.relation.type, address: b.relation.address ?? '' } : null,
1025
+ verdict,
1026
+ };
1027
+ }
1028
+
1029
+ /* ── 脑包:把"她"打包带走 ────────────────────────────────────── */
1030
+
1031
+ export const PACK_FORMAT = 'feiyu-brainpack/1';
1032
+
1033
+ /**
1034
+ * 导出"她"——人设 + 记忆 + 关系 + 词表 + 情绪。
1035
+ * **换脑不是换人的前提是这个包带得走。**
1036
+ */
1037
+ export function exportPack(id = DEFAULT_ID, { includeMemory = true } = {}) {
1038
+ const b = ensureBrain(id);
1039
+ return {
1040
+ format: PACK_FORMAT,
1041
+ exportedAt: nowMs(),
1042
+ id: b.id,
1043
+ born: b.born,
1044
+ roleCard: b.roleCard,
1045
+ persona: b.persona,
1046
+ self: b.self,
1047
+ relation: b.relation,
1048
+ vocab: b.vocab ?? {},
1049
+ affect: b.affect ?? {},
1050
+ body: b.body ? { kind: b.body.kind, ownership: b.body.ownership } : null,
1051
+ patience: b.patience,
1052
+ ...(includeMemory ? { memory: b.memory } : {}),
1053
+ };
1054
+ }
1055
+
1056
+ /**
1057
+ * 把包装回来。
1058
+ *
1059
+ * 只认 `feiyu-brainpack/1`;别的格式(aurobot / 口袋 / TavernCard)需要先写迁移器转成这个格式。
1060
+ * 宁可拒收,也不假装兼容。
1061
+ */
1062
+ export function importPack(pack, { id, keepMemory = true } = {}) {
1063
+ if (!pack || pack.format !== PACK_FORMAT) {
1064
+ return { ok: false, reason: `不是 ${PACK_FORMAT} 格式,先用迁移器转一下` };
1065
+ }
1066
+ const units = pack.persona?.units ?? [];
1067
+ if (!units.length) return { ok: false, reason: '包里没有命题,导进来也是空壳' };
1068
+
1069
+ const targetId = id ?? pack.id ?? DEFAULT_ID;
1070
+ const identity = units.find((u) => u.kind === 'identity')?.text ?? `你是${pack.roleCard ?? targetId}`;
1071
+ const cardText = [identity, ...units.filter((u) => u.kind !== 'identity').map((u) => `- ${u.text}`)].join('\n');
1072
+
1073
+ const brain = birth({
1074
+ id: targetId,
1075
+ relation: pack.relation?.type ?? 'parent',
1076
+ address: pack.relation?.address ?? '',
1077
+ cardText,
1078
+ cardName: pack.roleCard ?? targetId,
1079
+ });
1080
+
1081
+ // 用包里的原样覆盖:保留命题 id、权重、来源——这些是"她"的部分
1082
+ brain.persona = { ...pack.persona, brief: '' };
1083
+ brain.self = { ...brain.self, ...(pack.self ?? {}) };
1084
+ brain.self.style = brain.self.style ?? styleVector(brain.persona.traits);
1085
+ brain.self.styleName = dominantStyle(brain.self.style);
1086
+ if (pack.relation) brain.relation = pack.relation;
1087
+ brain.vocab = pack.vocab ?? {};
1088
+ brain.affect = pack.affect ?? brain.affect;
1089
+ if (Number.isFinite(pack.patience)) brain.patience = pack.patience;
1090
+ if (keepMemory && pack.memory) brain.memory = { ...emptyMemory(), ...pack.memory };
1091
+ if (pack.body?.kind) {
1092
+ try { brain.body = createBody({ kind: pack.body.kind, ownership: pack.body.ownership }); } catch { /* 身体坏了不影响她是谁 */ }
1093
+ }
1094
+ if (Number.isFinite(pack.born)) brain.born = pack.born;
1095
+
1096
+ refreshBrief(brain);
1097
+ saveBrain(brain);
1098
+ cache.set(targetId, brain);
1099
+ appendAudit(targetId, { kind: 'import-pack', from: pack.id ?? '?', units: units.length, memory: keepMemory });
1100
+
1101
+ return { ok: true, id: targetId, units: units.length, check: identityCheck(targetId) };
1102
+ }
1103
+
1104
+ /* ── 记忆搬迁:老鱼把过去搬进来 ─────────────────────────────── */
1105
+
1106
+ /**
1107
+ * 把宿主已有的记忆搬进脑子。
1108
+ *
1109
+ * 这是**有损转换**,不是复制:宿主日记是流水账,脑子里存的是"她记得的事"。
1110
+ * 每条都标 source:'import',将来能分清哪些是亲历、哪些是搬来的。
1111
+ *
1112
+ * migrateMemory('old', { text, format: 'jsonl' }) // 真搬
1113
+ * migrateMemory('old', { text, format: 'days', dryRun: true }) // 只看会搬多少
1114
+ */
1115
+ export function migrateMemory(id = DEFAULT_ID, { text = '', format = 'jsonl', dryRun = false } = {}) {
1116
+ const brain = ensureBrain(id);
1117
+ const parsed = parseAny(String(text ?? ''), format);
1118
+ const d = dedupe(parsed.episodes, { existing: brain.memory.episodes });
1119
+
1120
+ const ats = d.episodes.map((e) => e.at).filter((t) => t > 0).sort((a, b) => a - b);
1121
+ const report = {
1122
+ format,
1123
+ parsed: parsed.episodes.length,
1124
+ duplicated: d.duplicated,
1125
+ willImport: d.episodes.length,
1126
+ parseErrors: parsed.errors.slice(0, 20),
1127
+ parseErrorCount: parsed.errors.length,
1128
+ span: ats.length ? { from: new Date(ats[0]).toISOString().slice(0, 10), to: new Date(ats[ats.length - 1]).toISOString().slice(0, 10) } : null,
1129
+ };
1130
+
1131
+ if (dryRun) return { ok: true, dryRun: true, report };
1132
+
1133
+ const r = importEpisodes(id, d.episodes, { source: 'import' });
1134
+ return { ok: true, dryRun: false, report, imported: r.imported, total: r.total };
1135
+ }
1136
+
1137
+ /** 读归档(过期但没丢的那些) */
1138
+ export function readArchive(id = DEFAULT_ID, limit = 20) {
1139
+ const file = path.join(brainDir(id), 'archive.jsonl');
1140
+ if (!fs.existsSync(file)) return [];
1141
+ const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
1142
+ return lines.slice(-limit).map((l) => {
1143
+ try { return JSON.parse(l); } catch { return { raw: l }; }
1144
+ });
1145
+ }
1146
+
1147
+ /* ── 全量整合:把宿主所有记忆并成一份 ───────────────────────── */
1148
+
1149
+ /** 脑里最多存多少条经历,超了自动压卡片 + 归档(防止 brain.json 无限膨胀) */
1150
+ export const MAX_EPISODES = 5000;
1151
+
1152
+ /**
1153
+ * 容量保护:最老的一批压成卡片,原文进 archive.jsonl。
1154
+ * 只留最近 MAX_EPISODES 条在检索池里——不变大,也不真丢。
1155
+ */
1156
+ function enforceCapacity(brain) {
1157
+ const eps = brain.memory.episodes;
1158
+ if (eps.length <= MAX_EPISODES) return { compacted: 0 };
1159
+ const overflow = eps.length - MAX_EPISODES;
1160
+ const take = Math.min(overflow + 200, eps.length); // 一次多挤一点,别每条都触发
1161
+ const oldest = eps.slice(0, take);
1162
+ const card = makeCard(oldest);
1163
+ if (card) addCard(brain.memory, card);
1164
+ try {
1165
+ fs.appendFileSync(
1166
+ path.join(brainDir(brain.id), 'archive.jsonl'),
1167
+ `${oldest.map((x) => JSON.stringify(x)).join('\n')}\n`,
1168
+ 'utf8',
1169
+ );
1170
+ } catch (e) {
1171
+ logOnce(`[brain] 容量归档失败(已忽略):${e?.message ?? e}`);
1172
+ }
1173
+ brain.memory.episodes = eps.slice(take);
1174
+ appendAudit(brain.id, { kind: 'capacity', compacted: take });
1175
+ return { compacted: take, card: card?.id ?? null };
1176
+ }
1177
+
1178
+ /**
1179
+ * 把多份记忆一次性并进来。**这是"只剩一份记忆"的唯一入口。**
1180
+ *
1181
+ * @param {Array} sources [{ path, text, format }]
1182
+ * @param {object} [opts]
1183
+ * @param {boolean} [opts.dryRun] 只算不写
1184
+ * @param {boolean} [opts.deleteSource] 搬完把原文件改名成 .migrated(不是删除,留后悔药)
1185
+ */
1186
+ export function migrateAll(id = DEFAULT_ID, sources = [], { dryRun = false, deleteSource = false } = {}) {
1187
+ const brain = ensureBrain(id);
1188
+ const all = [];
1189
+ const errors = [];
1190
+ const files = [];
1191
+
1192
+ for (const s of Array.isArray(sources) ? sources : []) {
1193
+ if (!s?.text) continue;
1194
+ files.push(s.path ?? '(inline)');
1195
+ const r = parseAny(String(s.text), s.format ?? 'jsonl');
1196
+ all.push(...r.episodes);
1197
+ for (const e of r.errors.slice(0, 3)) errors.push({ path: s.path ?? '', ...e });
1198
+ }
1199
+
1200
+ const d = dedupe(all, { existing: brain.memory.episodes });
1201
+ const ats = d.episodes.map((e) => e.at).filter((t) => t > 0).sort((a, b) => a - b);
1202
+ const report = {
1203
+ files: files.length,
1204
+ parsed: all.length,
1205
+ duplicated: d.duplicated,
1206
+ willImport: d.episodes.length,
1207
+ errors: errors.slice(0, 20),
1208
+ errorCount: errors.length,
1209
+ span: ats.length ? { from: new Date(ats[0]).toISOString().slice(0, 10), to: new Date(ats[ats.length - 1]).toISOString().slice(0, 10) } : null,
1210
+ };
1211
+
1212
+ if (dryRun) return { ok: true, dryRun: true, report };
1213
+
1214
+ const r = importEpisodes(id, d.episodes, { source: 'import' });
1215
+ const cap = enforceCapacity(brain);
1216
+
1217
+ // 原始文件不 rm,改名 —— 用户要删自己删,别让我们替他做不可逆的事
1218
+ const renamed = [];
1219
+ if (deleteSource) {
1220
+ for (const p of files) {
1221
+ if (!p || p === '(inline)' || !fs.existsSync(p)) continue;
1222
+ try {
1223
+ fs.renameSync(p, `${p}.migrated`);
1224
+ renamed.push(`${p}.migrated`);
1225
+ } catch (e) {
1226
+ errors.push({ path: p, reason: `改名失败:${e?.message ?? e}` });
1227
+ }
1228
+ }
1229
+ }
1230
+
1231
+ return {
1232
+ ok: true,
1233
+ dryRun: false,
1234
+ report,
1235
+ imported: r.imported,
1236
+ total: r.total,
1237
+ compacted: cap.compacted,
1238
+ renamed,
1239
+ check: identityCheck(id),
1240
+ };
1241
+ }
1242
+
1243
+ /** 迁完之后的自检:搬进来的东西到底能不能被想起来 */
1244
+ export function verifyMemory(id = DEFAULT_ID, { samples = 5 } = {}) {
1245
+ const brain = ensureBrain(id);
1246
+ const eps = brain.memory.episodes;
1247
+ const imported = eps.filter((e) => e.source === 'import').length;
1248
+ const live = eps.filter((e) => e.source === 'live').length;
1249
+
1250
+ const picked = eps.filter((e) => e.what).slice(-samples);
1251
+ const checks = picked.map((e) => {
1252
+ const kw = String(e.what).slice(0, 6);
1253
+ const line = wakeLine(id, { who: e.who ?? '', text: kw });
1254
+ return { keyword: kw, found: line.includes(kw.slice(0, 3)) };
1255
+ });
1256
+
1257
+ return {
1258
+ id,
1259
+ episodes: eps.length,
1260
+ imported,
1261
+ live,
1262
+ cards: (brain.memory.cards ?? []).length,
1263
+ people: Object.keys(brain.memory.impressions ?? {}).length,
1264
+ check: identityCheck(id),
1265
+ recall: checks,
1266
+ recallRate: checks.length ? checks.filter((c) => c.found).length / checks.length : 1,
1267
+ };
1268
+ }
1269
+
1270
+ /* ── 日记:她自己的心房 ─────────────────────────────────────── */
1271
+
1272
+ /** 日记目录:<dataDir>/days/,跟宿主自己的日记分开,别互相覆盖 */
1273
+ export function diaryDir(id = DEFAULT_ID) {
1274
+ return path.join(brainDir(id), 'days');
1275
+ }
1276
+
1277
+ export function diaryPath(id = DEFAULT_ID, date = '') {
1278
+ const d = date || dayKey();
1279
+ return path.join(diaryDir(id), `${d}.md`);
1280
+ }
1281
+
1282
+ /**
1283
+ * 今天的素材 + 第一人称骨架。
1284
+ * 脑子不出文笔,只给料——宿主拿 draft 让模型用她的口吻写成日记。
1285
+ */
1286
+ export function diaryDigest(id = DEFAULT_ID, date = '') {
1287
+ const brain = ensureBrain(id);
1288
+ return dayDigest(brain, date || dayKey());
1289
+ }
1290
+
1291
+ /**
1292
+ * 她把日记存回来。
1293
+ *
1294
+ * 存完之后这段文字会被当作"她写过的"记进记忆——将来问"你写过什么"能想起来。
1295
+ * **日记要带心情**:正文里没写就补一行(`withMood:false` 可关掉)。
1296
+ */
1297
+ export function writeDiary(id = DEFAULT_ID, { date = '', text = '', withMood = true } = {}) {
1298
+ const brain = ensureBrain(id);
1299
+ const body = String(text ?? '').trim();
1300
+ if (!body) return { ok: false, reason: '日记是空的' };
1301
+
1302
+ const d = date || dayKey();
1303
+ const mood = brain.affect?.mood ?? '';
1304
+ const hasMood = mood && mood !== '平静' && mood !== '说不上来';
1305
+
1306
+ // 她自己写了心情就不动;没写就补一行,别让日记丢了心情
1307
+ let final = body;
1308
+ let moodAdded = false;
1309
+ if (withMood && hasMood && !/心情/.test(final)) {
1310
+ final = `${final}\n\n心情:${mood}`;
1311
+ moodAdded = true;
1312
+ }
1313
+
1314
+ const dir = diaryDir(id);
1315
+ fs.mkdirSync(dir, { recursive: true });
1316
+ const file = diaryPath(id, d);
1317
+ fs.writeFileSync(file, final.endsWith('\n') ? final : `${final}\n`, 'utf8');
1318
+
1319
+ // 记进记忆:以后能想起来"我写过什么"
1320
+ addEpisode(brain.memory, {
1321
+ who: '',
1322
+ what: `我写了日记:${final.replace(/\s+/g, ' ').slice(0, 60)}`,
1323
+ feel: hasMood ? mood : '',
1324
+ mood: hasMood ? mood : '',
1325
+ source: 'diary',
1326
+ evidence: file,
1327
+ }, nowMs());
1328
+
1329
+ if (!Array.isArray(brain.meta.diary)) brain.meta.diary = [];
1330
+ if (!brain.meta.diary.includes(d)) brain.meta.diary.push(d);
1331
+ brain.meta.diary = brain.meta.diary.slice(-400);
1332
+
1333
+ // 心情单独存一份,方便按月看她的情绪曲线
1334
+ if (!brain.meta.diaryMood) brain.meta.diaryMood = {};
1335
+ brain.meta.diaryMood[d] = hasMood ? mood : '';
1336
+
1337
+ saveBrain(brain);
1338
+ appendAudit(id, { kind: 'diary', date: d, chars: final.length, mood: brain.meta.diaryMood[d], moodAdded });
1339
+ return { ok: true, date: d, file, chars: final.length, mood: brain.meta.diaryMood[d] || null, moodAdded };
1340
+ }
1341
+
1342
+ export function readDiary(id = DEFAULT_ID, date = '') {
1343
+ const file = diaryPath(id, date);
1344
+ if (!fs.existsSync(file)) return null;
1345
+ const brain = ensureBrain(id);
1346
+ const d = path.basename(file, '.md');
1347
+ return {
1348
+ date: d,
1349
+ text: fs.readFileSync(file, 'utf8'),
1350
+ mood: brain.meta.diaryMood?.[d] ?? null,
1351
+ };
1352
+ }
1353
+
1354
+ export function listDiary(id = DEFAULT_ID) {
1355
+ const dir = diaryDir(id);
1356
+ if (!fs.existsSync(dir)) return [];
1357
+ return fs.readdirSync(dir)
1358
+ .filter((f) => f.endsWith('.md'))
1359
+ .map((f) => {
1360
+ const full = path.join(dir, f);
1361
+ return { date: f.replace(/\.md$/, ''), size: fs.statSync(full).size, at: fs.statSync(full).mtimeMs };
1362
+ })
1363
+ .sort((a, b) => (a.date < b.date ? 1 : -1));
1364
+ }
1365
+
1366
+ /** 日记也能被检索:问"你写过什么"时用它 */
1367
+ export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
1368
+ const list = listDiary(id);
1369
+ if (!list.length) return [];
1370
+ const q = String(word ?? '').trim();
1371
+ const hits = [];
1372
+ for (const d of list) {
1373
+ const r = readDiary(id, d.date);
1374
+ if (!r) continue;
1375
+ if (!q || r.text.includes(q)) hits.push({ date: r.date, excerpt: r.text.replace(/\s+/g, ' ').slice(0, 80) });
1376
+ if (hits.length >= limit) break;
1377
+ }
1378
+ return hits;
1379
+ }
1380
+
706
1381
  export function snapshot(id = DEFAULT_ID) {
707
1382
  const brain = ensureBrain(id);
708
1383
  const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
@@ -730,8 +1405,18 @@ export function snapshot(id = DEFAULT_ID) {
730
1405
  relation: brain.relation,
731
1406
  weights: weightReport(brain.persona.units),
732
1407
  personaSource: brain.persona.source ?? null,
733
- apps: appSummary(brain.memory),
1408
+ apps: appSummary(brain.memory, brain.persona.traits),
734
1409
  affect: brain.affect,
1410
+ runtime: {
1411
+ shadow: Boolean(shadowMode || brain.meta.shadow),
1412
+ ttlPolicy,
1413
+ moodPolicy,
1414
+ dataDir: dataDir(),
1415
+ dataDirSource: dataDirSource(),
1416
+ dataDirInsidePackage: isDataDirInsidePackage(),
1417
+ roleDir: roleDir(),
1418
+ },
1419
+ contractWarnings: brain.meta.contractWarnings ?? [],
735
1420
  emotion: {
736
1421
  stage: emotion.stageOf(brain.vocab),
737
1422
  words: Object.keys(brain.vocab),
@@ -779,7 +1464,12 @@ export function forgetCache(id) {
779
1464
  * fy.tick()
780
1465
  */
781
1466
  export function createBrain(options = {}) {
782
- configure({ dataDir: options.dataDir, roleDir: options.roleDir });
1467
+ configure({
1468
+ dataDir: options.dataDir,
1469
+ roleDir: options.roleDir,
1470
+ shadow: options.shadow,
1471
+ ttl: options.ttlPolicy,
1472
+ });
783
1473
  const id = options.id ?? DEFAULT_ID;
784
1474
 
785
1475
  // 第一次建这条鱼时,把关系和称呼一起落进去——
@@ -800,11 +1490,26 @@ export function createBrain(options = {}) {
800
1490
  return {
801
1491
  id,
802
1492
  get brain() { return ensureBrain(id); },
803
- wake(event) {
1493
+ wake(event, opts) {
804
1494
  if (shouldObserve(event)) observe(id, event);
805
- return { text: wakeLine(id, event), id };
1495
+ return { text: wakeLine(id, event, opts), id };
806
1496
  },
807
- observe(event) { return observe(id, event); },
1497
+ observe(event, opts) { return observe(id, event, opts); },
1498
+ /** 「我还是我吗」三件套体检 */
1499
+ identity() { return identityCheck(id); },
1500
+ /** 打包带走 */
1501
+ exportPack(opts) { return exportPack(id, opts); },
1502
+ /** 存档 / 回滚 */
1503
+ snapshot(name) { return snapshotBrain(id, name); },
1504
+ restore(name) { return restoreBrain(id, name); },
1505
+ snapshots() { return listSnapshots(id); },
1506
+ /** 把宿主已有的历史灌进来 */
1507
+ importEpisodes(list, opts) { return importEpisodes(id, list, opts); },
1508
+ /** 日记:她的心房 */
1509
+ diary(date) { return diaryDigest(id, date); },
1510
+ writeDiary(opts) { return writeDiary(id, opts); },
1511
+ readDiary(date) { return readDiary(id, date); },
1512
+ listDiary() { return listDiary(id); },
808
1513
  tick(now) { return settleBrain(id, now); },
809
1514
  brief() { return getBrief(id); },
810
1515
  snapshot() { return snapshot(id); },
@@ -853,6 +1558,9 @@ export { retrieve } from './core/memory.js';
853
1558
  export { brief } from './core/persona.js';
854
1559
  export { normalizeEvent, toCue, toObservation, shouldObserve, keywords } from './core/event.js';
855
1560
  export { dataDir, roleDir } from './store.js';
1561
+ export { dataDirSource, isDataDirInsidePackage } from './store.js';
1562
+ export { lintCard } from './core/extract.js';
1563
+ export { dedupeKey } from './adapters/qq-bridge.js';
856
1564
  export { createBridgeAdapter } from './adapters/qq-bridge.js';
857
1565
  export {
858
1566
  createBody, chooseBody, bodyScores, bodyLine, canDo, hasCapability,