feiyu-brain 1.2.0 → 1.4.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
@@ -8,6 +8,7 @@
8
8
 
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import crypto from 'node:crypto';
11
12
 
12
13
  import { birthFromCard } from './core/extract.js';
13
14
  import { brief, decay, evolve, shed, weightReport } from './core/persona.js';
@@ -18,6 +19,13 @@ import { createContract } from './core/relation.js';
18
19
  import { attribute, LABELS } from './core/attribution.js';
19
20
  import { check } from './core/invariants.js';
20
21
  import { toCue, toObservation, shouldObserve, normalizeEvent } from './core/event.js';
22
+ import * as emotion from './core/emotion.js';
23
+ import { makeCard, addCard, shouldCompact } from './core/memory.js';
24
+ import { driverFor } from './core/driver.js';
25
+ import {
26
+ recordSeen, recallApp, appTaste, appSummary, similarSeen, emptyApps,
27
+ priorTaste, effectiveTaste, nudgeTraits, chooseApp, chooseContent, AFFINITY, APP_AFFINITY,
28
+ } from './core/apps.js';
21
29
  import {
22
30
  ROOT, loadBrain, saveBrain, appendAudit, readAudit, listBrains,
23
31
  setDataDir, setRoleDir, dataDir, roleDir,
@@ -30,6 +38,14 @@ function nowMs() {
30
38
  return Date.now();
31
39
  }
32
40
 
41
+ /** 同一条警告只打一次,别刷屏 */
42
+ const warnedOnce = new Set();
43
+ function logOnce(msg) {
44
+ if (warnedOnce.has(msg)) return;
45
+ warnedOnce.add(msg);
46
+ try { console.warn(msg); } catch { /* 没有 console 也不影响 */ }
47
+ }
48
+
33
49
  /** 宿主初始化:指定数据目录和角色卡目录 */
34
50
  export function configure({ dataDir: d, roleDir: r } = {}) {
35
51
  if (d) setDataDir(d);
@@ -82,19 +98,41 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
82
98
  throw new Error(`找不到角色卡:请传 cardText,或把 ${roleDir()}/<角色>.md 放好`);
83
99
  }
84
100
 
85
- const { traits, units } = birthFromCard(card.text);
101
+ // 特质旁挂文件:roles/<名字>.traits.json,用来精确指定(比自动统计准)
102
+ let traitsOverride = null;
103
+ try {
104
+ const sidecar = path.join(roleDir(), `${card.name}.traits.json`);
105
+ if (fs.existsSync(sidecar)) traitsOverride = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
106
+ } catch { traitsOverride = null; }
107
+
108
+ const { traits, units } = birthFromCard(card.text, { traitsOverride });
86
109
  const brain = {
87
110
  id,
88
111
  schema: 'brain/2',
89
112
  born: nowMs(),
90
113
  roleCard: card.name,
91
- persona: { seed: cardName ? `card:${card.name}` : `${roleDir()}/${card.name}.md`, traits, units, brief: '' },
114
+ persona: {
115
+ seed: cardName ? `card:${card.name}` : `${roleDir()}/${card.name}.md`,
116
+ traits,
117
+ units,
118
+ brief: '',
119
+ // 人格主档只有一个:这里。外部卡只是"导入源",导过就记下来。
120
+ source: {
121
+ kind: cardText ? 'inline' : 'file',
122
+ name: card.name,
123
+ source: 'birth',
124
+ hash: crypto.createHash('sha1').update(String(card.text)).digest('hex').slice(0, 12),
125
+ importedAt: nowMs(),
126
+ },
127
+ },
92
128
  relation: createContract(relation, address),
93
129
  self: { style: styleVector(traits), divergence: 0, narrative: '', styleName: null },
94
130
  state: { energy: 0.8, fatigue: 0.2, sleep: 'awake', flow: 1 },
95
131
  affect: { p: 0, a: 0, d: 0, mood: '平静' },
96
132
  drive: { curiosity: Math.min(1, 0.4 + (traits.好奇 ?? 0.3)), boredom: 0.5, social: 0.6 },
97
133
  memory: emptyMemory(),
134
+ // 情绪词表:出生时是空的。她没有"委屈"这个词,只有感受。
135
+ vocab: {},
98
136
  // 身体:手机 / 平板 / 电脑。没指定就按人设算——好动的摸手机,爱折腾的开电脑。
99
137
  body: createBody({ kind: body ?? chooseBody(traits, {}, mulberry32(hashTraits(traits))) }),
100
138
  patience: 1,
@@ -144,12 +182,24 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null) {
144
182
 
145
183
  if (level !== 1) parts.push(`【意识流】${flowName(level)}`);
146
184
  const mood = brain.affect?.mood;
147
- if (mood && mood !== '平静') parts.push(`【心情】${mood}`);
185
+ if (mood && mood !== '平静' && mood !== '说不上来') parts.push(`【心情】${mood}`);
148
186
 
149
187
  const cue = eventOrCue?.who !== undefined ? eventOrCue : toCue(eventOrCue);
150
188
  if (cue) {
151
189
  const hit = retrieve(cue, brain.memory);
152
190
  if (hit.text) parts.push(`【想到的】\n${hit.text}`);
191
+
192
+ // 外部检索器(向量/图谱):同步读缓存,不 await
193
+ if (extraRetriever) {
194
+ try {
195
+ const extra = extraRetriever(cue, brain.memory) ?? [];
196
+ const lines = (Array.isArray(extra) ? extra : []).filter(Boolean).slice(0, 3);
197
+ if (lines.length) parts.push(`【搜到的】\n${lines.join('\n')}`);
198
+ } catch (e) {
199
+ // 检索器坏了不能拖垮唤醒
200
+ logOnce(`[brain] 外部检索器出错(已忽略):${e?.message ?? e}`);
201
+ }
202
+ }
153
203
  }
154
204
  return parts.join('\n');
155
205
  }
@@ -171,7 +221,9 @@ export function observe(id = DEFAULT_ID, event = {}) {
171
221
  const consistent = ev.consistent ?? matchUnits(brain.persona.units, ev.text ?? '').consistent;
172
222
  const conflicting = ev.conflicting ?? matchUnits(brain.persona.units, ev.text ?? '').conflicting;
173
223
 
174
- brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at });
224
+ // step:默认 1(每次 ±0.01)。只有传了 magnitude(重大转折)才放大,上限 5。
225
+ const step = Math.max(1, Math.min(5, Number(ev.magnitude) || 1));
226
+ brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
175
227
 
176
228
  // 蜕皮
177
229
  const sh = shed(brain.persona.units, { at });
@@ -184,7 +236,9 @@ export function observe(id = DEFAULT_ID, event = {}) {
184
236
  }
185
237
 
186
238
  // 记忆
187
- const obs = ev.sender ? toObservation(ev) : (ev.what ? ev : null);
239
+ const obs = ev.what
240
+ ? ev
241
+ : (ev.text ? { who: ev.who ?? ev.sender ?? '', what: String(ev.text).slice(0, 80), feel: ev.feel ?? '', via: ev.via ?? 'api' } : null);
188
242
  if (obs?.what) {
189
243
  addEpisode(brain.memory, {
190
244
  who: obs.who ?? '',
@@ -209,6 +263,27 @@ export function observe(id = DEFAULT_ID, event = {}) {
209
263
  brain.memory.strategies[ev.action.strategy].uses += 1;
210
264
  }
211
265
 
266
+ // 平台记忆:她刷到过什么(有 app 才记)
267
+ if (ev.app && (ev.title || ev.text)) {
268
+ recordSeen(brain.memory, ev.app, {
269
+ title: ev.title ?? String(ev.text).slice(0, 60),
270
+ kind: ev.kind ?? '',
271
+ reaction: Number.isFinite(ev.reaction) ? ev.reaction : 0,
272
+ minutes: Number(ev.minutes) || 0,
273
+ });
274
+ appendAudit(id, { kind: 'seen', app: ev.app, title: String(ev.title ?? ev.text).slice(0, 40) });
275
+
276
+ // ── 闭环:刷到的东西反过来改人设 ──
277
+ // 看的解压视频多了,"懒"这条特质就真的涨一点;人设变了,下次爱看的就不一样。
278
+ const { traits: nextTraits, delta } = nudgeTraits(brain.persona.traits, ev.kind ?? '', Number(ev.reaction) || 0);
279
+ if (Object.keys(delta).length) {
280
+ brain.persona.traits = nextTraits;
281
+ brain.self.style = styleVector(nextTraits);
282
+ brain.self.styleName = dominantStyle(brain.self.style);
283
+ appendAudit(id, { kind: 'trait-drift', app: ev.app, contentKind: ev.kind, delta });
284
+ }
285
+ }
286
+
212
287
  // 关系记忆:互动次数
213
288
  const who = ev.who ?? ev.sender;
214
289
  if (who) {
@@ -304,6 +379,314 @@ export function tryBody(id = DEFAULT_ID, action = {}) {
304
379
  return res;
305
380
  }
306
381
 
382
+ /* ── 情绪:按当前情况演变 ─────────────────────────────────────── */
383
+
384
+ /**
385
+ * 一件事发生了,她此刻是什么感受。
386
+ *
387
+ * 同一件事,人设 + 状态决定坐标:
388
+ * 有劲的鱼 → 掌控感高 → 靠近"生气"
389
+ * 累垮的鱼 → 掌控感低 → 靠近"委屈"
390
+ *
391
+ * @param {object} event { valence:-1~1, intensity:0~1, what?, who? }
392
+ */
393
+ export function feel(id = DEFAULT_ID, event = {}) {
394
+ const brain = ensureBrain(id);
395
+ const r = emotion.feel({
396
+ event,
397
+ traits: brain.persona.traits,
398
+ state: brain.state,
399
+ vocab: brain.vocab,
400
+ });
401
+
402
+ brain.affect = {
403
+ p: r.pad[0],
404
+ a: r.pad[1],
405
+ d: r.pad[2],
406
+ mood: r.label.kind === 'word' ? r.label.word : (r.label.kind === 'variant' ? `${r.label.word}(变体)` : '说不上来'),
407
+ };
408
+ brain.meta.lastFeel = { at: Date.now(), pad: r.pad, label: r.label, stage: r.stage, text: r.text };
409
+ saveBrain(brain);
410
+ return r;
411
+ }
412
+
413
+ /**
414
+ * 学一个情绪词。**必须两个以上来源一致**才采纳。
415
+ * @param {string[]} sources 例如 ['user:扶摇','douyin'] / ['user:老爹','群聊']
416
+ */
417
+ export function learnEmotion(id = DEFAULT_ID, word, { pad, sources = [], cause = '' } = {}) {
418
+ const brain = ensureBrain(id);
419
+ const r = emotion.learn(brain.vocab, word, { pad, sources, cause });
420
+ if (r.learned) {
421
+ brain.vocab = r.vocab;
422
+ saveBrain(brain);
423
+ appendAudit(id, { kind: 'learn-emotion', word, sources: r.sources });
424
+ }
425
+ return { ...r, stage: emotion.stageOf(brain.vocab), knownWords: Object.keys(brain.vocab).length };
426
+ }
427
+
428
+ /** 阶段三:从 ≥3 个实例里自己归纳出这个词的含义。 */
429
+ export function induceEmotion(id = DEFAULT_ID, word) {
430
+ const brain = ensureBrain(id);
431
+ const r = emotion.induce(brain.vocab, word);
432
+ if (r.induced) {
433
+ brain.vocab = r.vocab;
434
+ saveBrain(brain);
435
+ appendAudit(id, { kind: 'induce-emotion', word, cause: r.definition.cause });
436
+ }
437
+ return r;
438
+ }
439
+
440
+ export function vocabOf(id = DEFAULT_ID) {
441
+ const brain = ensureBrain(id);
442
+ return {
443
+ stage: emotion.stageOf(brain.vocab),
444
+ words: Object.keys(brain.vocab),
445
+ detail: brain.vocab,
446
+ };
447
+ }
448
+
449
+ /* ── 记忆卡片:上下文过长时压缩中段 ───────────────────────────── */
450
+
451
+ export function needsCard(id = DEFAULT_ID, contextChars = 0) {
452
+ return shouldCompact(contextChars);
453
+ }
454
+
455
+ /**
456
+ * 把最近的一段经历压成一张卡片(≈160 字)。
457
+ * 原文可以裁掉,卡片留在上下文里。
458
+ */
459
+ export function compactNow(id = DEFAULT_ID, { episodes } = {}) {
460
+ const brain = ensureBrain(id);
461
+ const list = Array.isArray(episodes) ? episodes : brain.memory.episodes.slice(-12);
462
+ const card = makeCard(list);
463
+ if (!card) return { ok: false, reason: '没有可压缩的经历' };
464
+ addCard(brain.memory, card);
465
+ saveBrain(brain);
466
+ appendAudit(id, { kind: 'card', chars: card.chars, from: card.from.length });
467
+ return { ok: true, card };
468
+ }
469
+
470
+ export function cardsOf(id = DEFAULT_ID) {
471
+ return ensureBrain(id).memory.cards ?? [];
472
+ }
473
+
474
+ /* ── 身体驱动:真的去开 App ───────────────────────────────────── */
475
+
476
+ const drivers = new Map(); // id -> driver
477
+
478
+ function getDriver(brain) {
479
+ const key = `${brain.id}:${brain.body?.kind}:${brain.body?.ownership}`;
480
+ if (drivers.has(key)) return drivers.get(key);
481
+ const d = driverFor(brain.body, {
482
+ adbPath: process.env.FEISHU_ADB || 'adb',
483
+ deviceId: process.env.FEISHU_DEVICE || '',
484
+ evidenceDir: path.join(dataDir(), 'evidence', brain.body?.kind ?? 'none'),
485
+ });
486
+ drivers.set(key, d);
487
+ return d;
488
+ }
489
+
490
+ /**
491
+ * 让她真的做一件事。
492
+ *
493
+ * execAction('default', { type:'open_app', package:'com.ss.android.ugc.aweme', app:'douyin', capability:2 })
494
+ * execAction('default', { type:'screenshot' })
495
+ *
496
+ * 先过权限闸,再调驱动,最后记账——**没有 evidence 的动作不算发生**。
497
+ */
498
+ export async function execAction(id = DEFAULT_ID, action = {}) {
499
+ const brain = ensureBrain(id);
500
+ const gate = canDo(brain.body, action);
501
+ if (!gate.ok) {
502
+ appendAudit(id, { kind: 'deny', code: gate.code, action: action.type });
503
+ return gate;
504
+ }
505
+
506
+ const driver = getDriver(brain);
507
+ const res = await driver.exec(action);
508
+ const rec = recordAction(brain.body, action, res, res.evidence);
509
+ brain.memory.lastActions = [...(brain.memory.lastActions ?? []), rec].slice(-50);
510
+ saveBrain(brain);
511
+ appendAudit(id, {
512
+ kind: 'action',
513
+ type: action.type,
514
+ ok: res.ok !== false,
515
+ code: res.code ?? 'OK',
516
+ evidence: res.evidence ?? null,
517
+ });
518
+ return res;
519
+ }
520
+
521
+ /**
522
+ * 卸载:**临界点 + 三问**,两个都过才动手。
523
+ *
524
+ * @param {object} q { why:'追到的事件', fits:true, consequence:'删了会怎样' }
525
+ */
526
+ export async function requestUninstall(id = DEFAULT_ID, pkg, q = {}) {
527
+ const brain = ensureBrain(id);
528
+ if (!pkg) return { ok: false, code: 'E_ARGS', reason: '缺 package' };
529
+
530
+ const threshold = 0.5 + 0.4 * (brain.persona.traits?.心软 ?? 0.5);
531
+ if ((brain.patience ?? 1) < threshold) {
532
+ return {
533
+ ok: false,
534
+ code: 'E_NOT_YET',
535
+ reason: `还没攒够(忍耐 ${Number(brain.patience ?? 1).toFixed(2)} < 临界 ${threshold.toFixed(2)})——那只是情绪,不是决定`,
536
+ };
537
+ }
538
+
539
+ if (!q.why) return { ok: false, code: 'Q1', reason: 'Q1 没过:说不出为什么想删' };
540
+ if (q.fits === false) return { ok: false, code: 'Q2', reason: 'Q2 没过:这不像她会做的事' };
541
+ if (!q.consequence) return { ok: false, code: 'Q3', reason: 'Q3 没过:没想过删了会怎样' };
542
+
543
+ return execAction(id, { type: 'uninstall', package: pkg, capability: CAPABILITY.DESTROY });
544
+ }
545
+
546
+ /* ── 重大转折:一次改多条,但必须留证据 ───────────────────────── */
547
+
548
+ /**
549
+ * 她想通了一件事——允许一次推动多条命题,不像日常那样只动 0.01。
550
+ *
551
+ * @param {object} o
552
+ * @param {string[]} o.units 要动的命题 id
553
+ * @param {'up'|'down'} o.direction
554
+ * @param {number} [o.magnitude] 1~5,对应 ±0.01×magnitude
555
+ * @param {string} o.evidence 凭什么改(必填,没有证据不许改)
556
+ */
557
+ export function reframe(id = DEFAULT_ID, { units = [], direction = 'up', magnitude = 3, evidence = '' } = {}) {
558
+ const brain = ensureBrain(id);
559
+ if (!evidence) return { ok: false, reason: '没有证据的转折不算转折' };
560
+ if (!units.length) return { ok: false, reason: '没指定要动哪几条命题' };
561
+
562
+ const before = Object.fromEntries(brain.persona.units.filter((u) => units.includes(u.id)).map((u) => [u.id, u.weight]));
563
+ brain.persona.units = evolve(brain.persona.units, {
564
+ consistent: direction === 'up' ? units : [],
565
+ conflicting: direction === 'down' ? units : [],
566
+ at: nowMs(),
567
+ step: magnitude,
568
+ });
569
+ const after = Object.fromEntries(brain.persona.units.filter((u) => units.includes(u.id)).map((u) => [u.id, u.weight]));
570
+
571
+ refreshBrief(brain);
572
+ saveBrain(brain);
573
+ appendAudit(id, { kind: 'reframe', direction, magnitude, evidence: String(evidence).slice(0, 120), before, after });
574
+ return { ok: true, direction, magnitude, before, after };
575
+ }
576
+
577
+ /* ── 人格卡:只加载,不代写 ───────────────────────────────────── */
578
+
579
+ /**
580
+ * 换一张人格卡。这是"已经写好的鱼只需要加载卡"的入口。
581
+ *
582
+ * **不生成卡,只接收卡。** 卡必须由用户写(或别的工具写),这里只负责装进来。
583
+ * 记忆、关系、身体、情绪词表全部保留——只换人格部分。
584
+ */
585
+ export function importRoleCard(id = DEFAULT_ID, cardText, { name = 'imported', source = 'manual' } = {}) {
586
+ if (!cardText || String(cardText).trim().length < 20) {
587
+ return { ok: false, reason: '卡太短了,至少 20 字' };
588
+ }
589
+ const brain = ensureBrain(id);
590
+ const prev = {
591
+ units: brain.persona.units.length,
592
+ traits: roundTraits(brain.persona.traits),
593
+ source: brain.persona.source ?? null,
594
+ };
595
+
596
+ const { traits, units } = birthFromCard(String(cardText));
597
+ const hash = crypto.createHash('sha1').update(String(cardText)).digest('hex').slice(0, 12);
598
+
599
+ brain.persona = {
600
+ ...brain.persona,
601
+ traits,
602
+ units,
603
+ brief: '',
604
+ source: { kind: 'card', name, source, hash, importedAt: nowMs() },
605
+ };
606
+ brain.self.style = styleVector(traits);
607
+ brain.self.styleName = dominantStyle(brain.self.style);
608
+
609
+ refreshBrief(brain);
610
+ saveBrain(brain);
611
+ appendAudit(id, { kind: 'import-card', name, hash, units: units.length, prevUnits: prev.units });
612
+
613
+ return { ok: true, name, hash, units: units.length, previous: prev, traits: roundTraits(traits) };
614
+ }
615
+
616
+ /* ── 检索:内置关键词 + 可插拔的语义检索 ─────────────────────── */
617
+
618
+ let extraRetriever = null;
619
+
620
+ /**
621
+ * 接一个外部检索器(向量库、图谱都行)。
622
+ *
623
+ * 约定:**同步**返回字符串数组,按相关度从高到低。
624
+ * 异步检索(向量/网络)请在宿主侧预取成缓存,这里只读缓存——
625
+ * 因为唤醒是同步路径,await 会把桥接卡住。
626
+ *
627
+ * @param {(cue:object, memory:object) => string[]} fn 传 null 取消
628
+ */
629
+ export function setRetriever(fn) {
630
+ extraRetriever = typeof fn === 'function' ? fn : null;
631
+ return extraRetriever !== null;
632
+ }
633
+
634
+ export function currentRetriever() {
635
+ return extraRetriever;
636
+ }
637
+
638
+ /* ── 平台记忆:她刷过什么 ─────────────────────────────────────── */
639
+
640
+ /** 记一条"她在某平台看到了什么"(不吃人设,只进记忆) */
641
+ export function recordAppSeen(id = DEFAULT_ID, app, item = {}) {
642
+ const brain = ensureBrain(id);
643
+ const entry = recordSeen(brain.memory, app, item);
644
+ if (!entry) return { ok: false, reason: '缺 app 名' };
645
+ saveBrain(brain);
646
+ return { ok: true, app, entry };
647
+ }
648
+
649
+ /** 某个平台的印象;不传 app 就返回全部平台的摘要 */
650
+ export function appMemory(id = DEFAULT_ID, app = null) {
651
+ const brain = ensureBrain(id);
652
+ const traits = brain.persona.traits;
653
+ if (!app) return appSummary(brain.memory, traits);
654
+ return {
655
+ taste: appTaste(brain.memory, app, { traits, limit: 8 }),
656
+ recent: recallApp(brain.memory, app, { limit: 10 }),
657
+ summary: appSummary(brain.memory, traits)[app] ?? null,
658
+ };
659
+ }
660
+
661
+ /** 她此刻更想摸哪个 App(由当前人设算) */
662
+ export function pickApp(id = DEFAULT_ID, rng = Math.random) {
663
+ return chooseApp(ensureBrain(id).persona.traits, rng);
664
+ }
665
+
666
+ /**
667
+ * 从那批内容里挑一条她想看的。
668
+ * pool = [{ title, kind }],由宿主从平台/卡池里取。
669
+ */
670
+ export function pickContent(id = DEFAULT_ID, app = '', pool = [], rng = Math.random) {
671
+ const brain = ensureBrain(id);
672
+ return chooseContent(brain.persona.traits, brain.memory, app, pool, rng);
673
+ }
674
+
675
+ /** 看她现在的口味:先验(人设派生的)和合成后的(先验+经历) */
676
+ export function tasteOf(id = DEFAULT_ID, app = '') {
677
+ const brain = ensureBrain(id);
678
+ return {
679
+ prior: priorTaste(brain.persona.traits),
680
+ effective: effectiveTaste(brain.memory, app, brain.persona.traits),
681
+ traits: roundTraits(brain.persona.traits),
682
+ };
683
+ }
684
+
685
+ /** 这件事她以前见过类似的吗(跨平台) */
686
+ export function seenBefore(id = DEFAULT_ID, text = '') {
687
+ return similarSeen(ensureBrain(id).memory, text);
688
+ }
689
+
307
690
  export function snapshot(id = DEFAULT_ID) {
308
691
  const brain = ensureBrain(id);
309
692
  const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
@@ -330,12 +713,22 @@ export function snapshot(id = DEFAULT_ID) {
330
713
  : null,
331
714
  relation: brain.relation,
332
715
  weights: weightReport(brain.persona.units),
716
+ personaSource: brain.persona.source ?? null,
717
+ apps: appSummary(brain.memory),
718
+ affect: brain.affect,
719
+ emotion: {
720
+ stage: emotion.stageOf(brain.vocab),
721
+ words: Object.keys(brain.vocab),
722
+ last: brain.meta.lastFeel ?? null,
723
+ },
333
724
  memory: {
334
725
  episodes: brain.memory.episodes.length,
335
726
  imagination: brain.memory.imagination.length,
727
+ cards: (brain.memory.cards ?? []).length,
336
728
  formerSelves: brain.memory.formerSelves.length,
337
729
  forgotten: brain.memory.forgotten.length,
338
730
  impressions: Object.keys(brain.memory.impressions).length,
731
+ actions: (brain.memory.lastActions ?? []).length,
339
732
  },
340
733
  observations: brain.meta.observations,
341
734
  invariants: check(brain),
@@ -357,6 +750,7 @@ export function importBrain(data) {
357
750
 
358
751
  export function forgetCache(id) {
359
752
  cache.delete(id);
753
+ for (const k of [...drivers.keys()]) if (k.startsWith(`${id}:`)) drivers.delete(k);
360
754
  return id;
361
755
  }
362
756
 
@@ -372,8 +766,16 @@ export function createBrain(options = {}) {
372
766
  configure({ dataDir: options.dataDir, roleDir: options.roleDir });
373
767
  const id = options.id ?? DEFAULT_ID;
374
768
 
375
- if (options.cardText) {
376
- birth({ id, cardText: options.cardText, cardName: options.cardName ?? id, relation: options.relation ?? 'parent', address: options.address ?? '' });
769
+ // 第一次建这条鱼时,把关系和称呼一起落进去——
770
+ // 以前只有传 cardText 才会走到 birth,导致 relation/address 被静默忽略。
771
+ if (options.cardText || !loadBrain(id)) {
772
+ birth({
773
+ id,
774
+ relation: options.relation ?? 'parent',
775
+ address: options.address ?? '',
776
+ cardText: options.cardText,
777
+ cardName: options.cardName ?? id,
778
+ });
377
779
  forgetCache(id);
378
780
  }
379
781
 
@@ -391,6 +793,35 @@ export function createBrain(options = {}) {
391
793
  brief() { return getBrief(id); },
392
794
  snapshot() { return snapshot(id); },
393
795
  export() { return exportBrain(id); },
796
+ /** 情绪:这件事让她什么感受 */
797
+ feel(event) { return feel(id, event); },
798
+ /** 学一个情绪词(要两个来源) */
799
+ learnEmotion(word, opts) { return learnEmotion(id, word, opts); },
800
+ /** 从实例里自己归纳 */
801
+ induce(word) { return induceEmotion(id, word); },
802
+ vocab() { return vocabOf(id); },
803
+ /** 压一张记忆卡片 */
804
+ compact() { return compactNow(id); },
805
+ /** 她在某平台刷到了什么 */
806
+ recordAppSeen(app, item) { return recordAppSeen(id, app, item); },
807
+ /** 某个平台 / 全部平台的印象 */
808
+ appMemory(app) { return appMemory(id, app); },
809
+ /** 这件事她以前见过类似的吗 */
810
+ seenBefore(text) { return seenBefore(id, text); },
811
+ /** 此刻更想摸哪个 App */
812
+ pickApp(rng) { return pickApp(id, rng); },
813
+ /** 从这批内容里挑一条想看的 */
814
+ pickContent(app, pool, rng) { return pickContent(id, app, pool, rng); },
815
+ /** 先验口味 vs 合成口味 */
816
+ taste(app) { return tasteOf(id, app); },
817
+ /** 想通一件事:一次推多条命题(要证据) */
818
+ reframe(opts) { return reframe(id, opts); },
819
+ /** 换人格卡(只加载,不代写) */
820
+ loadCard(cardText, opts) { return importRoleCard(id, cardText, opts); },
821
+ /** 真的做一件事(开 App / 截图 / 卸载) */
822
+ exec(action) { return execAction(id, action); },
823
+ uninstall(pkg, q) { return requestUninstall(id, pkg, q); },
824
+ setBody(kind, opts) { return setBody(id, kind, opts); },
394
825
  reset(opts = {}) {
395
826
  cache.delete(id);
396
827
  return birth({ id, relation: opts.relation ?? brain.relation.type, address: opts.address ?? brain.relation.address, cardText: opts.cardText, cardName: opts.cardName });
@@ -411,3 +842,24 @@ export {
411
842
  createBody, chooseBody, bodyScores, bodyLine, canDo, hasCapability,
412
843
  recordAction, CAPABILITY, BODY_KINDS, BODY_PROFILES,
413
844
  } from './core/body.js';
845
+
846
+ /* 情绪:三段式 */
847
+ export {
848
+ STAGE, PROTOTYPES, RAW_FEELINGS, RADIUS,
849
+ appraise, label as labelEmotion, speak as speakEmotion, stageOf, distance as emotionDistance,
850
+ learn as learnWord, induce as induceWord, describeSensation,
851
+ } from './core/emotion.js';
852
+
853
+ /* 记忆卡片 */
854
+ export {
855
+ makeCard, addCard, shouldCompact, CARD_THRESHOLD_CHARS, CARD_MAX_CHARS,
856
+ } from './core/memory.js';
857
+
858
+ /* 平台记忆 + 口味闭环 */
859
+ export {
860
+ recordSeen, recallApp, appTaste, appSummary, similarSeen, SEEN_MAX,
861
+ priorTaste, effectiveTaste, nudgeTraits, chooseApp, chooseContent, AFFINITY, APP_AFFINITY,
862
+ } from './core/apps.js';
863
+
864
+ /* 身体驱动 */
865
+ export { driverFor, AdbDriver, DesktopDriver, DryDriver } from './core/driver.js';