feiyu-brain 1.2.0 → 1.4.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/README.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  > **人设是根,其余都是长出来的。**
4
4
 
5
+ > ⚠️ **人格卡必须由用户自己写。**
6
+ > 这个包**不生成卡、不代写卡、不猜你想让她是什么样**——它只负责把卡装进来、按卡运行、让卡随经历慢慢变。
7
+ > 卡是起点,也是她能变成什么样的边界。
8
+
5
9
  一个**平台无关**的认知内核。给它一张人设卡,它长出一条有记忆、有情绪、会发呆、会嘴硬的鱼。
6
10
 
7
11
  它**不会说话**——说话是"身体"的事。它只做两件事:
@@ -13,6 +17,26 @@
13
17
 
14
18
  ---
15
19
 
20
+ ## 闭环:人设 → 刷什么 → 改人设 → 又改刷什么
21
+
22
+ ```
23
+ 用户写的卡(起点,唯一入口)
24
+ ↓ 决定她先看什么
25
+ 刷视频 / 经历
26
+ ↓ 产生反应
27
+ 人设被改(特质 +0.004,权重 ±0.01)
28
+ ↓ 人也变了
29
+ 口味跟着变(先验重新算)
30
+ ↓
31
+ 下次刷的不一样 ──→ 回到第二行
32
+ ```
33
+
34
+ **人设不是常量,是被经历改写的变量;而这个变量又是"选什么"的依据。**
35
+
36
+ 新鱼的性子是用户写的;刷得多了,她会慢慢变成另一条鱼——但她始终从那张卡出发。
37
+
38
+ ---
39
+
16
40
  ## 安装
17
41
 
18
42
  ```bash
package/cli.mjs CHANGED
@@ -1,24 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  // 大肥鱼大脑 · 运维命令行
3
3
  //
4
- // node cli.mjs status 看她现在什么状态
5
- // node cli.mjs brief 打印"此刻的她"(唤醒时注入的那段)
6
- // node cli.mjs observe 扶摇 "你嘴真硬" 手动记一次经历
7
- // node cli.mjs settle 跑一次每日结算(衰减 + TTL + 蜕皮)
8
- // node cli.mjs audit 20 最近 20 条审计
9
- // node cli.mjs spread 派生检验:100 条鱼是不是 100 种样子
10
- // node cli.mjs rebirth parent 妈 重开一条鱼(会清空记忆,慎用)
4
+ // npx feiyu status 看她现在什么状态
5
+ // npx feiyu brief 打印"此刻的她"(唤醒时注入的那段)
6
+ // npx feiyu observe 扶摇 "你嘴真硬" 手动记一次经历
7
+ // npx feiyu settle 跑一次每日结算(衰减 / TTL / 蜕皮)
8
+ // npx feiyu audit 20 最近 20 条审计
9
+ // npx feiyu spread 派生检验:100 条鱼是不是 100 种样子
10
+ // npx feiyu body [phone] 看身体 / 换身体
11
+ // npx feiyu rebirth parent 老爹 重开一条鱼(会清空记忆,慎用)
11
12
 
12
13
  import fs from 'node:fs';
13
14
  import path from 'node:path';
14
15
 
15
16
  import * as brain from './index.js';
16
- import { ROOT } from './store.js';
17
- import { wakeReply, styleVector, flowName, flowLevel } from './core/derive.js';
17
+ import { brainsDir } from './store.js';
18
+ import { wakeReply, styleVector } from './core/derive.js';
18
19
  import { syntheticTraits } from './core/invariants.js';
19
20
  import { BODY_KINDS, BODY_PROFILES, bodyLine } from './core/body.js';
20
21
 
21
- const [, , cmd = 'status', ...args] = process.argv;
22
+ const [, , rawCmd = '', ...args] = process.argv;
22
23
  const ID = process.env.FEIYU_ID || 'default';
23
24
 
24
25
  const line = (s = '') => console.log(s);
@@ -29,9 +30,11 @@ function printStatus() {
29
30
  line(`自知:${s.styleName} (aware ${s.style.aware} / denial ${s.style.denial} / fixed ${s.style.fixed} / naive ${s.style.naive})`);
30
31
  line(`意识流:${s.flow.name}(${s.flow.level})`);
31
32
  line(`命题:${s.weights.count} 条,身份 ${s.weights.identity} 条,总权重 ${s.weights.totalWeight}`);
32
- line(`记忆:经历 ${s.memory.episodes} / 印象 ${s.memory.impressions} / 幻想 ${s.memory.imagination} / 蜕皮 ${s.memory.formerSelves} / 遗忘 ${s.memory.forgotten}`);
33
+ line(`记忆:经历 ${s.memory.episodes} / 印象 ${s.memory.impressions} / 卡片 ${s.memory.cards ?? 0} / 蜕皮 ${s.memory.formerSelves} / 遗忘 ${s.memory.forgotten}`);
33
34
  line(`观察次数:${s.observations}`);
34
35
  line(`关系:${s.relation.type}(称呼「${s.relation.address || '—'}」,可解除 ${s.relation.ctr.dissolvable ? '是' : '否'})`);
36
+ const apps = Object.keys(s.apps ?? {});
37
+ line(`平台:${apps.length ? apps.map((k) => `${k} ${s.apps[k].seen}条`).join(' · ') : '还没在任何平台上有记录'}`);
35
38
  line();
36
39
  line('权重最高的五条:');
37
40
  for (const u of s.weights.top) line(` ${u.id} ${String(u.weight).padEnd(5)} ${u.text}`);
@@ -44,92 +47,156 @@ function printStatus() {
44
47
  }
45
48
  }
46
49
 
47
- switch (cmd) {
48
- case 'status':
49
- printStatus();
50
- break;
51
-
52
- case 'brief': {
53
- const text = brain.getBrief(ID);
54
- line(text);
55
- line();
56
- line(`—— ${text.length} 字`);
57
- break;
58
- }
50
+ /**
51
+ * 没配角色卡时的第一体验。
52
+ *
53
+ * 用户装完第一件事通常就是 `npx feiyu status`,这时盘上什么都没有。
54
+ * 直接抛栈会让人以为坏了——给一段能照着做的引导,正常退出(exit 0)。
55
+ */
56
+ function firstRunGuide() {
57
+ const roles = brain.roleDir();
58
+ line('');
59
+ line('🐟 这里还没有鱼——第一次运行要先给她一张人格卡。');
60
+ line('');
61
+ line('人格卡必须你自己写(这个包不代写,也不猜你想让她是什么样)。');
62
+ line('准备两样东西:');
63
+ line('');
64
+ line(` ① 卡文件 ${path.join(roles, '<名字>.md')}`);
65
+ line(' 第一行:你是……(她是谁)');
66
+ line(' 可加一行:性格:嘴硬=0.85 心软=0.7 好奇=0.8');
67
+ line(' 之后一句一条:她的性格 / 偏好 / 遇到什么事会怎么反应');
68
+ line('');
69
+ line(` ② 指名 ${path.join(brain.dataDir(), 'current-role.json')}`);
70
+ line(' 内容:{"role":"<名字>"}');
71
+ line('');
72
+ line(' 两样齐了再跑:npx feiyu status');
73
+ line('');
74
+ line('不想写卡、只想先看效果:');
75
+ line(" node -e \"import('feiyu-brain').then(m=>{const f=m.createBrain({cardText:'你是鱼。\\n- 我嘴硬。',cardName:'鱼'});console.log(f.wake({sender:'A',text:'在吗'}).text)})\"");
76
+ line('');
77
+ line(`数据目录:${brain.dataDir()}`);
78
+ line(`角色目录:${roles}`);
79
+ line('');
80
+ }
81
+
82
+ function isNoCard(e) {
83
+ return /找不到角色卡/.test(String(e?.message ?? e));
84
+ }
85
+
86
+ function run() {
87
+ const cmd = rawCmd || 'status';
88
+
89
+ switch (cmd) {
90
+ case 'status':
91
+ printStatus();
92
+ return;
59
93
 
60
- case 'observe': {
61
- const who = args[0] || '';
62
- const text = args.slice(1).join(' ') || '';
63
- if (!text) {
64
- line('用法:node cli.mjs observe <谁> "<他说了什么>"');
65
- process.exit(1);
94
+ case 'brief': {
95
+ const text = brain.getBrief(ID);
96
+ line(text);
97
+ line();
98
+ line(`—— ${text.length} 字`);
99
+ return;
66
100
  }
67
- const r = brain.observe(ID, { text, who, what: text, via: 'cli' });
68
- line(`记下了:${who}「${text}」`);
69
- line(`一致:${r.consistent.length} 条 冲突:${r.conflicting.length} 条${r.label ? ` 归因:${r.label}` : ''}`);
70
- break;
71
- }
72
101
 
73
- case 'settle': {
74
- brain.settleBrain(ID);
75
- line('结算完成。');
76
- printStatus();
77
- break;
78
- }
102
+ case 'observe': {
103
+ const who = args[0] || '';
104
+ const text = args.slice(1).join(' ') || '';
105
+ if (!text) {
106
+ line('用法:npx feiyu observe <谁> "<他说了什么>"');
107
+ line(' 加平台:npx feiyu observe 扶摇 "刷到个驴蹄子" --app douyin --kind 解压 --reaction 0.9');
108
+ return;
109
+ }
110
+ const pick = (flag) => {
111
+ const i = args.indexOf(flag);
112
+ return i >= 0 ? args[i + 1] : undefined;
113
+ };
114
+ const app = pick('--app');
115
+ const kind = pick('--kind');
116
+ const reaction = Number(pick('--reaction') ?? 0);
117
+ const r = brain.observe(ID, {
118
+ text,
119
+ who,
120
+ via: app ? `app:${app}` : 'cli',
121
+ ...(app ? { app, kind, reaction } : {}),
122
+ });
123
+ line(`记下了:${who}「${text}」`);
124
+ if (app) line(`平台:${app}${kind ? ` / ${kind}` : ''}`);
125
+ line(`一致:${r.consistent.length} 条 冲突:${r.conflicting.length} 条${r.label ? ` 归因:${r.label}` : ''}`);
126
+ return;
127
+ }
79
128
 
80
- case 'audit': {
81
- const n = Number(args[0] || 20);
82
- const rows = brain.readAudit(ID, n);
83
- if (!rows.length) line('(还没有审计记录)');
84
- for (const r of rows) line(JSON.stringify(r));
85
- break;
86
- }
129
+ case 'settle': {
130
+ brain.settleBrain(ID);
131
+ line('结算完成。');
132
+ printStatus();
133
+ return;
134
+ }
87
135
 
88
- case 'spread': {
89
- const list = syntheticTraits(7, 100);
90
- const replies = list.map((t) => wakeReply(t, 0.8));
91
- const styles = list.map((t) => JSON.stringify(styleVector(t)));
92
- const uniqR = new Set(replies).size;
93
- const uniqS = new Set(styles).size;
94
- line(`100 条不同人设,同一情境(被吵醒,能量 0.8):`);
95
- line(` 反应种类:${uniqR} / 100`);
96
- line(` 自知配方:${uniqS} / 100`);
97
- line(` 样本:${[...new Set(replies)].slice(0, 8).map((x) => `「${x}」`).join(' ')}`);
98
- line();
99
- line(uniqR >= 20 ? '✔ 不是查找表' : '✘ 散度太低,退化成查找表了');
100
- break;
101
- }
136
+ case 'audit': {
137
+ const n = Number(args[0] || 20);
138
+ const rows = brain.readAudit(ID, n);
139
+ if (!rows.length) line('(还没有审计记录)');
140
+ for (const r of rows) line(JSON.stringify(r));
141
+ return;
142
+ }
102
143
 
103
- case 'rebirth': {
104
- const relation = args[0] || 'parent';
105
- const address = args[1] || '';
106
- const dir = path.join(ROOT, 'state', 'brains', ID);
107
- if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
108
- const b = brain.birth({ id: ID, relation, address });
109
- line(`重开了一条鱼:${b.roleCard},${b.persona.units.length} 条命题,主导 ${b.self.styleName}`);
110
- line(b.persona.brief);
111
- break;
112
- }
144
+ case 'spread': {
145
+ const list = syntheticTraits(7, 100);
146
+ const replies = list.map((t) => wakeReply(t, 0.8));
147
+ const styles = list.map((t) => JSON.stringify(styleVector(t)));
148
+ const uniqR = new Set(replies).size;
149
+ const uniqS = new Set(styles).size;
150
+ line('100 条不同人设,同一情境(被吵醒,能量 0.8):');
151
+ line(` 反应种类:${uniqR} / 100`);
152
+ line(` 自知配方:${uniqS} / 100`);
153
+ line(` 样本:${[...new Set(replies)].slice(0, 8).map((x) => `「${x}」`).join(' ')}`);
154
+ line();
155
+ line(uniqR >= 20 ? '✔ 不是查找表' : '✘ 散度太低,退化成查找表了');
156
+ return;
157
+ }
113
158
 
114
- case 'body': {
115
- const kind = args[0];
116
- const s = brain.snapshot(ID);
117
- if (!kind) {
118
- line(`当前身体:${s.body ? `${s.body.label}(${s.body.screen},${s.body.posture},${s.body.ownership === 'owned' ? '自己的' : s.body.ownership === 'borrowed' ? '借的' : '模拟的'})` : '无'}`);
119
- line(`可用:${BODY_KINDS.map((k) => `${k}(${BODY_PROFILES[k].label})`).join(' / ')}`);
120
- if (s.body) {
121
- line('');
122
- line('装了什么:');
123
- for (const app of s.body.apps) line(` · ${app}`);
159
+ case 'body': {
160
+ const kind = args[0];
161
+ const s = brain.snapshot(ID);
162
+ if (!kind) {
163
+ line(`当前身体:${s.body ? `${s.body.label}(${s.body.screen},${s.body.posture})` : '无'}`);
164
+ line(`可用:${BODY_KINDS.map((k) => `${k}(${BODY_PROFILES[k].label})`).join(' / ')}`);
165
+ if (s.body) {
166
+ line('');
167
+ line('装了什么:');
168
+ for (const app of s.body.apps) line(` · ${app}`);
169
+ }
170
+ return;
124
171
  }
125
- break;
172
+ const b = brain.setBody(ID, kind, { ownership: args[1] });
173
+ line(`换好了:${bodyLine(b)}`);
174
+ return;
126
175
  }
127
- const b = brain.setBody(ID, kind, { ownership: args[1] });
128
- line(`换好了:${bodyLine(b)}`);
129
- break;
176
+
177
+ case 'rebirth': {
178
+ const relation = args[0] || 'parent';
179
+ const address = args[1] || '';
180
+ const dir = path.join(brainsDir(), ID);
181
+ if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
182
+ const b = brain.birth({ id: ID, relation, address });
183
+ line(`重开了一条鱼:${b.roleCard},${b.persona.units.length} 条命题,主导 ${b.self.styleName}`);
184
+ line(b.persona.brief);
185
+ return;
186
+ }
187
+
188
+ default:
189
+ line('用法:npx feiyu [status|brief|observe|settle|audit|spread|body|rebirth]');
130
190
  }
191
+ }
131
192
 
132
- default:
133
- line('用法:node cli.mjs [status|brief|observe|settle|audit|spread|body|rebirth]');
134
- process.exit(1);
193
+ try {
194
+ run();
195
+ } catch (e) {
196
+ if (isNoCard(e)) {
197
+ firstRunGuide();
198
+ process.exit(0); // 这不是错误,是还没开始
199
+ }
200
+ console.error(`出错了:${e?.message ?? e}`);
201
+ process.exit(1);
135
202
  }
package/core/apps.js ADDED
@@ -0,0 +1,279 @@
1
+ // 平台记忆:她在每个平台上看过什么、喜欢什么、上次停在哪。
2
+ //
3
+ // 这一层是"闭环"的下半截:
4
+ //
5
+ // 用户写的卡 → 决定先看什么 → 刷到 → 有反应 → 人设被改 → 口味变 → 刷的不一样
6
+ // ↑ │
7
+ // └──────────────────── 下一轮还是从人设出发 ────────────────────┘
8
+ //
9
+ // 所以这里有两套数:
10
+ // · 先验 priorTaste(traits) —— 从**当前**人设算,人设变了它立刻跟着变
11
+ // · 后验 seen[].reaction —— 她真的刷过、真的有反应
12
+ // 合起来 effectiveTaste(),再拿去 chooseContent()。
13
+ //
14
+ // 关键:人设是变量。新鱼的人格是用户写死的;刷得多了,traits 会被 nudgeTraits()
15
+ // 一点点改,于是下一次她爱看的东西就不一样了。
16
+
17
+ export const SEEN_MAX = 200;
18
+ export const TASTE_STEP = 0.05;
19
+ export const TRAIT_NUDGE = 0.004; // 每刷一条,特质最多动这么多
20
+
21
+ function clamp1(n) {
22
+ return Math.max(-1, Math.min(1, n));
23
+ }
24
+ function clamp01(n) {
25
+ return Math.max(0, Math.min(1, n));
26
+ }
27
+
28
+ /** 内容类型 ↔ 特质:谁爱看什么。这是"人设决定口味"的那张表。 */
29
+ export const AFFINITY = {
30
+ 解压: { 懒: 0.8, 理性: 0.3, 好动: -0.3 },
31
+ 搞笑: { 活泼: 0.9, 嘴硬: 0.4, 好奇: 0.3 },
32
+ 动物: { 心软: 0.9, 活泼: 0.3 },
33
+ 做饭: { 心软: 0.5, 懒: 0.4 },
34
+ 游戏: { 好动: 0.8, 好奇: 0.4 },
35
+ 科技: { 好奇: 0.9, 理性: 0.6 },
36
+ 情感: { 心软: 0.7, 敏感: 0.8 },
37
+ 历史: { 理性: 0.7, 好奇: 0.5 },
38
+ 离谱新闻: { 好奇: 0.6, 活泼: 0.4, 敏感: 0.2 },
39
+ 带货: { 理性: -0.6, 懒: -0.3 },
40
+ };
41
+
42
+ /**
43
+ * 刷这类内容会把她变成什么样。
44
+ *
45
+ * 跟 AFFINITY 不是同一张表——AFFINITY 是"什么样的人爱看什么"(选片用),
46
+ * NUDGE 是"看了会变成什么样"(改人设用)。混用会出事:
47
+ * 解压类里带 0.3 的"理性"权重,如果拿去做 nudge,看 100 条解压视频她会变理性——
48
+ * 这不对。看得多只会更懒。
49
+ */
50
+ export const NUDGE = {
51
+ 解压: { 懒: 1.0, 好动: -0.6 },
52
+ 搞笑: { 活泼: 1.0, 嘴硬: 0.4 },
53
+ 动物: { 心软: 1.0 },
54
+ 做饭: { 心软: 0.5, 懒: 0.5 },
55
+ 游戏: { 好动: 1.0, 好奇: 0.3 },
56
+ 科技: { 好奇: 0.8, 理性: 0.5 },
57
+ 情感: { 敏感: 1.0, 心软: 0.5 },
58
+ 历史: { 理性: 0.8, 好奇: 0.4 },
59
+ 离谱新闻: { 好奇: 0.8, 活泼: 0.4 },
60
+ 带货: { 理性: -0.6 },
61
+ };
62
+
63
+ /** 平台 ↔ 特质:她会先摸哪个 App。 */
64
+ export const APP_AFFINITY = {
65
+ douyin: { 好动: 0.7, 活泼: 0.6, 懒: 0.3 },
66
+ bilibili: { 好奇: 0.6, 理性: 0.5, 懒: 0.4 },
67
+ qq: { 社交: 0.8, 活泼: 0.3 },
68
+ wechat: { 社交: 0.7, 心软: 0.4 },
69
+ kuaishou: { 活泼: 0.5, 好动: 0.5 },
70
+ weibo: { 好奇: 0.5, 活泼: 0.4, 敏感: 0.3 },
71
+ };
72
+
73
+ export function emptyApps() {
74
+ return {};
75
+ }
76
+
77
+ /**
78
+ * 从**当前**人设推出先验口味。
79
+ * 注意:每次调用都按最新的 traits 算——所以人设一漂,口味立刻跟着漂。
80
+ */
81
+ export function priorTaste(traits = {}) {
82
+ const out = {};
83
+ for (const [kind, weights] of Object.entries(AFFINITY)) {
84
+ let score = 0;
85
+ for (const [trait, w] of Object.entries(weights)) {
86
+ score += (traits[trait] ?? 0.5) * w;
87
+ }
88
+ out[kind] = clamp1(score / 2);
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** 先验 + 经历 → 她"现在"的口味。人设占七成,刷出来的占三成。 */
94
+ export function effectiveTaste(memory, app, traits = {}) {
95
+ const prior = priorTaste(traits);
96
+ const learned = memory?.apps?.[app]?.taste ?? {};
97
+ const out = {};
98
+ for (const kind of new Set([...Object.keys(prior), ...Object.keys(learned)])) {
99
+ out[kind] = clamp1((prior[kind] ?? 0) * 0.7 + (learned[kind] ?? 0) * 0.3);
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * 刷到一条内容,反过来改人设。
106
+ *
107
+ * 这就是用户说的"人设是因为刷了视频才慢慢变的":
108
+ * 看了 100 条解压视频,她"懒"的那条特质就真的涨了一点。
109
+ *
110
+ * @returns {{traits:object, delta:object}} 新的 traits 和各特质变化量
111
+ */
112
+ export function nudgeTraits(traits = {}, kind = '', reaction = 0) {
113
+ const aff = NUDGE[kind];
114
+ if (!aff || !reaction) return { traits, delta: {} };
115
+ const next = { ...traits };
116
+ const delta = {};
117
+ for (const [trait, w] of Object.entries(aff)) {
118
+ const d = clamp1(reaction) * w * TRAIT_NUDGE;
119
+ if (!d) continue;
120
+ const before = next[trait] ?? 0.5;
121
+ next[trait] = clamp01(before + d);
122
+ delta[trait] = Number((next[trait] - before).toFixed(4));
123
+ }
124
+ return { traits: next, delta };
125
+ }
126
+
127
+ /** 取某个平台的桶(没有就建) */
128
+ export function appBucket(memory, app) {
129
+ const name = String(app || '').trim();
130
+ if (!name) return null;
131
+ if (!memory.apps) memory.apps = {};
132
+ if (!memory.apps[name]) {
133
+ memory.apps[name] = { minutes: 0, seen: [], taste: {}, lastLeft: null, firstAt: Date.now(), lastAt: 0 };
134
+ }
135
+ return memory.apps[name];
136
+ }
137
+
138
+ /**
139
+ * 记一条"她在某平台看到了什么"。
140
+ *
141
+ * @param {object} memory
142
+ * @param {string} app 平台名:douyin / bilibili / wechat / qq / kuaishou / 任意
143
+ * @param {object} item
144
+ * @param {string} item.title 看到的东西
145
+ * @param {string} [item.kind] 类型(解压/搞笑/做饭…),决定口味
146
+ * @param {number} [item.reaction] 她的反应,-1 ~ 1
147
+ * @param {number} [item.minutes] 这次待了多久
148
+ */
149
+ export function recordSeen(memory, app, item = {}) {
150
+ const b = appBucket(memory, app);
151
+ if (!b) return null;
152
+
153
+ const at = Date.now();
154
+ const entry = {
155
+ at,
156
+ title: String(item.title ?? '').slice(0, 80),
157
+ kind: String(item.kind ?? ''),
158
+ reaction: Number.isFinite(item.reaction) ? clamp1(item.reaction) : 0,
159
+ };
160
+ b.seen.push(entry);
161
+ if (b.seen.length > SEEN_MAX) b.seen.splice(0, b.seen.length - SEEN_MAX);
162
+
163
+ if (entry.kind && entry.reaction !== 0) {
164
+ b.taste[entry.kind] = clamp1((b.taste[entry.kind] ?? 0) + TASTE_STEP * entry.reaction);
165
+ }
166
+
167
+ b.minutes = Number(b.minutes ?? 0) + Math.max(0, Number(item.minutes) || 0);
168
+ b.lastAt = at;
169
+ b.lastLeft = { at, item: entry.title, kind: entry.kind };
170
+ return entry;
171
+ }
172
+
173
+ /** 她在某平台最喜欢什么(传 traits 就按当前人设算,不传就看纯经历) */
174
+ export function appTaste(memory, app, { limit = 5, traits = null } = {}) {
175
+ const b = memory?.apps?.[app];
176
+ if (!b) return [];
177
+ const table = traits ? effectiveTaste(memory, app, traits) : (b.taste ?? {});
178
+ return Object.entries(table)
179
+ .sort((a, z) => z[1] - a[1])
180
+ .slice(0, limit)
181
+ .map(([kind, score]) => ({ kind, score: Number(score.toFixed(2)) }));
182
+ }
183
+
184
+ /** 某平台最近的印象(新的在前) */
185
+ export function recallApp(memory, app, { limit = 5 } = {}) {
186
+ const b = memory?.apps?.[app];
187
+ if (!b) return [];
188
+ return b.seen.slice(-limit).reverse();
189
+ }
190
+
191
+ /**
192
+ * 她此刻会更想刷哪个 App —— 由当前人设算。
193
+ * 换了卡、或者刷久了人设变了,摸出来的 App 就不一样。
194
+ */
195
+ export function chooseApp(traits = {}, rng = Math.random) {
196
+ const scores = {};
197
+ for (const [app, weights] of Object.entries(APP_AFFINITY)) {
198
+ let s = 0;
199
+ for (const [trait, w] of Object.entries(weights)) s += (traits[trait] ?? 0.5) * w;
200
+ scores[app] = Math.max(0, s);
201
+ }
202
+ const total = Object.values(scores).reduce((a, b) => a + b, 0);
203
+ if (total <= 0) return 'douyin';
204
+ let r = rng() * total;
205
+ for (const [app, s] of Object.entries(scores)) {
206
+ r -= s;
207
+ if (r <= 0) return app;
208
+ }
209
+ return 'douyin';
210
+ }
211
+
212
+ /**
213
+ * 从那批内容里挑一条她想看的。
214
+ *
215
+ * pool = [{ title, kind }]
216
+ * 权重 = 当前口味(先验 0.7 + 经历 0.3),负分也能抽,只是概率低。
217
+ */
218
+ export function chooseContent(traits = {}, memory = null, app = '', pool = [], rng = Math.random) {
219
+ if (!Array.isArray(pool) || !pool.length) return null;
220
+ const taste = memory ? effectiveTaste(memory, app, traits) : priorTaste(traits);
221
+ const weighted = pool.map((item) => {
222
+ const kind = String(item.kind ?? '');
223
+ const t = taste[kind] ?? 0;
224
+ return { item, w: Math.max(0.02, t + 0.8) }; // 再不喜欢也有 2% 概率,别锁死
225
+ });
226
+ const total = weighted.reduce((a, b) => a + b.w, 0);
227
+ let r = rng() * total;
228
+ for (const { item, w } of weighted) {
229
+ r -= w;
230
+ if (r <= 0) return item;
231
+ }
232
+ return weighted[weighted.length - 1].item;
233
+ }
234
+
235
+ /** 她在这件事上"见过类似的吗"——跨平台找最接近的标题 */
236
+ export function similarSeen(memory, text, { limit = 3 } = {}) {
237
+ const q = String(text ?? '').trim();
238
+ if (!q) return [];
239
+ const hits = [];
240
+ for (const [app, b] of Object.entries(memory?.apps ?? {})) {
241
+ for (const item of b.seen ?? []) {
242
+ if (!item.title) continue;
243
+ const overlap = bigramOverlap(q, item.title);
244
+ if (overlap >= 0.3) hits.push({ app, ...item, score: overlap });
245
+ }
246
+ }
247
+ return hits.sort((a, z) => z.score - a.score || z.at - a.at).slice(0, limit);
248
+ }
249
+
250
+ function bigrams(s) {
251
+ const clean = String(s).replace(/[\s,。;、!?,.!?;:"'()()【】\[\]]/g, '');
252
+ const set = new Set();
253
+ for (let i = 0; i < clean.length - 1; i += 1) set.add(clean.slice(i, i + 2));
254
+ return set;
255
+ }
256
+
257
+ function bigramOverlap(a, b) {
258
+ const A = bigrams(a);
259
+ const B = bigrams(b);
260
+ if (!A.size || !B.size) return 0;
261
+ let n = 0;
262
+ for (const g of A) if (B.has(g)) n += 1;
263
+ return n / Math.min(A.size, B.size);
264
+ }
265
+
266
+ /** 一页摘要:每个平台刷了多久、最爱什么、最后停在什么 */
267
+ export function appSummary(memory, traits = null) {
268
+ const out = {};
269
+ for (const [app, b] of Object.entries(memory?.apps ?? {})) {
270
+ out[app] = {
271
+ seen: (b.seen ?? []).length,
272
+ minutes: Math.round(b.minutes ?? 0),
273
+ favorite: appTaste(memory, app, { limit: 2, traits }),
274
+ lastLeft: b.lastLeft?.item ?? null,
275
+ lastAt: b.lastAt ?? null,
276
+ };
277
+ }
278
+ return out;
279
+ }