feiyu-brain 1.4.2 → 1.5.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 +160 -5
- package/adapters/qq-bridge.js +169 -26
- package/cli.mjs +276 -3
- package/cordis.patch.yml +32 -2
- package/core/body.js +13 -1
- package/core/bond.js +186 -0
- package/core/concept.js +138 -0
- package/core/diary.js +119 -0
- package/core/extract.js +124 -12
- package/core/memory.js +539 -18
- package/core/migrate.js +170 -0
- package/core/persona.js +91 -4
- package/core/relation.js +78 -0
- package/core/self.js +72 -0
- package/docs/ADAPTER-CONTRACT.md +101 -0
- package/docs/CHANGELOG-1.5.md +136 -0
- package/docs/MEMORY.md +454 -0
- package/docs/TROUBLESHOOT.md +136 -0
- package/index.js +1294 -56
- package/lib/doctor.mjs +181 -0
- package/lib/dsh-plugin.mjs +197 -15
- package/lib/serve.mjs +187 -0
- package/market/fangqiuci__feiyu-brain.yml +2 -2
- package/package.json +3 -2
- package/selftest.mjs +37 -3
- package/store.js +172 -13
package/index.js
CHANGED
|
@@ -10,17 +10,22 @@ 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';
|
|
14
|
-
import { brief, decay, evolve, shed, weightReport } from './core/persona.js';
|
|
13
|
+
import { birthFromCard, lintCard, TRAIT_LEXICON } from './core/extract.js';
|
|
14
|
+
import { brief, decay, evolve, shed, weightReport, shellSummary, recentShift } 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';
|
|
17
|
-
import { emptyMemory, addEpisode, addImagination, recall, settle, retrieve } from './core/memory.js';
|
|
18
|
-
import {
|
|
17
|
+
import { emptyMemory, addEpisode, addImagination, recall, settle, retrieve, touchByIds, distillGists, distillUmbrellas, nameFaded, detectRepeat, markImportant, markImportantByTopic, isRepeatNoise, textSimilarity, IMPORTANT_REPEAT, IMPORTANT_WINDOW_DAYS } from './core/memory.js';
|
|
18
|
+
import { addBond, bondDelta, bondOf, bondLine, decayBonds, bondSensitivity, markBondAbsent, clearBondAbsent, bondAbsentOf, ABSENT_MIN_TIER, BOND_TIERS, BOND_MAX } from './core/bond.js';
|
|
19
|
+
import { learnConcept, conceptOf, conceptAnswer, conceptsIn, makeQuestion } from './core/concept.js';
|
|
20
|
+
import { composeNarrative, narrativeChanged, NARRATIVE_MAX } from './core/self.js';
|
|
21
|
+
import { createContract, markAbsent as markAbsentContract, clearAbsent as clearAbsentRelation, relationLine, isAbsent } from './core/relation.js';
|
|
19
22
|
import { attribute, LABELS } from './core/attribution.js';
|
|
20
23
|
import { check } from './core/invariants.js';
|
|
21
24
|
import { toCue, toObservation, shouldObserve, normalizeEvent } from './core/event.js';
|
|
22
25
|
import * as emotion from './core/emotion.js';
|
|
23
26
|
import { makeCard, addCard, shouldCompact } from './core/memory.js';
|
|
27
|
+
import { parseAny, dedupe, MIGRATE_FORMATS } from './core/migrate.js';
|
|
28
|
+
import { dayKey, dayDigest } from './core/diary.js';
|
|
24
29
|
import { driverFor } from './core/driver.js';
|
|
25
30
|
import {
|
|
26
31
|
recordSeen, recallApp, appTaste, appSummary, similarSeen, emptyApps,
|
|
@@ -28,12 +33,22 @@ import {
|
|
|
28
33
|
} from './core/apps.js';
|
|
29
34
|
import {
|
|
30
35
|
ROOT, loadBrain, saveBrain, appendAudit, readAudit, listBrains,
|
|
31
|
-
setDataDir, setRoleDir, dataDir, roleDir,
|
|
36
|
+
setDataDir, setRoleDir, dataDir, roleDir, brainDir, dataDirSource, isDataDirInsidePackage,
|
|
37
|
+
setEpisodeWindow, episodeWindow, readYear, listYears,
|
|
32
38
|
} from './store.js';
|
|
33
39
|
|
|
34
40
|
const DEFAULT_ID = 'default';
|
|
35
41
|
const cache = new Map();
|
|
36
42
|
|
|
43
|
+
/* 全局开关(configure 改) */
|
|
44
|
+
let shadowMode = false; // 影子模式:算但不写人设,全记进 shadow.jsonl
|
|
45
|
+
let ttlPolicy = 'hard'; // hard | summarize | archive | off
|
|
46
|
+
let moodPolicy = 'brain'; // 情绪双源:brain(脑说了算)| host(宿主说了算)| blend(各一半)
|
|
47
|
+
let compressDays = 21; // 完整期:21 天没人提 → 压成卡片
|
|
48
|
+
let forgetDays = 730; // 卡片期:2 年没人提 → 遗忘
|
|
49
|
+
let briefChars = 300; // 「此刻的她」多长;老鱼可以调大
|
|
50
|
+
let maxEpisodes = 5000; // 脑里最多存多少条,超了最老的压卡片
|
|
51
|
+
|
|
37
52
|
function nowMs() {
|
|
38
53
|
return Date.now();
|
|
39
54
|
}
|
|
@@ -46,10 +61,92 @@ function logOnce(msg) {
|
|
|
46
61
|
try { console.warn(msg); } catch { /* 没有 console 也不影响 */ }
|
|
47
62
|
}
|
|
48
63
|
|
|
49
|
-
/**
|
|
50
|
-
|
|
64
|
+
/**
|
|
65
|
+
* 宿主初始化:指定数据目录和角色卡目录。
|
|
66
|
+
*
|
|
67
|
+
* configure({ dataDir, roleDir })
|
|
68
|
+
* configure({ shadow: true }) 影子模式:observe 只留审计,不动人设、不落盘
|
|
69
|
+
* configure({ ttlPolicy: 'off' }) hard(默认) | summarize(过期前压卡片) | off(永不遗忘)
|
|
70
|
+
*/
|
|
71
|
+
/**
|
|
72
|
+
* 宿主初始化。
|
|
73
|
+
*
|
|
74
|
+
* configure({ dataDir, roleDir })
|
|
75
|
+
* configure({ shadow: true }) 影子模式:算但不写人设,全记进 shadow.jsonl
|
|
76
|
+
* configure({ ttlPolicy: 'off' }) hard(默认) | summarize | archive | off
|
|
77
|
+
* configure({ moodPolicy: 'host' }) brain | host | blend
|
|
78
|
+
* configure({ compressDays: 30 }) 多少天没人提就压扁
|
|
79
|
+
* configure({ forgetDays: 90 }) 多少天没人提就遗忘
|
|
80
|
+
* configure({ briefChars: 300 }) 「此刻的她」多长(老鱼可以调到 600)
|
|
81
|
+
* configure({ maxEpisodes: 5000 }) 脑里最多存多少条
|
|
82
|
+
*/
|
|
83
|
+
export function configure({
|
|
84
|
+
dataDir: d, roleDir: r, shadow, ttl, mood,
|
|
85
|
+
compressDays: cd, forgetDays: fd, briefChars: bc, maxEpisodes: me,
|
|
86
|
+
} = {}) {
|
|
51
87
|
if (d) setDataDir(d);
|
|
52
88
|
if (r) setRoleDir(r);
|
|
89
|
+
if (typeof shadow === 'boolean') shadowMode = shadow;
|
|
90
|
+
if (ttl && ['hard', 'summarize', 'archive', 'off'].includes(ttl)) ttlPolicy = ttl;
|
|
91
|
+
if (mood && ['brain', 'host', 'blend'].includes(mood)) moodPolicy = mood;
|
|
92
|
+
if (Number.isFinite(cd) && cd > 0) compressDays = Math.floor(cd);
|
|
93
|
+
if (Number.isFinite(fd) && fd > compressDays) forgetDays = Math.floor(fd);
|
|
94
|
+
// 经历按年分片:打开时只加载 forgetDays 窗口内的年份(16 年也不会越读越慢)
|
|
95
|
+
setEpisodeWindow(forgetDays);
|
|
96
|
+
if (Number.isFinite(bc) && bc >= 100) briefChars = Math.floor(bc);
|
|
97
|
+
if (Number.isFinite(me) && me >= 100) maxEpisodes = Math.floor(me);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function runtimeOptions() {
|
|
101
|
+
return {
|
|
102
|
+
shadow: shadowMode,
|
|
103
|
+
ttlPolicy,
|
|
104
|
+
moodPolicy,
|
|
105
|
+
compressDays,
|
|
106
|
+
forgetDays,
|
|
107
|
+
briefChars,
|
|
108
|
+
maxEpisodes,
|
|
109
|
+
dataDir: dataDir(),
|
|
110
|
+
dataDirSource: dataDirSource(),
|
|
111
|
+
dataDirInsidePackage: isDataDirInsidePackage(),
|
|
112
|
+
roleDir: roleDir(),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 情绪双源仲裁。
|
|
118
|
+
*
|
|
119
|
+
* 宿主往往已经有自己的情绪系统(比如 state/emotion.json)。两边都能改情绪时必须定个优先级:
|
|
120
|
+
*
|
|
121
|
+
* brain (默认) 宿主推过来的直接忽略,脑说了算
|
|
122
|
+
* host 情绪以宿主为准,`feel()` 只算不写
|
|
123
|
+
* blend 各占一半
|
|
124
|
+
*/
|
|
125
|
+
export function syncMood(id = DEFAULT_ID, pad = [], { policy } = {}) {
|
|
126
|
+
const brain = ensureBrain(id);
|
|
127
|
+
const p = ['brain', 'host', 'blend'].includes(policy) ? policy : moodPolicy;
|
|
128
|
+
const host = [0, 1, 2].map((i) => {
|
|
129
|
+
const v = Number(pad?.[i]);
|
|
130
|
+
return Number.isFinite(v) ? Math.max(-1, Math.min(1, v)) : 0;
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
if (p === 'brain') {
|
|
134
|
+
return { ok: true, ignored: true, policy: p, affect: brain.affect };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const cur = [Number(brain.affect?.p) || 0, Number(brain.affect?.a) || 0, Number(brain.affect?.d) || 0];
|
|
138
|
+
const next = p === 'host' ? host : cur.map((c, i) => Number(((c + host[i]) / 2).toFixed(4)));
|
|
139
|
+
|
|
140
|
+
brain.affect = {
|
|
141
|
+
...brain.affect,
|
|
142
|
+
p: next[0],
|
|
143
|
+
a: next[1],
|
|
144
|
+
d: next[2],
|
|
145
|
+
moodSource: p,
|
|
146
|
+
};
|
|
147
|
+
saveBrain(brain);
|
|
148
|
+
appendAudit(id, { kind: 'mood-sync', policy: p, pad: next });
|
|
149
|
+
return { ok: true, ignored: false, policy: p, affect: brain.affect };
|
|
53
150
|
}
|
|
54
151
|
|
|
55
152
|
/** 读角色卡:优先显式名字,否则读 state/current-role.json。 */
|
|
@@ -72,7 +169,7 @@ export function resolveRoleCard(roleName) {
|
|
|
72
169
|
}
|
|
73
170
|
|
|
74
171
|
function refreshBrief(brain) {
|
|
75
|
-
brain.persona.brief = brief(brain.persona.units);
|
|
172
|
+
brain.persona.brief = brief(brain.persona.units, { maxChars: briefChars });
|
|
76
173
|
return brain;
|
|
77
174
|
}
|
|
78
175
|
|
|
@@ -107,7 +204,10 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
107
204
|
if (fs.existsSync(sidecar)) traitsOverride = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
|
|
108
205
|
} catch { traitsOverride = null; }
|
|
109
206
|
|
|
110
|
-
const { traits, units } = birthFromCard(card.text, { traitsOverride });
|
|
207
|
+
const { traits, units, knownTraits, openTraits } = birthFromCard(card.text, { traitsOverride });
|
|
208
|
+
// 命题的"最后一次被碰到"从出生算起——不然一条新鱼第一天就开始褪色
|
|
209
|
+
const born = nowMs();
|
|
210
|
+
for (const u of units) { u.lastTouched = born; u.born = born; }
|
|
111
211
|
const brain = {
|
|
112
212
|
id,
|
|
113
213
|
schema: 'brain/2',
|
|
@@ -116,8 +216,16 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
116
216
|
persona: {
|
|
117
217
|
seed: cardName ? `card:${card.name}` : `${roleDir()}/${card.name}.md`,
|
|
118
218
|
traits,
|
|
219
|
+
// 已知 12 维(先验)与她自己长出来的维度分开存,方便看"哪些是她的原话"
|
|
220
|
+
knownTraits: knownTraits ?? traits,
|
|
221
|
+
openTraits: openTraits ?? {},
|
|
119
222
|
units,
|
|
120
223
|
brief: '',
|
|
224
|
+
// 一年一度蜕壳:把这一年掉出去的人设打包成永久记忆卡片
|
|
225
|
+
shellYear: new Date(born).getFullYear(),
|
|
226
|
+
shellAt: born,
|
|
227
|
+
// 最近几天的权重变动,用来生成「最近」那一段
|
|
228
|
+
moves: [],
|
|
121
229
|
// 人格主档只有一个:这里。外部卡只是"导入源",导过就记下来。
|
|
122
230
|
source: {
|
|
123
231
|
kind: cardText ? 'inline' : 'file',
|
|
@@ -138,7 +246,13 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
138
246
|
// 身体:手机 / 平板 / 电脑。没指定就按人设算——好动的摸手机,爱折腾的开电脑。
|
|
139
247
|
body: createBody({ kind: body ?? chooseBody(traits, {}, mulberry32(hashTraits(traits))) }),
|
|
140
248
|
patience: 1,
|
|
141
|
-
meta: {
|
|
249
|
+
meta: {
|
|
250
|
+
lastSettle: nowMs(),
|
|
251
|
+
observations: 0,
|
|
252
|
+
version: '1.5.0',
|
|
253
|
+
shadow: shadowMode,
|
|
254
|
+
contractWarnings: [],
|
|
255
|
+
},
|
|
142
256
|
};
|
|
143
257
|
|
|
144
258
|
brain.self.styleName = dominantStyle(brain.self.style);
|
|
@@ -171,39 +285,109 @@ export function getBrief(id = DEFAULT_ID) {
|
|
|
171
285
|
* 接受两种入参:
|
|
172
286
|
* - 通用事件 { sender, text, ... }
|
|
173
287
|
* - 线索 { who, words }
|
|
288
|
+
*
|
|
289
|
+
* 第三参数用来"点菜"——叠加到别人已有的系统里时,只取你要的那几段:
|
|
290
|
+
*
|
|
291
|
+
* wakeLine(id, cue) // 全给(默认)
|
|
292
|
+
* wakeLine(id, cue, { sections: ['mood'] }) // 只要心情,约 20 字
|
|
293
|
+
* wakeLine(id, cue, { sections: ['mood','memory'], budget: 300 })
|
|
294
|
+
*
|
|
295
|
+
* sections 可选:persona / flow / body / mood / memory / search
|
|
296
|
+
* budget 是**总字数上限**,超了就从低优先级的段开始砍(persona 保底不砍)。
|
|
174
297
|
*/
|
|
175
|
-
export
|
|
298
|
+
export const WAKE_SECTIONS = ['persona', 'self', 'relation', 'bond', 'concept', 'flow', 'body', 'mood', 'recent', 'memory', 'search'];
|
|
299
|
+
/** 预算不够时的砍法:越靠后越先砍 */
|
|
300
|
+
const WAKE_PRIORITY = ['persona', 'self', 'relation', 'concept', 'bond', 'mood', 'recent', 'flow', 'memory', 'body', 'search'];
|
|
301
|
+
|
|
302
|
+
export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
176
303
|
const brain = ensureBrain(id);
|
|
177
304
|
if (!brain.persona.brief) refreshBrief(brain);
|
|
178
305
|
|
|
306
|
+
const want = Array.isArray(opts?.sections) && opts.sections.length
|
|
307
|
+
? new Set(opts.sections.filter((s) => WAKE_SECTIONS.includes(s)))
|
|
308
|
+
: new Set(WAKE_SECTIONS);
|
|
309
|
+
const budget = Number.isFinite(opts?.budget) ? Number(opts.budget) : Infinity;
|
|
310
|
+
|
|
179
311
|
const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
|
|
180
312
|
brain.state.flow = level;
|
|
181
|
-
|
|
313
|
+
|
|
314
|
+
const seg = { persona: `【此刻的她】${brain.persona.brief}` };
|
|
315
|
+
|
|
316
|
+
// 「我是谁」——会跟着经历长的那一句
|
|
317
|
+
const nar = brain.self?.narrativeText ?? brain.self?.narrative;
|
|
318
|
+
if (nar) seg.self = `【我是谁】${nar}`;
|
|
319
|
+
|
|
320
|
+
// 缺位:那个人不在了。关系没断,但状态要说出来——
|
|
321
|
+
// 不写"想念",只给事实,怎么感受由她的人设决定。
|
|
322
|
+
const relLine = relationLine(brain.relation);
|
|
323
|
+
if (relLine) seg.relation = `【他】${relLine}`;
|
|
324
|
+
|
|
325
|
+
// 恩情:除了主人,还有谁对她好过——这是她自己算的,不是标签
|
|
326
|
+
const bonded = Object.keys(brain.memory.bonds ?? {})
|
|
327
|
+
.filter((w) => w !== brain.relation?.address)
|
|
328
|
+
.map((w) => bondOf(brain.memory, w))
|
|
329
|
+
.filter((b) => b.tier !== 'stranger')
|
|
330
|
+
.sort((a, b) => b.score - a.score)
|
|
331
|
+
.slice(0, 2);
|
|
332
|
+
if (bonded.length) {
|
|
333
|
+
seg.bond = `【他们】${bonded.map((b) => bondLine(brain.memory, b.who)).join(';')}`;
|
|
334
|
+
}
|
|
335
|
+
if (level !== 1) seg.flow = `【意识流】${flowName(level)}`;
|
|
336
|
+
|
|
182
337
|
const bodyText = bodyLine(brain.body);
|
|
183
|
-
if (bodyText)
|
|
338
|
+
if (bodyText) seg.body = `【手上的东西】${bodyText}`;
|
|
184
339
|
|
|
185
|
-
|
|
340
|
+
// 心情段:还没学会词的时候不能说"不知道",要给出身体感受——
|
|
341
|
+
// 否则只要心情的宿主会拿到一个空段。
|
|
186
342
|
const mood = brain.affect?.mood;
|
|
187
|
-
if (mood && mood !== '平静'
|
|
343
|
+
if (mood && mood !== '平静') {
|
|
344
|
+
seg.mood = mood === '说不上来'
|
|
345
|
+
? `【心情】${emotion.describeSensation([brain.affect.p ?? 0, brain.affect.a ?? 0, brain.affect.d ?? 0])}`
|
|
346
|
+
: `【心情】${mood}`;
|
|
347
|
+
}
|
|
188
348
|
|
|
189
349
|
const cue = eventOrCue?.who !== undefined ? eventOrCue : toCue(eventOrCue);
|
|
350
|
+
|
|
351
|
+
// 概念:这次聊到的东西她到底懂不懂
|
|
352
|
+
const cs = conceptsIn(brain.memory, cue?.text ?? '');
|
|
353
|
+
if (cs.length) {
|
|
354
|
+
seg.concept = `【她懂的】${cs.map((c) => `${c.term}:${c.definition}${c.why ? `(${c.why})` : ''}`).join(';')}`;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// 「最近」:每天 ±0.01 看不出来,七天攒起来就能说一句
|
|
358
|
+
const shift = recentShift(brain.persona.moves, brain.persona.units, { at: nowMs() });
|
|
359
|
+
if (shift) seg.recent = `【最近】${shift.line}`;
|
|
190
360
|
if (cue) {
|
|
191
361
|
const hit = retrieve(cue, brain.memory);
|
|
192
|
-
if (hit.text)
|
|
362
|
+
if (hit.text) seg.memory = `【想到的】\n${hit.text}`;
|
|
363
|
+
// 「被想起来」也算提起:检索命中的记忆会续命,一直没人想起的才会老化
|
|
364
|
+
if (hit.items?.length) touchByIds(brain.memory, hit.items.map((i) => i.id), nowMs());
|
|
193
365
|
|
|
194
366
|
// 外部检索器(向量/图谱):同步读缓存,不 await
|
|
195
367
|
if (extraRetriever) {
|
|
196
368
|
try {
|
|
197
369
|
const extra = extraRetriever(cue, brain.memory) ?? [];
|
|
198
370
|
const lines = (Array.isArray(extra) ? extra : []).filter(Boolean).slice(0, 3);
|
|
199
|
-
if (lines.length)
|
|
371
|
+
if (lines.length) seg.search = `【搜到的】\n${lines.join('\n')}`;
|
|
200
372
|
} catch (e) {
|
|
201
373
|
// 检索器坏了不能拖垮唤醒
|
|
202
374
|
logOnce(`[brain] 外部检索器出错(已忽略):${e?.message ?? e}`);
|
|
203
375
|
}
|
|
204
376
|
}
|
|
205
377
|
}
|
|
206
|
-
|
|
378
|
+
|
|
379
|
+
const out = [];
|
|
380
|
+
let used = 0;
|
|
381
|
+
for (const key of WAKE_PRIORITY) {
|
|
382
|
+
if (!want.has(key)) continue;
|
|
383
|
+
const text = seg[key];
|
|
384
|
+
if (!text) continue;
|
|
385
|
+
// persona 是根,再穷也得给;其余按预算砍
|
|
386
|
+
if (key !== 'persona' && used + text.length > budget) continue;
|
|
387
|
+
out.push(text);
|
|
388
|
+
used += text.length;
|
|
389
|
+
}
|
|
390
|
+
return out.join('\n');
|
|
207
391
|
}
|
|
208
392
|
|
|
209
393
|
/**
|
|
@@ -211,10 +395,18 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null) {
|
|
|
211
395
|
*
|
|
212
396
|
* event = { sender, text, ... } ← 适配器直接传
|
|
213
397
|
* event = { consistent, conflicting, ... } ← 高级用法
|
|
398
|
+
*
|
|
399
|
+
* 第三参数 opts:
|
|
400
|
+
* evolve = true 记经历的同时,改人设权重(默认)
|
|
401
|
+
* = false **只记经历,不碰人设** —— 叠加到别人已有的人格系统时用这个,
|
|
402
|
+
* 免得两套各说各话、token 翻倍
|
|
403
|
+
* remember = true 写进记忆(默认)
|
|
214
404
|
*/
|
|
215
|
-
export function observe(id = DEFAULT_ID, event = {}) {
|
|
405
|
+
export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
216
406
|
const brain = ensureBrain(id);
|
|
217
407
|
const at = nowMs();
|
|
408
|
+
const doEvolve = opts?.evolve !== false;
|
|
409
|
+
const doRemember = opts?.remember !== false;
|
|
218
410
|
|
|
219
411
|
const ev = event.consistent || event.conflicting || !event.sender
|
|
220
412
|
? event
|
|
@@ -223,17 +415,82 @@ export function observe(id = DEFAULT_ID, event = {}) {
|
|
|
223
415
|
const consistent = ev.consistent ?? matchUnits(brain.persona.units, ev.text ?? '').consistent;
|
|
224
416
|
const conflicting = ev.conflicting ?? matchUnits(brain.persona.units, ev.text ?? '').conflicting;
|
|
225
417
|
|
|
418
|
+
// ── 影子模式 ──
|
|
419
|
+
// 算但不写:人设权重、记忆、brain.json 一个字不动。
|
|
420
|
+
// 但**不是空跑**——这一次的「本来会发生什么」全记进 shadow.jsonl,
|
|
421
|
+
// 跑一百轮之后能看见她会长成什么样,再决定要不要真接。
|
|
422
|
+
if (shadowMode || brain.meta.shadow) {
|
|
423
|
+
const would = brain.persona.units
|
|
424
|
+
.filter((u) => consistent.includes(u.id) || conflicting.includes(u.id))
|
|
425
|
+
.map((u) => ({
|
|
426
|
+
id: u.id,
|
|
427
|
+
text: u.text.slice(0, 30),
|
|
428
|
+
from: Number(u.weight.toFixed(3)),
|
|
429
|
+
to: Number(Math.max(0, Math.min(1, u.weight + (consistent.includes(u.id) ? 1 : -1) * 0.01)).toFixed(3)),
|
|
430
|
+
}));
|
|
431
|
+
|
|
432
|
+
const entry = {
|
|
433
|
+
at,
|
|
434
|
+
text: String(ev.text ?? ev.what ?? '').slice(0, 100),
|
|
435
|
+
wouldChange: would,
|
|
436
|
+
wouldRemember: String(ev.what ?? ev.text ?? '').slice(0, 80),
|
|
437
|
+
app: ev.app ?? null,
|
|
438
|
+
};
|
|
439
|
+
appendAudit(id, { kind: 'shadow', shadow: true, at, text: entry.text, wouldChange: would });
|
|
440
|
+
try {
|
|
441
|
+
fs.appendFileSync(path.join(brainDir(id), 'shadow.jsonl'), `${JSON.stringify(entry)}\n`, 'utf8');
|
|
442
|
+
} catch (e) {
|
|
443
|
+
logOnce(`[brain] shadow 写入失败(已忽略):${e?.message ?? e}`);
|
|
444
|
+
}
|
|
445
|
+
return {
|
|
446
|
+
brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would, shadowFile: path.join(brainDir(id), 'shadow.jsonl'),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
226
450
|
// step:默认 1(每次 ±0.01)。只有传了 magnitude(重大转折)才放大,上限 5。
|
|
227
451
|
const step = Math.max(1, Math.min(5, Number(ev.magnitude) || 1));
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
brain.
|
|
235
|
-
|
|
236
|
-
|
|
452
|
+
if (doEvolve) {
|
|
453
|
+
const beforeW = new Map(brain.persona.units.map((u) => [u.id, u.weight]));
|
|
454
|
+
brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
|
|
455
|
+
|
|
456
|
+
// 记下这次的变动,攒成「最近」
|
|
457
|
+
const moves = [];
|
|
458
|
+
for (const u of brain.persona.units) {
|
|
459
|
+
const b = beforeW.get(u.id);
|
|
460
|
+
if (b !== undefined && b !== u.weight) {
|
|
461
|
+
moves.push({ id: u.id, delta: Number((u.weight - b).toFixed(4)), at });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (moves.length) {
|
|
465
|
+
brain.persona.moves = [...(brain.persona.moves ?? []), ...moves].slice(-300);
|
|
466
|
+
// 按年累计,供年底蜕壳时总结"这一年我变了什么"
|
|
467
|
+
const ym = brain.persona.yearMoves ?? {};
|
|
468
|
+
for (const m of moves) ym[m.id] = Number(((ym[m.id] ?? 0) + m.delta).toFixed(4));
|
|
469
|
+
brain.persona.yearMoves = ym;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// 蜕皮
|
|
473
|
+
const sh = shed(brain.persona.units, { at });
|
|
474
|
+
if (sh.formerSelves.length) {
|
|
475
|
+
brain.persona.units = sh.units;
|
|
476
|
+
brain.memory.formerSelves.push(...sh.formerSelves);
|
|
477
|
+
for (const f of sh.formerSelves) {
|
|
478
|
+
appendAudit(id, { kind: 'shed', id: f.id, weight: Number(f.weight.toFixed(3)), memoir: f.memoir });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// 带情绪的事件:先让她有感受,再记下来。
|
|
484
|
+
// 否则 episode 记的是"这件事之前"的心情,日记里就变成时间错位。
|
|
485
|
+
if (doRemember && Number.isFinite(Number(ev.valence))) {
|
|
486
|
+
try {
|
|
487
|
+
feel(id, {
|
|
488
|
+
valence: Math.max(-1, Math.min(1, Number(ev.valence))),
|
|
489
|
+
intensity: Number.isFinite(Number(ev.intensity)) ? Math.max(0, Math.min(1, Number(ev.intensity))) : 0.5,
|
|
490
|
+
what: ev.what ?? ev.text ?? '',
|
|
491
|
+
});
|
|
492
|
+
} catch (e) {
|
|
493
|
+
logOnce(`[brain] 事件自带情绪但算失败(已忽略):${e?.message ?? e}`);
|
|
237
494
|
}
|
|
238
495
|
}
|
|
239
496
|
|
|
@@ -241,8 +498,10 @@ export function observe(id = DEFAULT_ID, event = {}) {
|
|
|
241
498
|
const obs = ev.what
|
|
242
499
|
? ev
|
|
243
500
|
: (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) {
|
|
245
|
-
|
|
501
|
+
if (doRemember && obs?.what) {
|
|
502
|
+
// 反复出现的事 → 重要记忆,永不压扁
|
|
503
|
+
const rep = detectRepeat(brain.memory, { who: obs.who ?? '', what: obs.what }, at);
|
|
504
|
+
const ep = addEpisode(brain.memory, {
|
|
246
505
|
who: obs.who ?? '',
|
|
247
506
|
what: obs.what,
|
|
248
507
|
feel: ev.feel ?? '',
|
|
@@ -252,10 +511,18 @@ export function observe(id = DEFAULT_ID, event = {}) {
|
|
|
252
511
|
context: ev.context ?? null,
|
|
253
512
|
strategy: ev.action?.strategy ?? null,
|
|
254
513
|
evidence: obs.via ?? 'chat',
|
|
514
|
+
source: 'live',
|
|
515
|
+
...(rep.important ? { important: true, longTerm: true, importantCount: rep.count, importantSample: rep.sample } : {}),
|
|
255
516
|
}, at);
|
|
517
|
+
if (rep.important) {
|
|
518
|
+
// 追溯:之前提过的同话题也转重要,别让前两次被压成卡片
|
|
519
|
+
const back = markImportantByTopic(brain.memory, { who: obs.who ?? '', what: obs.what }, at);
|
|
520
|
+
appendAudit(id, { kind: 'important', count: rep.count, backfilled: back, what: String(obs.what).slice(0, 40) });
|
|
521
|
+
void ep;
|
|
522
|
+
}
|
|
256
523
|
}
|
|
257
524
|
|
|
258
|
-
if (ev.action) {
|
|
525
|
+
if (doRemember && ev.action) {
|
|
259
526
|
const label = attribute(ev.action, brain.memory);
|
|
260
527
|
appendAudit(id, { kind: 'attribution', label, strategy: ev.action.strategy });
|
|
261
528
|
brain.meta.lastLabel = label;
|
|
@@ -266,7 +533,7 @@ export function observe(id = DEFAULT_ID, event = {}) {
|
|
|
266
533
|
}
|
|
267
534
|
|
|
268
535
|
// 平台记忆:她刷到过什么(有 app 才记)
|
|
269
|
-
if (ev.app && (ev.title || ev.text)) {
|
|
536
|
+
if (doRemember && ev.app && (ev.title || ev.text)) {
|
|
270
537
|
recordSeen(brain.memory, ev.app, {
|
|
271
538
|
title: ev.title ?? String(ev.text).slice(0, 60),
|
|
272
539
|
kind: ev.kind ?? '',
|
|
@@ -277,30 +544,48 @@ export function observe(id = DEFAULT_ID, event = {}) {
|
|
|
277
544
|
|
|
278
545
|
// ── 闭环:刷到的东西反过来改人设 ──
|
|
279
546
|
// 看的解压视频多了,"懒"这条特质就真的涨一点;人设变了,下次爱看的就不一样。
|
|
280
|
-
|
|
281
|
-
if (
|
|
282
|
-
brain.persona.traits
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
547
|
+
// evolve:false 时这条也关掉——只当记忆库用,就不该偷偷改人设。
|
|
548
|
+
if (doEvolve) {
|
|
549
|
+
const { traits: nextTraits, delta } = nudgeTraits(brain.persona.traits, ev.kind ?? '', Number(ev.reaction) || 0);
|
|
550
|
+
if (Object.keys(delta).length) {
|
|
551
|
+
brain.persona.traits = nextTraits;
|
|
552
|
+
brain.self.style = styleVector(nextTraits);
|
|
553
|
+
brain.self.styleName = dominantStyle(brain.self.style);
|
|
554
|
+
appendAudit(id, { kind: 'trait-drift', app: ev.app, contentKind: ev.kind, delta });
|
|
555
|
+
}
|
|
286
556
|
}
|
|
287
557
|
}
|
|
288
558
|
|
|
289
559
|
// 关系记忆:互动次数
|
|
290
560
|
const who = ev.who ?? ev.sender;
|
|
291
|
-
if (who) {
|
|
561
|
+
if (doRemember && who) {
|
|
292
562
|
const im = brain.memory.impressions[who] ?? { traits: [], count: 0, lastAt: at };
|
|
293
563
|
im.count += 1;
|
|
294
564
|
im.lastAt = at;
|
|
295
565
|
if (ev.feel) im.traits = [...new Set([...(im.traits ?? []), ev.feel])].slice(-6);
|
|
296
566
|
brain.memory.impressions[who] = im;
|
|
567
|
+
|
|
568
|
+
// 恩情:谁对我好,是算出来的,不是写死的
|
|
569
|
+
// care = 真的照顾(充电、开窗、修我)base 8
|
|
570
|
+
// 普通互动 base 1;被凶了会扣
|
|
571
|
+
const isOwner = brain.relation?.address && who === brain.relation.address;
|
|
572
|
+
if (!isOwner) {
|
|
573
|
+
const base = ev.care ? 8 : 1;
|
|
574
|
+
const valence = Number.isFinite(Number(ev.valence)) ? Number(ev.valence) : 1;
|
|
575
|
+
const d = bondDelta({ traits: brain.persona.traits, base, valence });
|
|
576
|
+
if (d) {
|
|
577
|
+
addBond(brain.memory, who, { delta: d, at, what: ev.care ? 'care' : 'talk' });
|
|
578
|
+
const b = bondOf(brain.memory, who);
|
|
579
|
+
if (b.tier !== 'stranger') appendAudit(id, { kind: 'bond', who, delta: d, score: b.score, tier: b.tier });
|
|
580
|
+
}
|
|
581
|
+
}
|
|
297
582
|
}
|
|
298
583
|
|
|
299
584
|
brain.meta.observations += 1;
|
|
300
585
|
brain.meta.lastObservationAt = at;
|
|
301
586
|
refreshBrief(brain);
|
|
302
587
|
saveBrain(brain);
|
|
303
|
-
return { brain, consistent, conflicting, label: brain.meta.lastLabel };
|
|
588
|
+
return { brain, consistent, conflicting, label: brain.meta.lastLabel, evolved: doEvolve, remembered: doRemember };
|
|
304
589
|
}
|
|
305
590
|
|
|
306
591
|
/** 关键词匹配:粗但确定(中文按二元组)。 */
|
|
@@ -327,25 +612,204 @@ function bigrams(text) {
|
|
|
327
612
|
return set;
|
|
328
613
|
}
|
|
329
614
|
|
|
330
|
-
/**
|
|
615
|
+
/**
|
|
616
|
+
* 每日结算:人设衰减 + 记忆两层老化(压扁 → 遗忘)+ 蜕皮。幂等,可以随便跑。
|
|
617
|
+
*
|
|
618
|
+
* 老化不是"到期删除":先压扁成一句"大概",再更久没人提才真正遗忘。
|
|
619
|
+
* 全程把原文摊进 archive.jsonl——**忘的是检索,不是档案。**
|
|
620
|
+
*/
|
|
331
621
|
export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
|
|
332
622
|
const brain = ensureBrain(id);
|
|
333
623
|
const days = Math.max(0, (now - (brain.meta.lastSettle ?? now)) / (24 * 60 * 60 * 1000));
|
|
334
624
|
if (days >= 1) {
|
|
335
|
-
|
|
625
|
+
// ── 一年一度蜕壳:跨自然年时,把这一年掉出去的人设收进永久卡片 ──
|
|
626
|
+
const thisYear = new Date(now).getFullYear();
|
|
627
|
+
const prevYear = brain.persona.shellYear ?? thisYear;
|
|
628
|
+
if (thisYear > prevYear) {
|
|
629
|
+
const s = shellSummary(brain.persona.units, brain.memory.formerSelves, {
|
|
630
|
+
year: prevYear, at: now, yearMoves: brain.persona.yearMoves ?? {},
|
|
631
|
+
});
|
|
632
|
+
if (s.changed > 0) {
|
|
633
|
+
addCard(brain.memory, {
|
|
634
|
+
id: `shell_${prevYear}`,
|
|
635
|
+
kind: 'card',
|
|
636
|
+
title: s.title,
|
|
637
|
+
text: s.text,
|
|
638
|
+
at: now,
|
|
639
|
+
lastRecall: now,
|
|
640
|
+
expiresAt: now + 1000 * 365 * 24 * 60 * 60 * 1000,
|
|
641
|
+
consecutiveDays: 1,
|
|
642
|
+
longTerm: true,
|
|
643
|
+
// 永久:这是"我以前是谁"的唯一凭证,不许老化
|
|
644
|
+
important: true,
|
|
645
|
+
source: 'shell',
|
|
646
|
+
});
|
|
647
|
+
appendAudit(id, { kind: 'shell', year: prevYear, changed: s.changed, text: s.text.slice(0, 60) });
|
|
648
|
+
}
|
|
649
|
+
brain.persona.shellYear = thisYear;
|
|
650
|
+
brain.persona.shellAt = now;
|
|
651
|
+
brain.persona.yearMoves = {};
|
|
652
|
+
// 蜕了壳,「我是谁」要跟着重写
|
|
653
|
+
refreshNarrative(brain, 'shell');
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// 人设:只有长期没人碰的命题才褪色
|
|
657
|
+
brain.persona.units = decay(brain.persona.units, Math.floor(days), now, { quietDays: compressDays });
|
|
336
658
|
const sh = shed(brain.persona.units, { at: now });
|
|
337
659
|
if (sh.formerSelves.length) {
|
|
338
660
|
brain.persona.units = sh.units;
|
|
339
661
|
brain.memory.formerSelves.push(...sh.formerSelves);
|
|
662
|
+
for (const f of sh.formerSelves) {
|
|
663
|
+
appendAudit(id, { kind: 'shed', id: f.id, weight: Number(f.weight.toFixed(3)), memoir: f.memoir });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
if (ttlPolicy === 'summarize' || ttlPolicy === 'archive') {
|
|
668
|
+
const card = makeCard(brain.memory.episodes.slice(-12));
|
|
669
|
+
if (card) addCard(brain.memory, card);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const archived = [];
|
|
673
|
+
if (ttlPolicy !== 'off') {
|
|
674
|
+
settle(brain.memory, now, {
|
|
675
|
+
compressDays,
|
|
676
|
+
forgetDays,
|
|
677
|
+
onArchive: (item, reason) => archived.push({ ...item, archiveReason: reason }),
|
|
678
|
+
});
|
|
340
679
|
}
|
|
341
|
-
|
|
680
|
+
|
|
681
|
+
// 原文一律留档:压扁的和遗忘的都写进 archive.jsonl
|
|
682
|
+
if (archived.length) {
|
|
683
|
+
try {
|
|
684
|
+
fs.appendFileSync(
|
|
685
|
+
path.join(brainDir(id), 'archive.jsonl'),
|
|
686
|
+
`${archived.map((x) => JSON.stringify(x)).join('\n')}\n`,
|
|
687
|
+
'utf8',
|
|
688
|
+
);
|
|
689
|
+
} catch (e) {
|
|
690
|
+
logOnce(`[brain] 归档写入失败(已忽略):${e?.message ?? e}`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (brain.memory.forgotten.length > 500) {
|
|
694
|
+
brain.memory.forgotten = brain.memory.forgotten.slice(-500);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// 提炼纲和伞:细节会烂,但"我认识他""这事发生过""我上过学"不能跟着烂
|
|
698
|
+
try {
|
|
699
|
+
distillGists(brain.memory, now);
|
|
700
|
+
distillUmbrellas(brain.memory, now);
|
|
701
|
+
} catch (e) {
|
|
702
|
+
logOnce(`[brain] 纲/伞提炼失败(已忽略):${e?.message ?? e}`);
|
|
703
|
+
}
|
|
704
|
+
|
|
342
705
|
brain.meta.lastSettle = now;
|
|
343
706
|
refreshBrief(brain);
|
|
344
707
|
saveBrain(brain);
|
|
708
|
+
if (archived.length) appendAudit(id, { kind: 'aging', archived: archived.length });
|
|
345
709
|
}
|
|
346
710
|
return brain;
|
|
347
711
|
}
|
|
348
712
|
|
|
713
|
+
/* ── 快照 / 回滚 ─────────────────────────────────────────────── */
|
|
714
|
+
|
|
715
|
+
/** 给现在的她存个档,坏了能退回来。 */
|
|
716
|
+
export function snapshotBrain(id = DEFAULT_ID, name = '') {
|
|
717
|
+
const brain = ensureBrain(id);
|
|
718
|
+
const dir = path.join(brainDir(id), 'snapshots');
|
|
719
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
720
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
|
721
|
+
const file = path.join(dir, `${name || stamp}.json`);
|
|
722
|
+
fs.writeFileSync(file, JSON.stringify(brain, null, 2), 'utf8');
|
|
723
|
+
appendAudit(id, { kind: 'snapshot', name: path.basename(file, '.json') });
|
|
724
|
+
return { ok: true, name: path.basename(file, '.json'), file };
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** 退回到某个快照。权重逐条还原。 */
|
|
728
|
+
export function restoreBrain(id = DEFAULT_ID, name = '') {
|
|
729
|
+
if (!name) return { ok: false, reason: '要说退回到哪个快照' };
|
|
730
|
+
const dir = path.join(brainDir(id), 'snapshots');
|
|
731
|
+
const file = name.endsWith('.json') ? path.join(dir, name) : path.join(dir, `${name}.json`);
|
|
732
|
+
if (!fs.existsSync(file)) {
|
|
733
|
+
const list = listSnapshots(id).map((s) => s.name);
|
|
734
|
+
return { ok: false, reason: `没有这个快照:${name}`, available: list };
|
|
735
|
+
}
|
|
736
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
|
737
|
+
data.id = id;
|
|
738
|
+
saveBrain(data);
|
|
739
|
+
cache.set(id, data);
|
|
740
|
+
appendAudit(id, { kind: 'restore', name });
|
|
741
|
+
return { ok: true, restored: name, check: identityCheck(id) };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
export function listSnapshots(id = DEFAULT_ID) {
|
|
745
|
+
const dir = path.join(brainDir(id), 'snapshots');
|
|
746
|
+
if (!fs.existsSync(dir)) return [];
|
|
747
|
+
return fs.readdirSync(dir)
|
|
748
|
+
.filter((f) => f.endsWith('.json'))
|
|
749
|
+
.map((f) => ({
|
|
750
|
+
name: f.replace(/\.json$/, ''),
|
|
751
|
+
size: fs.statSync(path.join(dir, f)).size,
|
|
752
|
+
at: fs.statSync(path.join(dir, f)).mtimeMs,
|
|
753
|
+
}))
|
|
754
|
+
.sort((a, b) => b.at - a.at);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/* ── 导入历史 ───────────────────────────────────────────────── */
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* 把宿主已有的历史经历灌进来。
|
|
761
|
+
*
|
|
762
|
+
* 宿主那边往往已经有日记/经验库,不导进来就是"两套记忆各记一套",
|
|
763
|
+
* 用户问「你记得吗」会出现两个答案。
|
|
764
|
+
*
|
|
765
|
+
* @param {Array} list [{ who, text|what, at, feel, mood, emotion }]
|
|
766
|
+
*/
|
|
767
|
+
export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' } = {}) {
|
|
768
|
+
const brain = ensureBrain(id);
|
|
769
|
+
let imported = 0;
|
|
770
|
+
let skipped = 0;
|
|
771
|
+
const touched = new Map(); // who → 次数
|
|
772
|
+
|
|
773
|
+
for (const it of Array.isArray(list) ? list : []) {
|
|
774
|
+
const what = String(it?.text ?? it?.what ?? '').trim();
|
|
775
|
+
if (!what) { skipped += 1; continue; }
|
|
776
|
+
const at = Number(it?.at) || nowMs();
|
|
777
|
+
// ⚠️ 第三个参数必须是「现在」,不是 at。
|
|
778
|
+
// 它同时决定 lastRecall(多久没被提起);传历史时间会让刚搬进来的记忆
|
|
779
|
+
// 一出生就过期,第一次结算就被清空。
|
|
780
|
+
addEpisode(brain.memory, {
|
|
781
|
+
at,
|
|
782
|
+
who: it.who ?? '',
|
|
783
|
+
what: what.slice(0, 140),
|
|
784
|
+
feel: it.feel ?? '',
|
|
785
|
+
mood: it.mood ?? '',
|
|
786
|
+
emotion: Number(it.emotion) || 0,
|
|
787
|
+
outcome: it.outcome ?? null,
|
|
788
|
+
context: it.context ?? null,
|
|
789
|
+
strategy: it.strategy ?? null,
|
|
790
|
+
evidence: it.via ?? source,
|
|
791
|
+
source, // live | import | diary
|
|
792
|
+
// 搬进来的是「已经沉淀过的」——它在宿主那边活过了,不该再按新经历老化
|
|
793
|
+
...(source === 'import' ? { longTerm: Boolean(it.longTerm ?? false) } : {}),
|
|
794
|
+
}, nowMs());
|
|
795
|
+
imported += 1;
|
|
796
|
+
const who = String(it.who ?? '').trim();
|
|
797
|
+
if (who) touched.set(who, (touched.get(who) ?? 0) + 1);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// 搬进来的也要"认识这个人"——否则检索里永远"还不熟"
|
|
801
|
+
for (const [who, n] of touched) {
|
|
802
|
+
const im = brain.memory.impressions[who] ?? { traits: [], count: 0, lastAt: 0 };
|
|
803
|
+
im.count += n;
|
|
804
|
+
im.lastAt = Math.max(Number(im.lastAt) || 0, nowMs());
|
|
805
|
+
brain.memory.impressions[who] = im;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
saveBrain(brain);
|
|
809
|
+
appendAudit(id, { kind: 'import-episodes', imported, skipped, source, people: touched.size });
|
|
810
|
+
return { ok: true, imported, skipped, people: touched.size, total: brain.memory.episodes.length };
|
|
811
|
+
}
|
|
812
|
+
|
|
349
813
|
/** 记一次"想起"(续命)。 */
|
|
350
814
|
export function touch(id, key, { pool = 'facts' } = {}) {
|
|
351
815
|
const brain = ensureBrain(id);
|
|
@@ -405,11 +869,20 @@ export function feel(id = DEFAULT_ID, event = {}, { blend = 0.65 } = {}) {
|
|
|
405
869
|
// 情绪有余温:新感受占 65%,上一次剩 35%。
|
|
406
870
|
// 否则每件事都把心情冲成新的,人会像开关而不是像有情绪惯性的活物。
|
|
407
871
|
const k = Math.max(0, Math.min(1, Number(blend)));
|
|
872
|
+
|
|
873
|
+
// 双源仲裁:宿主说了算时,只算不写——免得两套情绪系统互相覆盖
|
|
874
|
+
if (moodPolicy === 'host') {
|
|
875
|
+
brain.meta.lastFeel = { at: Date.now(), pad: r.pad, label: r.label, stage: r.stage, text: r.text, applied: false };
|
|
876
|
+
saveBrain(brain);
|
|
877
|
+
return { ...r, applied: false, reason: 'moodPolicy=host,情绪以宿主为准,这里只算不写' };
|
|
878
|
+
}
|
|
879
|
+
|
|
408
880
|
const prev = brain.affect ?? {};
|
|
881
|
+
const effBlend = moodPolicy === 'blend' ? Math.min(k, 0.5) : k;
|
|
409
882
|
const mix = (next, before) => {
|
|
410
883
|
const old = Number(before);
|
|
411
884
|
const base = Number.isFinite(old) ? old : 0;
|
|
412
|
-
return Number((next *
|
|
885
|
+
return Number((next * effBlend + base * (1 - effBlend)).toFixed(4));
|
|
413
886
|
};
|
|
414
887
|
|
|
415
888
|
brain.affect = {
|
|
@@ -419,11 +892,12 @@ export function feel(id = DEFAULT_ID, event = {}, { blend = 0.65 } = {}) {
|
|
|
419
892
|
// 名字按**这次**的感受叫:旧的余温不该拖住命名
|
|
420
893
|
mood: r.label.kind === 'word' ? r.label.word : (r.label.kind === 'variant' ? `${r.label.word}(变体)` : '说不上来'),
|
|
421
894
|
// 余温多少,方便调试时看"她还没缓过来"
|
|
422
|
-
carryover: Number((1 -
|
|
895
|
+
carryover: Number((1 - effBlend).toFixed(2)),
|
|
896
|
+
moodSource: moodPolicy,
|
|
423
897
|
};
|
|
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 };
|
|
898
|
+
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
899
|
saveBrain(brain);
|
|
426
|
-
return { ...r, blended: [brain.affect.p, brain.affect.a, brain.affect.d] };
|
|
900
|
+
return { ...r, applied: true, blended: [brain.affect.p, brain.affect.a, brain.affect.d] };
|
|
427
901
|
}
|
|
428
902
|
|
|
429
903
|
/**
|
|
@@ -442,8 +916,7 @@ export function learnEmotion(id = DEFAULT_ID, word, { pad, sources = [], cause =
|
|
|
442
916
|
}
|
|
443
917
|
|
|
444
918
|
/** 阶段三:从 ≥3 个实例里自己归纳出这个词的含义。 */
|
|
445
|
-
export function induceEmotion(id = DEFAULT_ID, word) {
|
|
446
|
-
const brain = ensureBrain(id);
|
|
919
|
+
export function induceEmotion(id = DEFAULT_ID, word) { const brain = ensureBrain(id);
|
|
447
920
|
const r = emotion.induce(brain.vocab, word);
|
|
448
921
|
if (r.induced) {
|
|
449
922
|
brain.vocab = r.vocab;
|
|
@@ -462,6 +935,67 @@ export function vocabOf(id = DEFAULT_ID) {
|
|
|
462
935
|
};
|
|
463
936
|
}
|
|
464
937
|
|
|
938
|
+
/**
|
|
939
|
+
* 给老鱼预装一份情绪词表。
|
|
940
|
+
*
|
|
941
|
+
* **新鱼用不到**——她该从"说不清"开始学。
|
|
942
|
+
* 但一条活了两年的鱼搬进来,不该从"哼哼"开始。
|
|
943
|
+
*/
|
|
944
|
+
export const BASIC_VOCAB = ['委屈', '生气', '高兴', '失落', '烦', '慌', '得意', '无聊', '累', '暖'];
|
|
945
|
+
|
|
946
|
+
export function seedVocab(id = DEFAULT_ID, words = BASIC_VOCAB) {
|
|
947
|
+
const brain = ensureBrain(id);
|
|
948
|
+
let added = 0;
|
|
949
|
+
for (const w of words) {
|
|
950
|
+
if (brain.vocab[w]) continue;
|
|
951
|
+
const p = emotion.PROTOTYPES[w];
|
|
952
|
+
if (!p) continue;
|
|
953
|
+
brain.vocab[w] = {
|
|
954
|
+
pad: [...p.pad],
|
|
955
|
+
cause: p.cause,
|
|
956
|
+
body: p.body,
|
|
957
|
+
action: p.action,
|
|
958
|
+
instances: [],
|
|
959
|
+
sources: ['seed'],
|
|
960
|
+
learnedAt: Date.now(),
|
|
961
|
+
};
|
|
962
|
+
added += 1;
|
|
963
|
+
}
|
|
964
|
+
saveBrain(brain);
|
|
965
|
+
appendAudit(id, { kind: 'seed-vocab', added, total: Object.keys(brain.vocab).length });
|
|
966
|
+
return { ok: true, added, total: Object.keys(brain.vocab).length, stage: emotion.stageOf(brain.vocab) };
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* 精确导入词表(来自 exportPack,或别的系统导出的)。
|
|
971
|
+
* @param {Array} list [{ word, pad:[p,a,d], cause, body, action, instances }]
|
|
972
|
+
*/
|
|
973
|
+
export function importVocab(id = DEFAULT_ID, list = []) {
|
|
974
|
+
const brain = ensureBrain(id);
|
|
975
|
+
let imported = 0;
|
|
976
|
+
for (const it of Array.isArray(list) ? list : []) {
|
|
977
|
+
const word = String(it?.word ?? it?.name ?? '').trim();
|
|
978
|
+
if (!word) continue;
|
|
979
|
+
const proto = emotion.PROTOTYPES[word] ?? {};
|
|
980
|
+
const pad = Array.isArray(it.pad)
|
|
981
|
+
? [0, 1, 2].map((i) => Math.max(-1, Math.min(1, Number(it.pad[i]) || 0)))
|
|
982
|
+
: (proto.pad ?? [0, 0, 0]);
|
|
983
|
+
brain.vocab[word] = {
|
|
984
|
+
pad,
|
|
985
|
+
cause: it.cause ?? proto.cause ?? '',
|
|
986
|
+
body: it.body ?? proto.body ?? '',
|
|
987
|
+
action: it.action ?? proto.action ?? '',
|
|
988
|
+
instances: Array.isArray(it.instances) ? it.instances.slice(-20) : [],
|
|
989
|
+
sources: [...new Set([...(it.sources ?? []), 'import'])].slice(-8),
|
|
990
|
+
learnedAt: Number(it.learnedAt) || Date.now(),
|
|
991
|
+
};
|
|
992
|
+
imported += 1;
|
|
993
|
+
}
|
|
994
|
+
saveBrain(brain);
|
|
995
|
+
appendAudit(id, { kind: 'import-vocab', imported, total: Object.keys(brain.vocab).length });
|
|
996
|
+
return { ok: true, imported, total: Object.keys(brain.vocab).length, stage: emotion.stageOf(brain.vocab) };
|
|
997
|
+
}
|
|
998
|
+
|
|
465
999
|
/* ── 记忆卡片:上下文过长时压缩中段 ───────────────────────────── */
|
|
466
1000
|
|
|
467
1001
|
export function needsCard(id = DEFAULT_ID, contextChars = 0) {
|
|
@@ -703,6 +1237,671 @@ export function seenBefore(id = DEFAULT_ID, text = '') {
|
|
|
703
1237
|
return similarSeen(ensureBrain(id).memory, text);
|
|
704
1238
|
}
|
|
705
1239
|
|
|
1240
|
+
/* ── 身份体检:换脑之后还是不是她 ─────────────────────────────── */
|
|
1241
|
+
|
|
1242
|
+
/**
|
|
1243
|
+
* 「我还是我吗」不用哲学,查三样东西在不在:
|
|
1244
|
+
* ① 记忆 跟谁发生过什么
|
|
1245
|
+
* ② 自我叙事 她以为的自己
|
|
1246
|
+
* ③ 关系 认谁、怎么称呼
|
|
1247
|
+
*
|
|
1248
|
+
* 三个都在 → 是她;缺一个 → 像她但不是她;全没有 → 只是同名。
|
|
1249
|
+
*/
|
|
1250
|
+
export function identityCheck(id = DEFAULT_ID) {
|
|
1251
|
+
const b = ensureBrain(id);
|
|
1252
|
+
const episodes = b.memory.episodes.length;
|
|
1253
|
+
const people = Object.keys(b.memory.impressions ?? {}).length;
|
|
1254
|
+
const cards = (b.memory.cards ?? []).length;
|
|
1255
|
+
const narrative = Boolean(b.self?.narrative);
|
|
1256
|
+
const relation = Boolean(b.relation?.type);
|
|
1257
|
+
|
|
1258
|
+
const marks = [episodes + people > 0, narrative, relation];
|
|
1259
|
+
const verdict = marks.every(Boolean)
|
|
1260
|
+
? '是她'
|
|
1261
|
+
: marks.some(Boolean) ? '像她,但不是她' : '同名而已';
|
|
1262
|
+
|
|
1263
|
+
return {
|
|
1264
|
+
id,
|
|
1265
|
+
memory: { episodes, people, cards },
|
|
1266
|
+
narrative,
|
|
1267
|
+
narrativeText: b.self?.narrative ?? '',
|
|
1268
|
+
relation: relation ? { type: b.relation.type, address: b.relation.address ?? '' } : null,
|
|
1269
|
+
verdict,
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/* ── 脑包:把"她"打包带走 ────────────────────────────────────── */
|
|
1274
|
+
|
|
1275
|
+
export const PACK_FORMAT = 'feiyu-brainpack/1';
|
|
1276
|
+
|
|
1277
|
+
/**
|
|
1278
|
+
* 导出"她"——人设 + 记忆 + 关系 + 词表 + 情绪。
|
|
1279
|
+
* **换脑不是换人的前提是这个包带得走。**
|
|
1280
|
+
*/
|
|
1281
|
+
export function exportPack(id = DEFAULT_ID, { includeMemory = true } = {}) {
|
|
1282
|
+
const b = ensureBrain(id);
|
|
1283
|
+
return {
|
|
1284
|
+
format: PACK_FORMAT,
|
|
1285
|
+
exportedAt: nowMs(),
|
|
1286
|
+
id: b.id,
|
|
1287
|
+
born: b.born,
|
|
1288
|
+
roleCard: b.roleCard,
|
|
1289
|
+
persona: b.persona,
|
|
1290
|
+
self: b.self,
|
|
1291
|
+
relation: b.relation,
|
|
1292
|
+
vocab: b.vocab ?? {},
|
|
1293
|
+
affect: b.affect ?? {},
|
|
1294
|
+
body: b.body ? { kind: b.body.kind, ownership: b.body.ownership } : null,
|
|
1295
|
+
patience: b.patience,
|
|
1296
|
+
...(includeMemory ? { memory: b.memory } : {}),
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* 把包装回来。
|
|
1302
|
+
*
|
|
1303
|
+
* 只认 `feiyu-brainpack/1`;别的格式(aurobot / 口袋 / TavernCard)需要先写迁移器转成这个格式。
|
|
1304
|
+
* 宁可拒收,也不假装兼容。
|
|
1305
|
+
*/
|
|
1306
|
+
export function importPack(pack, { id, keepMemory = true } = {}) {
|
|
1307
|
+
if (!pack || pack.format !== PACK_FORMAT) {
|
|
1308
|
+
return { ok: false, reason: `不是 ${PACK_FORMAT} 格式,先用迁移器转一下` };
|
|
1309
|
+
}
|
|
1310
|
+
const units = pack.persona?.units ?? [];
|
|
1311
|
+
if (!units.length) return { ok: false, reason: '包里没有命题,导进来也是空壳' };
|
|
1312
|
+
|
|
1313
|
+
const targetId = id ?? pack.id ?? DEFAULT_ID;
|
|
1314
|
+
const identity = units.find((u) => u.kind === 'identity')?.text ?? `你是${pack.roleCard ?? targetId}`;
|
|
1315
|
+
const cardText = [identity, ...units.filter((u) => u.kind !== 'identity').map((u) => `- ${u.text}`)].join('\n');
|
|
1316
|
+
|
|
1317
|
+
const brain = birth({
|
|
1318
|
+
id: targetId,
|
|
1319
|
+
relation: pack.relation?.type ?? 'parent',
|
|
1320
|
+
address: pack.relation?.address ?? '',
|
|
1321
|
+
cardText,
|
|
1322
|
+
cardName: pack.roleCard ?? targetId,
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
// 用包里的原样覆盖:保留命题 id、权重、来源——这些是"她"的部分
|
|
1326
|
+
brain.persona = { ...pack.persona, brief: '' };
|
|
1327
|
+
brain.self = { ...brain.self, ...(pack.self ?? {}) };
|
|
1328
|
+
brain.self.style = brain.self.style ?? styleVector(brain.persona.traits);
|
|
1329
|
+
brain.self.styleName = dominantStyle(brain.self.style);
|
|
1330
|
+
if (pack.relation) brain.relation = pack.relation;
|
|
1331
|
+
brain.vocab = pack.vocab ?? {};
|
|
1332
|
+
brain.affect = pack.affect ?? brain.affect;
|
|
1333
|
+
if (Number.isFinite(pack.patience)) brain.patience = pack.patience;
|
|
1334
|
+
if (keepMemory && pack.memory) brain.memory = { ...emptyMemory(), ...pack.memory };
|
|
1335
|
+
if (pack.body?.kind) {
|
|
1336
|
+
try { brain.body = createBody({ kind: pack.body.kind, ownership: pack.body.ownership }); } catch { /* 身体坏了不影响她是谁 */ }
|
|
1337
|
+
}
|
|
1338
|
+
if (Number.isFinite(pack.born)) brain.born = pack.born;
|
|
1339
|
+
|
|
1340
|
+
refreshBrief(brain);
|
|
1341
|
+
saveBrain(brain);
|
|
1342
|
+
cache.set(targetId, brain);
|
|
1343
|
+
appendAudit(targetId, { kind: 'import-pack', from: pack.id ?? '?', units: units.length, memory: keepMemory });
|
|
1344
|
+
|
|
1345
|
+
return { ok: true, id: targetId, units: units.length, check: identityCheck(targetId) };
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/* ── 记忆搬迁:老鱼把过去搬进来 ─────────────────────────────── */
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* 把宿主已有的记忆搬进脑子。
|
|
1352
|
+
*
|
|
1353
|
+
* 这是**有损转换**,不是复制:宿主日记是流水账,脑子里存的是"她记得的事"。
|
|
1354
|
+
* 每条都标 source:'import',将来能分清哪些是亲历、哪些是搬来的。
|
|
1355
|
+
*
|
|
1356
|
+
* migrateMemory('old', { text, format: 'jsonl' }) // 真搬
|
|
1357
|
+
* migrateMemory('old', { text, format: 'days', dryRun: true }) // 只看会搬多少
|
|
1358
|
+
*/
|
|
1359
|
+
export function migrateMemory(id = DEFAULT_ID, { text = '', format = 'jsonl', dryRun = false } = {}) {
|
|
1360
|
+
const brain = ensureBrain(id);
|
|
1361
|
+
const parsed = parseAny(String(text ?? ''), format);
|
|
1362
|
+
const d = dedupe(parsed.episodes, { existing: brain.memory.episodes });
|
|
1363
|
+
|
|
1364
|
+
const ats = d.episodes.map((e) => e.at).filter((t) => t > 0).sort((a, b) => a - b);
|
|
1365
|
+
const report = {
|
|
1366
|
+
format,
|
|
1367
|
+
parsed: parsed.episodes.length,
|
|
1368
|
+
duplicated: d.duplicated,
|
|
1369
|
+
willImport: d.episodes.length,
|
|
1370
|
+
parseErrors: parsed.errors.slice(0, 20),
|
|
1371
|
+
parseErrorCount: parsed.errors.length,
|
|
1372
|
+
span: ats.length ? { from: new Date(ats[0]).toISOString().slice(0, 10), to: new Date(ats[ats.length - 1]).toISOString().slice(0, 10) } : null,
|
|
1373
|
+
};
|
|
1374
|
+
|
|
1375
|
+
if (dryRun) return { ok: true, dryRun: true, report };
|
|
1376
|
+
|
|
1377
|
+
const r = importEpisodes(id, d.episodes, { source: 'import' });
|
|
1378
|
+
return { ok: true, dryRun: false, report, imported: r.imported, total: r.total };
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/** 读归档(过期但没丢的那些) */
|
|
1382
|
+
export function readArchive(id = DEFAULT_ID, limit = 20) {
|
|
1383
|
+
const file = path.join(brainDir(id), 'archive.jsonl');
|
|
1384
|
+
if (!fs.existsSync(file)) return [];
|
|
1385
|
+
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
|
|
1386
|
+
return lines.slice(-limit).map((l) => {
|
|
1387
|
+
try { return JSON.parse(l); } catch { return { raw: l }; }
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
/* ── 全量整合:把宿主所有记忆并成一份 ───────────────────────── */
|
|
1392
|
+
|
|
1393
|
+
/** 脑里最多存多少条经历,超了自动压卡片 + 归档(防止 brain.json 无限膨胀) */
|
|
1394
|
+
export const MAX_EPISODES = 5000;
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* 容量保护:最老的一批压成卡片,原文进 archive.jsonl。
|
|
1398
|
+
*
|
|
1399
|
+
* 不是"一次吃掉两百条"——按 20 条一张卡片分批压,别让一次溢出把半年吃成 160 字。
|
|
1400
|
+
*/
|
|
1401
|
+
function enforceCapacity(brain) {
|
|
1402
|
+
const eps = brain.memory.episodes;
|
|
1403
|
+
if (eps.length <= maxEpisodes) return { compacted: 0, cards: 0 };
|
|
1404
|
+
const overflow = eps.length - maxEpisodes;
|
|
1405
|
+
const take = Math.min(overflow, eps.length);
|
|
1406
|
+
const oldest = eps.slice(0, take);
|
|
1407
|
+
|
|
1408
|
+
let cards = 0;
|
|
1409
|
+
for (let i = 0; i < oldest.length; i += 20) {
|
|
1410
|
+
const chunk = oldest.slice(i, i + 20);
|
|
1411
|
+
const card = makeCard(chunk);
|
|
1412
|
+
if (card) { addCard(brain.memory, card); cards += 1; }
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
try {
|
|
1416
|
+
fs.appendFileSync(
|
|
1417
|
+
path.join(brainDir(brain.id), 'archive.jsonl'),
|
|
1418
|
+
`${oldest.map((x) => JSON.stringify({ ...x, archiveReason: 'capacity' })).join('\n')}\n`,
|
|
1419
|
+
'utf8',
|
|
1420
|
+
);
|
|
1421
|
+
} catch (e) {
|
|
1422
|
+
logOnce(`[brain] 容量归档失败(已忽略):${e?.message ?? e}`);
|
|
1423
|
+
}
|
|
1424
|
+
brain.memory.episodes = eps.slice(take);
|
|
1425
|
+
appendAudit(brain.id, { kind: 'capacity', compacted: take, cards });
|
|
1426
|
+
return { compacted: take, cards };
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/**
|
|
1430
|
+
* 把多份记忆一次性并进来。**这是"只剩一份记忆"的唯一入口。**
|
|
1431
|
+
*
|
|
1432
|
+
* @param {Array} sources [{ path, text, format }]
|
|
1433
|
+
* @param {object} [opts]
|
|
1434
|
+
* @param {boolean} [opts.dryRun] 只算不写
|
|
1435
|
+
* @param {boolean} [opts.deleteSource] 搬完把原文件改名成 .migrated(不是删除,留后悔药)
|
|
1436
|
+
*/
|
|
1437
|
+
export function migrateAll(id = DEFAULT_ID, sources = [], { dryRun = false, deleteSource = false } = {}) {
|
|
1438
|
+
const brain = ensureBrain(id);
|
|
1439
|
+
const all = [];
|
|
1440
|
+
const errors = [];
|
|
1441
|
+
const files = [];
|
|
1442
|
+
|
|
1443
|
+
for (const s of Array.isArray(sources) ? sources : []) {
|
|
1444
|
+
if (!s?.text) continue;
|
|
1445
|
+
files.push(s.path ?? '(inline)');
|
|
1446
|
+
const r = parseAny(String(s.text), s.format ?? 'jsonl');
|
|
1447
|
+
all.push(...r.episodes);
|
|
1448
|
+
for (const e of r.errors.slice(0, 3)) errors.push({ path: s.path ?? '', ...e });
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
const d = dedupe(all, { existing: brain.memory.episodes });
|
|
1452
|
+
const ats = d.episodes.map((e) => e.at).filter((t) => t > 0).sort((a, b) => a - b);
|
|
1453
|
+
const report = {
|
|
1454
|
+
files: files.length,
|
|
1455
|
+
parsed: all.length,
|
|
1456
|
+
duplicated: d.duplicated,
|
|
1457
|
+
willImport: d.episodes.length,
|
|
1458
|
+
errors: errors.slice(0, 20),
|
|
1459
|
+
errorCount: errors.length,
|
|
1460
|
+
span: ats.length ? { from: new Date(ats[0]).toISOString().slice(0, 10), to: new Date(ats[ats.length - 1]).toISOString().slice(0, 10) } : null,
|
|
1461
|
+
};
|
|
1462
|
+
|
|
1463
|
+
if (dryRun) return { ok: true, dryRun: true, report };
|
|
1464
|
+
|
|
1465
|
+
const r = importEpisodes(id, d.episodes, { source: 'import' });
|
|
1466
|
+
const cap = enforceCapacity(brain);
|
|
1467
|
+
|
|
1468
|
+
// 原始文件不 rm,改名 —— 用户要删自己删,别让我们替他做不可逆的事
|
|
1469
|
+
const renamed = [];
|
|
1470
|
+
if (deleteSource) {
|
|
1471
|
+
for (const p of files) {
|
|
1472
|
+
if (!p || p === '(inline)' || !fs.existsSync(p)) continue;
|
|
1473
|
+
try {
|
|
1474
|
+
fs.renameSync(p, `${p}.migrated`);
|
|
1475
|
+
renamed.push(`${p}.migrated`);
|
|
1476
|
+
} catch (e) {
|
|
1477
|
+
errors.push({ path: p, reason: `改名失败:${e?.message ?? e}` });
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
return {
|
|
1483
|
+
ok: true,
|
|
1484
|
+
dryRun: false,
|
|
1485
|
+
report,
|
|
1486
|
+
imported: r.imported,
|
|
1487
|
+
total: r.total,
|
|
1488
|
+
compacted: cap.compacted,
|
|
1489
|
+
renamed,
|
|
1490
|
+
check: identityCheck(id),
|
|
1491
|
+
};
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
/** 迁完之后的自检:搬进来的东西到底能不能被想起来 */
|
|
1495
|
+
export function verifyMemory(id = DEFAULT_ID, { samples = 5 } = {}) {
|
|
1496
|
+
const brain = ensureBrain(id);
|
|
1497
|
+
const eps = brain.memory.episodes;
|
|
1498
|
+
const imported = eps.filter((e) => e.source === 'import').length;
|
|
1499
|
+
const live = eps.filter((e) => e.source === 'live').length;
|
|
1500
|
+
|
|
1501
|
+
const picked = eps.filter((e) => e.what).slice(-samples);
|
|
1502
|
+
const checks = picked.map((e) => {
|
|
1503
|
+
const kw = String(e.what).slice(0, 6);
|
|
1504
|
+
const line = wakeLine(id, { who: e.who ?? '', text: kw });
|
|
1505
|
+
return { keyword: kw, found: line.includes(kw.slice(0, 3)) };
|
|
1506
|
+
});
|
|
1507
|
+
|
|
1508
|
+
return {
|
|
1509
|
+
id,
|
|
1510
|
+
episodes: eps.length,
|
|
1511
|
+
imported,
|
|
1512
|
+
live,
|
|
1513
|
+
cards: (brain.memory.cards ?? []).length,
|
|
1514
|
+
people: Object.keys(brain.memory.impressions ?? {}).length,
|
|
1515
|
+
check: identityCheck(id),
|
|
1516
|
+
recall: checks,
|
|
1517
|
+
recallRate: checks.length ? checks.filter((c) => c.found).length / checks.length : 1,
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/* ── 日记:她自己的心房 ─────────────────────────────────────── */
|
|
1522
|
+
|
|
1523
|
+
/** 日记目录:<dataDir>/days/,跟宿主自己的日记分开,别互相覆盖 */
|
|
1524
|
+
export function diaryDir(id = DEFAULT_ID) {
|
|
1525
|
+
return path.join(brainDir(id), 'days');
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
export function diaryPath(id = DEFAULT_ID, date = '') {
|
|
1529
|
+
const d = date || dayKey();
|
|
1530
|
+
return path.join(diaryDir(id), `${d}.md`);
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* 今天的素材 + 第一人称骨架。
|
|
1535
|
+
* 脑子不出文笔,只给料——宿主拿 draft 让模型用她的口吻写成日记。
|
|
1536
|
+
*/
|
|
1537
|
+
export function diaryDigest(id = DEFAULT_ID, date = '') {
|
|
1538
|
+
const brain = ensureBrain(id);
|
|
1539
|
+
return dayDigest(brain, date || dayKey());
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* 她把日记存回来。
|
|
1544
|
+
*
|
|
1545
|
+
* 存完之后这段文字会被当作"她写过的"记进记忆——将来问"你写过什么"能想起来。
|
|
1546
|
+
* **日记要带心情**:正文里没写就补一行(`withMood:false` 可关掉)。
|
|
1547
|
+
*/
|
|
1548
|
+
export function writeDiary(id = DEFAULT_ID, { date = '', text = '', withMood = true } = {}) {
|
|
1549
|
+
const brain = ensureBrain(id);
|
|
1550
|
+
const body = String(text ?? '').trim();
|
|
1551
|
+
if (!body) return { ok: false, reason: '日记是空的' };
|
|
1552
|
+
|
|
1553
|
+
const d = date || dayKey();
|
|
1554
|
+
const mood = brain.affect?.mood ?? '';
|
|
1555
|
+
const hasMood = mood && mood !== '平静' && mood !== '说不上来';
|
|
1556
|
+
|
|
1557
|
+
// 她自己写了心情就不动;没写就补一行,别让日记丢了心情
|
|
1558
|
+
let final = body;
|
|
1559
|
+
let moodAdded = false;
|
|
1560
|
+
if (withMood && hasMood && !/心情/.test(final)) {
|
|
1561
|
+
final = `${final}\n\n心情:${mood}`;
|
|
1562
|
+
moodAdded = true;
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
const dir = diaryDir(id);
|
|
1566
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1567
|
+
const file = diaryPath(id, d);
|
|
1568
|
+
fs.writeFileSync(file, final.endsWith('\n') ? final : `${final}\n`, 'utf8');
|
|
1569
|
+
|
|
1570
|
+
// 记进记忆:以后能想起来"我写过什么"
|
|
1571
|
+
addEpisode(brain.memory, {
|
|
1572
|
+
who: '',
|
|
1573
|
+
what: `我写了日记:${final.replace(/\s+/g, ' ').slice(0, 60)}`,
|
|
1574
|
+
feel: hasMood ? mood : '',
|
|
1575
|
+
mood: hasMood ? mood : '',
|
|
1576
|
+
source: 'diary',
|
|
1577
|
+
evidence: file,
|
|
1578
|
+
}, nowMs());
|
|
1579
|
+
|
|
1580
|
+
if (!Array.isArray(brain.meta.diary)) brain.meta.diary = [];
|
|
1581
|
+
if (!brain.meta.diary.includes(d)) brain.meta.diary.push(d);
|
|
1582
|
+
brain.meta.diary = brain.meta.diary.slice(-400);
|
|
1583
|
+
|
|
1584
|
+
// 心情单独存一份,方便按月看她的情绪曲线
|
|
1585
|
+
if (!brain.meta.diaryMood) brain.meta.diaryMood = {};
|
|
1586
|
+
brain.meta.diaryMood[d] = hasMood ? mood : '';
|
|
1587
|
+
|
|
1588
|
+
saveBrain(brain);
|
|
1589
|
+
appendAudit(id, { kind: 'diary', date: d, chars: final.length, mood: brain.meta.diaryMood[d], moodAdded });
|
|
1590
|
+
return { ok: true, date: d, file, chars: final.length, mood: brain.meta.diaryMood[d] || null, moodAdded };
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
export function readDiary(id = DEFAULT_ID, date = '') {
|
|
1594
|
+
const file = diaryPath(id, date);
|
|
1595
|
+
if (!fs.existsSync(file)) return null;
|
|
1596
|
+
const brain = ensureBrain(id);
|
|
1597
|
+
const d = path.basename(file, '.md');
|
|
1598
|
+
return {
|
|
1599
|
+
date: d,
|
|
1600
|
+
text: fs.readFileSync(file, 'utf8'),
|
|
1601
|
+
mood: brain.meta.diaryMood?.[d] ?? null,
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
export function listDiary(id = DEFAULT_ID) {
|
|
1606
|
+
const dir = diaryDir(id);
|
|
1607
|
+
if (!fs.existsSync(dir)) return [];
|
|
1608
|
+
return fs.readdirSync(dir)
|
|
1609
|
+
.filter((f) => f.endsWith('.md'))
|
|
1610
|
+
.map((f) => {
|
|
1611
|
+
const full = path.join(dir, f);
|
|
1612
|
+
return { date: f.replace(/\.md$/, ''), size: fs.statSync(full).size, at: fs.statSync(full).mtimeMs };
|
|
1613
|
+
})
|
|
1614
|
+
.sort((a, b) => (a.date < b.date ? 1 : -1));
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* 把**她以前写过的日记**搬进来。
|
|
1619
|
+
*
|
|
1620
|
+
* 不是把流水账重新生成一遍——那是造假。原样拷贝,一个字不改。
|
|
1621
|
+
* @param {Array} list [{ date:'2025-11-20', text:'...' }]
|
|
1622
|
+
*/
|
|
1623
|
+
export function importDiary(id = DEFAULT_ID, list = [], { overwrite = false } = {}) {
|
|
1624
|
+
const brain = ensureBrain(id);
|
|
1625
|
+
const dir = diaryDir(id);
|
|
1626
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1627
|
+
let imported = 0;
|
|
1628
|
+
let skipped = 0;
|
|
1629
|
+
for (const it of Array.isArray(list) ? list : []) {
|
|
1630
|
+
const date = String(it?.date ?? '').trim();
|
|
1631
|
+
const text = String(it?.text ?? '').trim();
|
|
1632
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !text) { skipped += 1; continue; }
|
|
1633
|
+
const file = diaryPath(id, date);
|
|
1634
|
+
if (fs.existsSync(file) && !overwrite) { skipped += 1; continue; }
|
|
1635
|
+
fs.writeFileSync(file, text.endsWith('\n') ? text : `${text}\n`, 'utf8');
|
|
1636
|
+
if (!Array.isArray(brain.meta.diary)) brain.meta.diary = [];
|
|
1637
|
+
if (!brain.meta.diary.includes(date)) brain.meta.diary.push(date);
|
|
1638
|
+
imported += 1;
|
|
1639
|
+
}
|
|
1640
|
+
brain.meta.diary = (brain.meta.diary ?? []).slice(-400);
|
|
1641
|
+
saveBrain(brain);
|
|
1642
|
+
appendAudit(id, { kind: 'import-diary', imported, skipped });
|
|
1643
|
+
return { ok: true, imported, skipped, days: listDiary(id).length };
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/** 日记也能被检索:问"你写过什么"时用它 */
|
|
1647
|
+
export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
|
|
1648
|
+
const list = listDiary(id);
|
|
1649
|
+
if (!list.length) return [];
|
|
1650
|
+
const q = String(word ?? '').trim();
|
|
1651
|
+
const hits = [];
|
|
1652
|
+
for (const d of list) {
|
|
1653
|
+
const r = readDiary(id, d.date);
|
|
1654
|
+
if (!r) continue;
|
|
1655
|
+
if (!q || r.text.includes(q)) hits.push({ date: r.date, excerpt: r.text.replace(/\s+/g, ' ').slice(0, 80) });
|
|
1656
|
+
if (hits.length >= limit) break;
|
|
1657
|
+
}
|
|
1658
|
+
return hits;
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
/* ── 特质:开放维度(她自己长出来的)────────────────────────── */
|
|
1662
|
+
|
|
1663
|
+
/**
|
|
1664
|
+
* 模型提名一个新维度(B 路径)。
|
|
1665
|
+
*
|
|
1666
|
+
* 脑不做"理解"——理解是模型的事。模型读完对话觉得"她今天很上头",
|
|
1667
|
+
* 就调这个把「上头」登记成她的一个维度,脑负责存、算、衰减、蜕皮。
|
|
1668
|
+
*/
|
|
1669
|
+
export function defineTrait(id = DEFAULT_ID, name = '', weight = 0.6, { source = 'model' } = {}) {
|
|
1670
|
+
const brain = ensureBrain(id);
|
|
1671
|
+
const n = String(name ?? '').trim();
|
|
1672
|
+
if (n.length < 2 || n.length > 8) return { ok: false, reason: '维度名 2~8 个字' };
|
|
1673
|
+
const w = Number.isFinite(Number(weight)) ? Math.max(0, Math.min(1, Number(weight))) : 0.6;
|
|
1674
|
+
|
|
1675
|
+
brain.persona.traits = { ...(brain.persona.traits ?? {}), [n]: w };
|
|
1676
|
+
brain.persona.openTraits = { ...(brain.persona.openTraits ?? {}), [n]: w };
|
|
1677
|
+
brain.self.style = styleVector(brain.persona.traits);
|
|
1678
|
+
brain.self.styleName = dominantStyle(brain.self.style);
|
|
1679
|
+
saveBrain(brain);
|
|
1680
|
+
appendAudit(id, { kind: 'define-trait', name: n, weight: w, source });
|
|
1681
|
+
return { ok: true, name: n, weight: w, total: Object.keys(brain.persona.traits).length };
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
/**
|
|
1685
|
+
* 看她现在有哪些维度:哪些是先验的,哪些是她自己长出来的。
|
|
1686
|
+
*/
|
|
1687
|
+
export function traitReport(id = DEFAULT_ID) {
|
|
1688
|
+
const brain = ensureBrain(id);
|
|
1689
|
+
const known = new Set(Object.keys(brain.persona.knownTraits ?? TRAIT_LEXICON));
|
|
1690
|
+
const rows = Object.entries(brain.persona.traits ?? {})
|
|
1691
|
+
.map(([name, weight]) => ({
|
|
1692
|
+
name,
|
|
1693
|
+
weight: Number(Number(weight).toFixed(2)),
|
|
1694
|
+
kind: known.has(name) ? 'known' : 'open',
|
|
1695
|
+
}))
|
|
1696
|
+
.sort((a, b) => b.weight - a.weight);
|
|
1697
|
+
return {
|
|
1698
|
+
total: rows.length,
|
|
1699
|
+
known: rows.filter((r) => r.kind === 'known').length,
|
|
1700
|
+
open: rows.filter((r) => r.kind === 'open').length,
|
|
1701
|
+
rows,
|
|
1702
|
+
openRows: rows.filter((r) => r.kind === 'open'),
|
|
1703
|
+
};
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
/**
|
|
1707
|
+
* 模型提名一条纲(B 路径)。
|
|
1708
|
+
*
|
|
1709
|
+
* 算法只能从字面统计出"什么词反复出现",但**"这意味着什么"要靠理解**。
|
|
1710
|
+
* 模型看完对话觉得"她好像把上学当成一件很重的事",就调这个把它记成纲。
|
|
1711
|
+
*/
|
|
1712
|
+
export function defineGist(id = DEFAULT_ID, text = '', { keyword = '', count = 1 } = {}) {
|
|
1713
|
+
const brain = ensureBrain(id);
|
|
1714
|
+
const t = String(text ?? '').trim();
|
|
1715
|
+
if (t.length < 4) return { ok: false, reason: '纲至少 4 个字' };
|
|
1716
|
+
if (!Array.isArray(brain.memory.gists)) brain.memory.gists = [];
|
|
1717
|
+
const key = keyword || t.slice(0, 8);
|
|
1718
|
+
const id2 = `g_${key}`;
|
|
1719
|
+
const existed = brain.memory.gists.find((g) => g.id === id2);
|
|
1720
|
+
if (existed) {
|
|
1721
|
+
existed.text = t;
|
|
1722
|
+
existed.count = Number(count) || existed.count;
|
|
1723
|
+
existed.at = nowMs();
|
|
1724
|
+
} else {
|
|
1725
|
+
brain.memory.gists.push({
|
|
1726
|
+
id: id2, kind: 'gist', topic: 'model', keyword: key, text: t, count: Number(count) || 1, at: nowMs(),
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
saveBrain(brain);
|
|
1730
|
+
appendAudit(id, { kind: 'define-gist', keyword: key, text: t.slice(0, 50) });
|
|
1731
|
+
return { ok: true, id: id2, total: brain.memory.gists.length };
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/**
|
|
1735
|
+
* 标记「那个人不在了」。
|
|
1736
|
+
*
|
|
1737
|
+
* 不是解除关系——契约照旧永久,称呼照旧,记忆一条不删。
|
|
1738
|
+
* 变的只是:她知道了,他不会再来。
|
|
1739
|
+
*
|
|
1740
|
+
* **必须显式调用。** 不许系统凭"多久没说话"去猜一个人死没死。
|
|
1741
|
+
*/
|
|
1742
|
+
export function markAbsent(id = DEFAULT_ID, { since, note = '', status = 'absent' } = {}) {
|
|
1743
|
+
const brain = ensureBrain(id);
|
|
1744
|
+
if (!brain.relation) return { ok: false, reason: '没有关系契约' };
|
|
1745
|
+
brain.relation = markAbsentContract(brain.relation, { since, note, status });
|
|
1746
|
+
// 他的人物伞改成"曾经一直在"——但伞本身不删
|
|
1747
|
+
for (const u of brain.memory.umbrellas ?? []) {
|
|
1748
|
+
if (u.topic === 'person' && u.who && u.who === brain.relation.address) {
|
|
1749
|
+
u.absent = true;
|
|
1750
|
+
u.text = `${u.who}:曾经一直在的人`;
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
saveBrain(brain);
|
|
1754
|
+
appendAudit(id, { kind: 'absent', address: brain.relation.address, since: brain.relation.absentSince, note });
|
|
1755
|
+
return { ok: true, relation: brain.relation, line: relationLine(brain.relation) };
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
/** 人回来了 / 标错了 */
|
|
1759
|
+
export function clearAbsent(id = DEFAULT_ID) {
|
|
1760
|
+
const brain = ensureBrain(id);
|
|
1761
|
+
brain.relation = clearAbsentRelation(brain.relation);
|
|
1762
|
+
for (const u of brain.memory.umbrellas ?? []) {
|
|
1763
|
+
if (u.topic === 'person' && u.absent) {
|
|
1764
|
+
u.absent = false;
|
|
1765
|
+
u.text = `${u.who}:一直在的人`;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
saveBrain(brain);
|
|
1769
|
+
appendAudit(id, { kind: 'absent-cleared', address: brain.relation?.address ?? '' });
|
|
1770
|
+
return { ok: true, relation: brain.relation };
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
/* ── 概念:什么是什么,为什么要这么做 ───────────────────────── */
|
|
1774
|
+
|
|
1775
|
+
/**
|
|
1776
|
+
* 有人给她解释一个词。
|
|
1777
|
+
*
|
|
1778
|
+
* **这是"想通了"的那一刻**:不是新增记忆,是让过去几十条经历突然有了名字。
|
|
1779
|
+
*
|
|
1780
|
+
* learnConcept('old', '上学', {
|
|
1781
|
+
* definition: '为了学到知识、学会道理',
|
|
1782
|
+
* why: '不然什么都不会',
|
|
1783
|
+
* })
|
|
1784
|
+
*/
|
|
1785
|
+
export function learnNewConcept(id = DEFAULT_ID, term = '', { definition = '', why = '', source = 'told', who = '' } = {}) {
|
|
1786
|
+
const brain = ensureBrain(id);
|
|
1787
|
+
const r = learnConcept(brain.memory, term, { definition, why, source, who, at: nowMs() });
|
|
1788
|
+
if (!r.ok) return r;
|
|
1789
|
+
refreshNarrative(id, 'concept');
|
|
1790
|
+
saveBrain(brain);
|
|
1791
|
+
appendAudit(id, { kind: 'concept', term: r.term, linked: r.linked, source });
|
|
1792
|
+
return r;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
/** 问她「X 是什么」——不知道就说不知道,不编 */
|
|
1796
|
+
export function askWhat(id = DEFAULT_ID, term = '') {
|
|
1797
|
+
return conceptAnswer(ensureBrain(id).memory, term);
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
/** 她自己去问(因为不会才问,这才叫学习) */
|
|
1801
|
+
export function askSomeone(id = DEFAULT_ID, term = '', { knower = '' } = {}) {
|
|
1802
|
+
const brain = ensureBrain(id);
|
|
1803
|
+
const q = makeQuestion(brain.memory, term, { knower });
|
|
1804
|
+
if (q.asked) appendAudit(id, { kind: 'ask', term: q.term, to: knower });
|
|
1805
|
+
return q;
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
export function conceptList(id = DEFAULT_ID) {
|
|
1809
|
+
const brain = ensureBrain(id);
|
|
1810
|
+
const list = Object.values(brain.memory.concepts ?? {});
|
|
1811
|
+
return {
|
|
1812
|
+
total: list.length,
|
|
1813
|
+
terms: list.map((c) => c.term),
|
|
1814
|
+
detail: list,
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
/* ── 自我叙事:我是谁(会长的,不是写死的)────────────────────── */
|
|
1819
|
+
|
|
1820
|
+
/**
|
|
1821
|
+
* 重写「我是谁」。
|
|
1822
|
+
*
|
|
1823
|
+
* 用她自己的零件拼:出身 → 学会的道理 → 变过几次 → 谁一直在。
|
|
1824
|
+
* 每一版都留下来——将来能说"我以前以为自己是……"。
|
|
1825
|
+
*/
|
|
1826
|
+
export function refreshNarrative(idOrBrain = DEFAULT_ID, why = 'auto') {
|
|
1827
|
+
const fromId = typeof idOrBrain === 'string';
|
|
1828
|
+
const brain = fromId ? ensureBrain(idOrBrain) : idOrBrain;
|
|
1829
|
+
if (!brain) return { changed: false, text: '' };
|
|
1830
|
+
const next = composeNarrative({
|
|
1831
|
+
cardName: brain.roleCard ?? '鱼',
|
|
1832
|
+
traits: brain.persona.traits,
|
|
1833
|
+
umbrellas: brain.memory.umbrellas ?? [],
|
|
1834
|
+
concepts: brain.memory.concepts ?? {},
|
|
1835
|
+
shells: (brain.memory.cards ?? []).filter((c) => c.source === 'shell').length,
|
|
1836
|
+
relation: brain.relation,
|
|
1837
|
+
});
|
|
1838
|
+
const prev = brain.self?.narrativeText ?? (typeof brain.self?.narrative === 'string' ? brain.self.narrative : '');
|
|
1839
|
+
if (!narrativeChanged(prev, next)) {
|
|
1840
|
+
if (fromId) { /* 没变也要落盘,保证首版存在 */ saveBrain(brain); }
|
|
1841
|
+
return { changed: false, text: next, version: (brain.self?.narrativeHistory ?? []).length };
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
brain.self = brain.self ?? {};
|
|
1845
|
+
brain.self.narrativeText = next;
|
|
1846
|
+
brain.self.narrative = next;
|
|
1847
|
+
if (!Array.isArray(brain.self.narrativeHistory)) brain.self.narrativeHistory = [];
|
|
1848
|
+
brain.self.narrativeHistory = [...brain.self.narrativeHistory, { text: next, at: nowMs(), why }].slice(-12);
|
|
1849
|
+
if (fromId) { saveBrain(brain); appendAudit(idOrBrain, { kind: 'narrative', why, text: next.slice(0, 60) }); }
|
|
1850
|
+
return { changed: true, text: next, version: brain.self.narrativeHistory.length };
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
/** 模型改写「我是谁」(理解是模型的事,脑只负责存和留档) */
|
|
1854
|
+
export function setNarrative(id = DEFAULT_ID, text = '', { why = 'model' } = {}) {
|
|
1855
|
+
const brain = ensureBrain(id);
|
|
1856
|
+
const t = String(text ?? '').trim();
|
|
1857
|
+
if (t.length < 6) return { ok: false, reason: '太短了' };
|
|
1858
|
+
brain.self = brain.self ?? {};
|
|
1859
|
+
brain.self.narrativeText = t.slice(0, NARRATIVE_MAX);
|
|
1860
|
+
brain.self.narrative = brain.self.narrativeText;
|
|
1861
|
+
if (!Array.isArray(brain.self.narrativeHistory)) brain.self.narrativeHistory = [];
|
|
1862
|
+
brain.self.narrativeHistory = [...brain.self.narrativeHistory, { text: brain.self.narrativeText, at: nowMs(), why }].slice(-12);
|
|
1863
|
+
saveBrain(brain);
|
|
1864
|
+
appendAudit(id, { kind: 'narrative', why, text: brain.self.narrativeText.slice(0, 60) });
|
|
1865
|
+
return { ok: true, text: brain.self.narrativeText, version: brain.self.narrativeHistory.length };
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
export function narrativeOf(id = DEFAULT_ID) {
|
|
1869
|
+
const b = ensureBrain(id);
|
|
1870
|
+
return {
|
|
1871
|
+
text: b.self?.narrativeText ?? b.self?.narrative ?? '',
|
|
1872
|
+
history: b.self?.narrativeHistory ?? [],
|
|
1873
|
+
version: (b.self?.narrativeHistory ?? []).length,
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
/**
|
|
1878
|
+
* 给一个**不是主人**的人标缺位(B 路径)。
|
|
1879
|
+
*
|
|
1880
|
+
* 主人走的是 relation.absent;爷爷奶奶、小主人这类人走这里。
|
|
1881
|
+
* 门槛:恩情要到「对我挺好的」(close)以上——才配得上"我记住他不在了"。
|
|
1882
|
+
*/
|
|
1883
|
+
export function markAbsentFor(id = DEFAULT_ID, who = '', { since, note = '', status = 'absent' } = {}) {
|
|
1884
|
+
const brain = ensureBrain(id);
|
|
1885
|
+
const name = String(who ?? '').trim();
|
|
1886
|
+
if (!name) return { ok: false, reason: '没说谁' };
|
|
1887
|
+
if (name === brain.relation?.address) {
|
|
1888
|
+
return markAbsent(id, { since, note, status });
|
|
1889
|
+
}
|
|
1890
|
+
const r = markBondAbsent(brain.memory, name, { since: since ?? nowMs(), note, status });
|
|
1891
|
+
if (!r.ok) return r;
|
|
1892
|
+
saveBrain(brain);
|
|
1893
|
+
appendAudit(id, { kind: 'absent-bond', who: name, note });
|
|
1894
|
+
return { ok: true, absence: r.absence, bond: r.bond, line: bondLine(brain.memory, name) };
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
export function clearAbsentFor(id = DEFAULT_ID, who = '') {
|
|
1898
|
+
const brain = ensureBrain(id);
|
|
1899
|
+
if (who === brain.relation?.address) return clearAbsent(id);
|
|
1900
|
+
clearBondAbsent(brain.memory, who);
|
|
1901
|
+
saveBrain(brain);
|
|
1902
|
+
return { ok: true, who };
|
|
1903
|
+
}
|
|
1904
|
+
|
|
706
1905
|
export function snapshot(id = DEFAULT_ID) {
|
|
707
1906
|
const brain = ensureBrain(id);
|
|
708
1907
|
const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
|
|
@@ -730,8 +1929,18 @@ export function snapshot(id = DEFAULT_ID) {
|
|
|
730
1929
|
relation: brain.relation,
|
|
731
1930
|
weights: weightReport(brain.persona.units),
|
|
732
1931
|
personaSource: brain.persona.source ?? null,
|
|
733
|
-
apps: appSummary(brain.memory),
|
|
1932
|
+
apps: appSummary(brain.memory, brain.persona.traits),
|
|
734
1933
|
affect: brain.affect,
|
|
1934
|
+
runtime: {
|
|
1935
|
+
shadow: Boolean(shadowMode || brain.meta.shadow),
|
|
1936
|
+
ttlPolicy,
|
|
1937
|
+
moodPolicy,
|
|
1938
|
+
dataDir: dataDir(),
|
|
1939
|
+
dataDirSource: dataDirSource(),
|
|
1940
|
+
dataDirInsidePackage: isDataDirInsidePackage(),
|
|
1941
|
+
roleDir: roleDir(),
|
|
1942
|
+
},
|
|
1943
|
+
contractWarnings: brain.meta.contractWarnings ?? [],
|
|
735
1944
|
emotion: {
|
|
736
1945
|
stage: emotion.stageOf(brain.vocab),
|
|
737
1946
|
words: Object.keys(brain.vocab),
|
|
@@ -779,7 +1988,12 @@ export function forgetCache(id) {
|
|
|
779
1988
|
* fy.tick()
|
|
780
1989
|
*/
|
|
781
1990
|
export function createBrain(options = {}) {
|
|
782
|
-
configure({
|
|
1991
|
+
configure({
|
|
1992
|
+
dataDir: options.dataDir,
|
|
1993
|
+
roleDir: options.roleDir,
|
|
1994
|
+
shadow: options.shadow,
|
|
1995
|
+
ttl: options.ttlPolicy,
|
|
1996
|
+
});
|
|
783
1997
|
const id = options.id ?? DEFAULT_ID;
|
|
784
1998
|
|
|
785
1999
|
// 第一次建这条鱼时,把关系和称呼一起落进去——
|
|
@@ -800,11 +2014,30 @@ export function createBrain(options = {}) {
|
|
|
800
2014
|
return {
|
|
801
2015
|
id,
|
|
802
2016
|
get brain() { return ensureBrain(id); },
|
|
803
|
-
wake(event) {
|
|
2017
|
+
wake(event, opts) {
|
|
804
2018
|
if (shouldObserve(event)) observe(id, event);
|
|
805
|
-
return { text: wakeLine(id, event), id };
|
|
2019
|
+
return { text: wakeLine(id, event, opts), id };
|
|
806
2020
|
},
|
|
807
|
-
observe(event) { return observe(id, event); },
|
|
2021
|
+
observe(event, opts) { return observe(id, event, opts); },
|
|
2022
|
+
/** 「我还是我吗」三件套体检 */
|
|
2023
|
+
identity() { return identityCheck(id); },
|
|
2024
|
+
/** 打包带走 */
|
|
2025
|
+
exportPack(opts) { return exportPack(id, opts); },
|
|
2026
|
+
/** 存档 / 回滚 */
|
|
2027
|
+
snapshot(name) { return snapshotBrain(id, name); },
|
|
2028
|
+
restore(name) { return restoreBrain(id, name); },
|
|
2029
|
+
snapshots() { return listSnapshots(id); },
|
|
2030
|
+
/** 把宿主已有的历史灌进来 */
|
|
2031
|
+
importEpisodes(list, opts) { return importEpisodes(id, list, opts); },
|
|
2032
|
+
/** 日记:她的心房 */
|
|
2033
|
+
diary(date) { return diaryDigest(id, date); },
|
|
2034
|
+
writeDiary(opts) { return writeDiary(id, opts); },
|
|
2035
|
+
readDiary(date) { return readDiary(id, date); },
|
|
2036
|
+
listDiary() { return listDiary(id); },
|
|
2037
|
+
importDiary(list, opts) { return importDiary(id, list, opts); },
|
|
2038
|
+
/** 老鱼预装情绪词 / 精确导入词表 */
|
|
2039
|
+
seedVocab(words) { return seedVocab(id, words); },
|
|
2040
|
+
importVocab(list) { return importVocab(id, list); },
|
|
808
2041
|
tick(now) { return settleBrain(id, now); },
|
|
809
2042
|
brief() { return getBrief(id); },
|
|
810
2043
|
snapshot() { return snapshot(id); },
|
|
@@ -849,10 +2082,14 @@ export { LABELS, listBrains, readAudit, addImagination, addEpisode };
|
|
|
849
2082
|
export { flowLevel, flowName, styleVector };
|
|
850
2083
|
export { attribute } from './core/attribution.js';
|
|
851
2084
|
export { PATIENCE_DELTA, applyPatience, isOutburst, whimProbability, wakeReply, sampleStyle } from './core/derive.js';
|
|
852
|
-
export { retrieve } from './core/memory.js';
|
|
2085
|
+
export { retrieve, settle, recall, touchByIds } from './core/memory.js';
|
|
853
2086
|
export { brief } from './core/persona.js';
|
|
854
2087
|
export { normalizeEvent, toCue, toObservation, shouldObserve, keywords } from './core/event.js';
|
|
855
2088
|
export { dataDir, roleDir } from './store.js';
|
|
2089
|
+
export { dataDirSource, isDataDirInsidePackage } from './store.js';
|
|
2090
|
+
export { readYear, listYears, setEpisodeWindow, episodeWindow } from './store.js';
|
|
2091
|
+
export { lintCard } from './core/extract.js';
|
|
2092
|
+
export { dedupeKey } from './adapters/qq-bridge.js';
|
|
856
2093
|
export { createBridgeAdapter } from './adapters/qq-bridge.js';
|
|
857
2094
|
export {
|
|
858
2095
|
createBody, chooseBody, bodyScores, bodyLine, canDo, hasCapability,
|
|
@@ -866,9 +2103,10 @@ export {
|
|
|
866
2103
|
learn as learnWord, induce as induceWord, describeSensation,
|
|
867
2104
|
} from './core/emotion.js';
|
|
868
2105
|
|
|
869
|
-
/* 记忆卡片 */
|
|
2106
|
+
/* 记忆卡片 + 两层老化 */
|
|
870
2107
|
export {
|
|
871
2108
|
makeCard, addCard, shouldCompact, CARD_THRESHOLD_CHARS, CARD_MAX_CHARS,
|
|
2109
|
+
COMPRESS_DAYS, FORGET_DAYS,
|
|
872
2110
|
} from './core/memory.js';
|
|
873
2111
|
|
|
874
2112
|
/* 平台记忆 + 口味闭环 */
|