feiyu-brain 1.5.0 → 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 +1 -1
- package/cli.mjs +31 -1
- package/cordis.patch.yml +13 -1
- package/core/bond.js +186 -0
- package/core/concept.js +138 -0
- package/core/extract.js +75 -2
- package/core/memory.js +539 -18
- package/core/persona.js +91 -4
- package/core/relation.js +78 -0
- package/core/self.js +72 -0
- package/docs/MEMORY.md +180 -15
- package/index.js +574 -44
- package/package.json +1 -1
- package/selftest.mjs +37 -3
- package/store.js +141 -10
package/index.js
CHANGED
|
@@ -10,12 +10,15 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import crypto from 'node:crypto';
|
|
12
12
|
|
|
13
|
-
import { birthFromCard, lintCard } 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';
|
|
@@ -31,15 +34,20 @@ import {
|
|
|
31
34
|
import {
|
|
32
35
|
ROOT, loadBrain, saveBrain, appendAudit, readAudit, listBrains,
|
|
33
36
|
setDataDir, setRoleDir, dataDir, roleDir, brainDir, dataDirSource, isDataDirInsidePackage,
|
|
37
|
+
setEpisodeWindow, episodeWindow, readYear, listYears,
|
|
34
38
|
} from './store.js';
|
|
35
39
|
|
|
36
40
|
const DEFAULT_ID = 'default';
|
|
37
41
|
const cache = new Map();
|
|
38
42
|
|
|
39
43
|
/* 全局开关(configure 改) */
|
|
40
|
-
let shadowMode = false; //
|
|
44
|
+
let shadowMode = false; // 影子模式:算但不写人设,全记进 shadow.jsonl
|
|
41
45
|
let ttlPolicy = 'hard'; // hard | summarize | archive | off
|
|
42
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; // 脑里最多存多少条,超了最老的压卡片
|
|
43
51
|
|
|
44
52
|
function nowMs() {
|
|
45
53
|
return Date.now();
|
|
@@ -60,12 +68,33 @@ function logOnce(msg) {
|
|
|
60
68
|
* configure({ shadow: true }) 影子模式:observe 只留审计,不动人设、不落盘
|
|
61
69
|
* configure({ ttlPolicy: 'off' }) hard(默认) | summarize(过期前压卡片) | off(永不遗忘)
|
|
62
70
|
*/
|
|
63
|
-
|
|
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
|
+
} = {}) {
|
|
64
87
|
if (d) setDataDir(d);
|
|
65
88
|
if (r) setRoleDir(r);
|
|
66
89
|
if (typeof shadow === 'boolean') shadowMode = shadow;
|
|
67
90
|
if (ttl && ['hard', 'summarize', 'archive', 'off'].includes(ttl)) ttlPolicy = ttl;
|
|
68
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);
|
|
69
98
|
}
|
|
70
99
|
|
|
71
100
|
export function runtimeOptions() {
|
|
@@ -73,6 +102,10 @@ export function runtimeOptions() {
|
|
|
73
102
|
shadow: shadowMode,
|
|
74
103
|
ttlPolicy,
|
|
75
104
|
moodPolicy,
|
|
105
|
+
compressDays,
|
|
106
|
+
forgetDays,
|
|
107
|
+
briefChars,
|
|
108
|
+
maxEpisodes,
|
|
76
109
|
dataDir: dataDir(),
|
|
77
110
|
dataDirSource: dataDirSource(),
|
|
78
111
|
dataDirInsidePackage: isDataDirInsidePackage(),
|
|
@@ -136,7 +169,7 @@ export function resolveRoleCard(roleName) {
|
|
|
136
169
|
}
|
|
137
170
|
|
|
138
171
|
function refreshBrief(brain) {
|
|
139
|
-
brain.persona.brief = brief(brain.persona.units);
|
|
172
|
+
brain.persona.brief = brief(brain.persona.units, { maxChars: briefChars });
|
|
140
173
|
return brain;
|
|
141
174
|
}
|
|
142
175
|
|
|
@@ -171,7 +204,10 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
171
204
|
if (fs.existsSync(sidecar)) traitsOverride = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
|
|
172
205
|
} catch { traitsOverride = null; }
|
|
173
206
|
|
|
174
|
-
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; }
|
|
175
211
|
const brain = {
|
|
176
212
|
id,
|
|
177
213
|
schema: 'brain/2',
|
|
@@ -180,8 +216,16 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
180
216
|
persona: {
|
|
181
217
|
seed: cardName ? `card:${card.name}` : `${roleDir()}/${card.name}.md`,
|
|
182
218
|
traits,
|
|
219
|
+
// 已知 12 维(先验)与她自己长出来的维度分开存,方便看"哪些是她的原话"
|
|
220
|
+
knownTraits: knownTraits ?? traits,
|
|
221
|
+
openTraits: openTraits ?? {},
|
|
183
222
|
units,
|
|
184
223
|
brief: '',
|
|
224
|
+
// 一年一度蜕壳:把这一年掉出去的人设打包成永久记忆卡片
|
|
225
|
+
shellYear: new Date(born).getFullYear(),
|
|
226
|
+
shellAt: born,
|
|
227
|
+
// 最近几天的权重变动,用来生成「最近」那一段
|
|
228
|
+
moves: [],
|
|
185
229
|
// 人格主档只有一个:这里。外部卡只是"导入源",导过就记下来。
|
|
186
230
|
source: {
|
|
187
231
|
kind: cardText ? 'inline' : 'file',
|
|
@@ -251,9 +295,9 @@ export function getBrief(id = DEFAULT_ID) {
|
|
|
251
295
|
* sections 可选:persona / flow / body / mood / memory / search
|
|
252
296
|
* budget 是**总字数上限**,超了就从低优先级的段开始砍(persona 保底不砍)。
|
|
253
297
|
*/
|
|
254
|
-
export const WAKE_SECTIONS = ['persona', 'flow', 'body', 'mood', 'memory', 'search'];
|
|
298
|
+
export const WAKE_SECTIONS = ['persona', 'self', 'relation', 'bond', 'concept', 'flow', 'body', 'mood', 'recent', 'memory', 'search'];
|
|
255
299
|
/** 预算不够时的砍法:越靠后越先砍 */
|
|
256
|
-
const WAKE_PRIORITY = ['persona', 'mood', 'flow', 'memory', 'body', 'search'];
|
|
300
|
+
const WAKE_PRIORITY = ['persona', 'self', 'relation', 'concept', 'bond', 'mood', 'recent', 'flow', 'memory', 'body', 'search'];
|
|
257
301
|
|
|
258
302
|
export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
259
303
|
const brain = ensureBrain(id);
|
|
@@ -268,6 +312,26 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
|
268
312
|
brain.state.flow = level;
|
|
269
313
|
|
|
270
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
|
+
}
|
|
271
335
|
if (level !== 1) seg.flow = `【意识流】${flowName(level)}`;
|
|
272
336
|
|
|
273
337
|
const bodyText = bodyLine(brain.body);
|
|
@@ -283,9 +347,21 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
|
283
347
|
}
|
|
284
348
|
|
|
285
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}`;
|
|
286
360
|
if (cue) {
|
|
287
361
|
const hit = retrieve(cue, brain.memory);
|
|
288
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());
|
|
289
365
|
|
|
290
366
|
// 外部检索器(向量/图谱):同步读缓存,不 await
|
|
291
367
|
if (extraRetriever) {
|
|
@@ -340,34 +416,59 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
340
416
|
const conflicting = ev.conflicting ?? matchUnits(brain.persona.units, ev.text ?? '').conflicting;
|
|
341
417
|
|
|
342
418
|
// ── 影子模式 ──
|
|
343
|
-
//
|
|
344
|
-
//
|
|
345
|
-
//
|
|
419
|
+
// 算但不写:人设权重、记忆、brain.json 一个字不动。
|
|
420
|
+
// 但**不是空跑**——这一次的「本来会发生什么」全记进 shadow.jsonl,
|
|
421
|
+
// 跑一百轮之后能看见她会长成什么样,再决定要不要真接。
|
|
346
422
|
if (shadowMode || brain.meta.shadow) {
|
|
347
423
|
const would = brain.persona.units
|
|
348
424
|
.filter((u) => consistent.includes(u.id) || conflicting.includes(u.id))
|
|
349
425
|
.map((u) => ({
|
|
350
426
|
id: u.id,
|
|
427
|
+
text: u.text.slice(0, 30),
|
|
351
428
|
from: Number(u.weight.toFixed(3)),
|
|
352
429
|
to: Number(Math.max(0, Math.min(1, u.weight + (consistent.includes(u.id) ? 1 : -1) * 0.01)).toFixed(3)),
|
|
353
430
|
}));
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
shadow: true,
|
|
431
|
+
|
|
432
|
+
const entry = {
|
|
357
433
|
at,
|
|
358
|
-
text: String(ev.text ?? ev.what ?? '').slice(0,
|
|
434
|
+
text: String(ev.text ?? ev.what ?? '').slice(0, 100),
|
|
359
435
|
wouldChange: would,
|
|
360
|
-
|
|
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
|
+
}
|
|
361
445
|
return {
|
|
362
|
-
brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would,
|
|
446
|
+
brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would, shadowFile: path.join(brainDir(id), 'shadow.jsonl'),
|
|
363
447
|
};
|
|
364
448
|
}
|
|
365
449
|
|
|
366
450
|
// step:默认 1(每次 ±0.01)。只有传了 magnitude(重大转折)才放大,上限 5。
|
|
367
451
|
const step = Math.max(1, Math.min(5, Number(ev.magnitude) || 1));
|
|
368
452
|
if (doEvolve) {
|
|
453
|
+
const beforeW = new Map(brain.persona.units.map((u) => [u.id, u.weight]));
|
|
369
454
|
brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
|
|
370
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
|
+
|
|
371
472
|
// 蜕皮
|
|
372
473
|
const sh = shed(brain.persona.units, { at });
|
|
373
474
|
if (sh.formerSelves.length) {
|
|
@@ -398,7 +499,9 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
398
499
|
? ev
|
|
399
500
|
: (ev.text ? { who: ev.who ?? ev.sender ?? '', what: String(ev.text).slice(0, 80), feel: ev.feel ?? '', via: ev.via ?? 'api' } : null);
|
|
400
501
|
if (doRemember && obs?.what) {
|
|
401
|
-
|
|
502
|
+
// 反复出现的事 → 重要记忆,永不压扁
|
|
503
|
+
const rep = detectRepeat(brain.memory, { who: obs.who ?? '', what: obs.what }, at);
|
|
504
|
+
const ep = addEpisode(brain.memory, {
|
|
402
505
|
who: obs.who ?? '',
|
|
403
506
|
what: obs.what,
|
|
404
507
|
feel: ev.feel ?? '',
|
|
@@ -409,7 +512,14 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
409
512
|
strategy: ev.action?.strategy ?? null,
|
|
410
513
|
evidence: obs.via ?? 'chat',
|
|
411
514
|
source: 'live',
|
|
515
|
+
...(rep.important ? { important: true, longTerm: true, importantCount: rep.count, importantSample: rep.sample } : {}),
|
|
412
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
|
+
}
|
|
413
523
|
}
|
|
414
524
|
|
|
415
525
|
if (doRemember && ev.action) {
|
|
@@ -454,6 +564,21 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
454
564
|
im.lastAt = at;
|
|
455
565
|
if (ev.feel) im.traits = [...new Set([...(im.traits ?? []), ev.feel])].slice(-6);
|
|
456
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
|
+
}
|
|
457
582
|
}
|
|
458
583
|
|
|
459
584
|
brain.meta.observations += 1;
|
|
@@ -487,34 +612,78 @@ function bigrams(text) {
|
|
|
487
612
|
return set;
|
|
488
613
|
}
|
|
489
614
|
|
|
490
|
-
/**
|
|
615
|
+
/**
|
|
616
|
+
* 每日结算:人设衰减 + 记忆两层老化(压扁 → 遗忘)+ 蜕皮。幂等,可以随便跑。
|
|
617
|
+
*
|
|
618
|
+
* 老化不是"到期删除":先压扁成一句"大概",再更久没人提才真正遗忘。
|
|
619
|
+
* 全程把原文摊进 archive.jsonl——**忘的是检索,不是档案。**
|
|
620
|
+
*/
|
|
491
621
|
export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
|
|
492
622
|
const brain = ensureBrain(id);
|
|
493
623
|
const days = Math.max(0, (now - (brain.meta.lastSettle ?? now)) / (24 * 60 * 60 * 1000));
|
|
494
624
|
if (days >= 1) {
|
|
495
|
-
|
|
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 });
|
|
496
658
|
const sh = shed(brain.persona.units, { at: now });
|
|
497
659
|
if (sh.formerSelves.length) {
|
|
498
660
|
brain.persona.units = sh.units;
|
|
499
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
|
+
}
|
|
500
665
|
}
|
|
501
666
|
|
|
502
667
|
if (ttlPolicy === 'summarize' || ttlPolicy === 'archive') {
|
|
503
|
-
// 过期前先压一张卡片——"忘了细节,但记得大概"
|
|
504
668
|
const card = makeCard(brain.memory.episodes.slice(-12));
|
|
505
669
|
if (card) addCard(brain.memory, card);
|
|
506
670
|
}
|
|
507
671
|
|
|
508
|
-
const
|
|
509
|
-
if (ttlPolicy !== 'off')
|
|
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
|
+
});
|
|
679
|
+
}
|
|
510
680
|
|
|
511
|
-
//
|
|
512
|
-
if (
|
|
681
|
+
// 原文一律留档:压扁的和遗忘的都写进 archive.jsonl
|
|
682
|
+
if (archived.length) {
|
|
513
683
|
try {
|
|
514
|
-
const newly = brain.memory.forgotten.slice(before);
|
|
515
684
|
fs.appendFileSync(
|
|
516
685
|
path.join(brainDir(id), 'archive.jsonl'),
|
|
517
|
-
`${
|
|
686
|
+
`${archived.map((x) => JSON.stringify(x)).join('\n')}\n`,
|
|
518
687
|
'utf8',
|
|
519
688
|
);
|
|
520
689
|
} catch (e) {
|
|
@@ -525,9 +694,18 @@ export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
|
|
|
525
694
|
brain.memory.forgotten = brain.memory.forgotten.slice(-500);
|
|
526
695
|
}
|
|
527
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
|
+
|
|
528
705
|
brain.meta.lastSettle = now;
|
|
529
706
|
refreshBrief(brain);
|
|
530
707
|
saveBrain(brain);
|
|
708
|
+
if (archived.length) appendAudit(id, { kind: 'aging', archived: archived.length });
|
|
531
709
|
}
|
|
532
710
|
return brain;
|
|
533
711
|
}
|
|
@@ -596,7 +774,11 @@ export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' }
|
|
|
596
774
|
const what = String(it?.text ?? it?.what ?? '').trim();
|
|
597
775
|
if (!what) { skipped += 1; continue; }
|
|
598
776
|
const at = Number(it?.at) || nowMs();
|
|
777
|
+
// ⚠️ 第三个参数必须是「现在」,不是 at。
|
|
778
|
+
// 它同时决定 lastRecall(多久没被提起);传历史时间会让刚搬进来的记忆
|
|
779
|
+
// 一出生就过期,第一次结算就被清空。
|
|
599
780
|
addEpisode(brain.memory, {
|
|
781
|
+
at,
|
|
600
782
|
who: it.who ?? '',
|
|
601
783
|
what: what.slice(0, 140),
|
|
602
784
|
feel: it.feel ?? '',
|
|
@@ -606,8 +788,10 @@ export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' }
|
|
|
606
788
|
context: it.context ?? null,
|
|
607
789
|
strategy: it.strategy ?? null,
|
|
608
790
|
evidence: it.via ?? source,
|
|
609
|
-
source, // live | import
|
|
610
|
-
|
|
791
|
+
source, // live | import | diary
|
|
792
|
+
// 搬进来的是「已经沉淀过的」——它在宿主那边活过了,不该再按新经历老化
|
|
793
|
+
...(source === 'import' ? { longTerm: Boolean(it.longTerm ?? false) } : {}),
|
|
794
|
+
}, nowMs());
|
|
611
795
|
imported += 1;
|
|
612
796
|
const who = String(it.who ?? '').trim();
|
|
613
797
|
if (who) touched.set(who, (touched.get(who) ?? 0) + 1);
|
|
@@ -732,8 +916,7 @@ export function learnEmotion(id = DEFAULT_ID, word, { pad, sources = [], cause =
|
|
|
732
916
|
}
|
|
733
917
|
|
|
734
918
|
/** 阶段三:从 ≥3 个实例里自己归纳出这个词的含义。 */
|
|
735
|
-
export function induceEmotion(id = DEFAULT_ID, word) {
|
|
736
|
-
const brain = ensureBrain(id);
|
|
919
|
+
export function induceEmotion(id = DEFAULT_ID, word) { const brain = ensureBrain(id);
|
|
737
920
|
const r = emotion.induce(brain.vocab, word);
|
|
738
921
|
if (r.induced) {
|
|
739
922
|
brain.vocab = r.vocab;
|
|
@@ -752,6 +935,67 @@ export function vocabOf(id = DEFAULT_ID) {
|
|
|
752
935
|
};
|
|
753
936
|
}
|
|
754
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
|
+
|
|
755
999
|
/* ── 记忆卡片:上下文过长时压缩中段 ───────────────────────────── */
|
|
756
1000
|
|
|
757
1001
|
export function needsCard(id = DEFAULT_ID, contextChars = 0) {
|
|
@@ -1151,28 +1395,35 @@ export const MAX_EPISODES = 5000;
|
|
|
1151
1395
|
|
|
1152
1396
|
/**
|
|
1153
1397
|
* 容量保护:最老的一批压成卡片,原文进 archive.jsonl。
|
|
1154
|
-
*
|
|
1398
|
+
*
|
|
1399
|
+
* 不是"一次吃掉两百条"——按 20 条一张卡片分批压,别让一次溢出把半年吃成 160 字。
|
|
1155
1400
|
*/
|
|
1156
1401
|
function enforceCapacity(brain) {
|
|
1157
1402
|
const eps = brain.memory.episodes;
|
|
1158
|
-
if (eps.length <=
|
|
1159
|
-
const overflow = eps.length -
|
|
1160
|
-
const take = Math.min(overflow
|
|
1403
|
+
if (eps.length <= maxEpisodes) return { compacted: 0, cards: 0 };
|
|
1404
|
+
const overflow = eps.length - maxEpisodes;
|
|
1405
|
+
const take = Math.min(overflow, eps.length);
|
|
1161
1406
|
const oldest = eps.slice(0, take);
|
|
1162
|
-
|
|
1163
|
-
|
|
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
|
+
|
|
1164
1415
|
try {
|
|
1165
1416
|
fs.appendFileSync(
|
|
1166
1417
|
path.join(brainDir(brain.id), 'archive.jsonl'),
|
|
1167
|
-
`${oldest.map((x) => JSON.stringify(x)).join('\n')}\n`,
|
|
1418
|
+
`${oldest.map((x) => JSON.stringify({ ...x, archiveReason: 'capacity' })).join('\n')}\n`,
|
|
1168
1419
|
'utf8',
|
|
1169
1420
|
);
|
|
1170
1421
|
} catch (e) {
|
|
1171
1422
|
logOnce(`[brain] 容量归档失败(已忽略):${e?.message ?? e}`);
|
|
1172
1423
|
}
|
|
1173
1424
|
brain.memory.episodes = eps.slice(take);
|
|
1174
|
-
appendAudit(brain.id, { kind: 'capacity', compacted: take });
|
|
1175
|
-
return { compacted: take,
|
|
1425
|
+
appendAudit(brain.id, { kind: 'capacity', compacted: take, cards });
|
|
1426
|
+
return { compacted: take, cards };
|
|
1176
1427
|
}
|
|
1177
1428
|
|
|
1178
1429
|
/**
|
|
@@ -1363,6 +1614,35 @@ export function listDiary(id = DEFAULT_ID) {
|
|
|
1363
1614
|
.sort((a, b) => (a.date < b.date ? 1 : -1));
|
|
1364
1615
|
}
|
|
1365
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
|
+
|
|
1366
1646
|
/** 日记也能被检索:问"你写过什么"时用它 */
|
|
1367
1647
|
export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
|
|
1368
1648
|
const list = listDiary(id);
|
|
@@ -1378,6 +1658,250 @@ export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
|
|
|
1378
1658
|
return hits;
|
|
1379
1659
|
}
|
|
1380
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
|
+
|
|
1381
1905
|
export function snapshot(id = DEFAULT_ID) {
|
|
1382
1906
|
const brain = ensureBrain(id);
|
|
1383
1907
|
const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
|
|
@@ -1510,6 +2034,10 @@ export function createBrain(options = {}) {
|
|
|
1510
2034
|
writeDiary(opts) { return writeDiary(id, opts); },
|
|
1511
2035
|
readDiary(date) { return readDiary(id, date); },
|
|
1512
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); },
|
|
1513
2041
|
tick(now) { return settleBrain(id, now); },
|
|
1514
2042
|
brief() { return getBrief(id); },
|
|
1515
2043
|
snapshot() { return snapshot(id); },
|
|
@@ -1554,11 +2082,12 @@ export { LABELS, listBrains, readAudit, addImagination, addEpisode };
|
|
|
1554
2082
|
export { flowLevel, flowName, styleVector };
|
|
1555
2083
|
export { attribute } from './core/attribution.js';
|
|
1556
2084
|
export { PATIENCE_DELTA, applyPatience, isOutburst, whimProbability, wakeReply, sampleStyle } from './core/derive.js';
|
|
1557
|
-
export { retrieve } from './core/memory.js';
|
|
2085
|
+
export { retrieve, settle, recall, touchByIds } from './core/memory.js';
|
|
1558
2086
|
export { brief } from './core/persona.js';
|
|
1559
2087
|
export { normalizeEvent, toCue, toObservation, shouldObserve, keywords } from './core/event.js';
|
|
1560
2088
|
export { dataDir, roleDir } from './store.js';
|
|
1561
2089
|
export { dataDirSource, isDataDirInsidePackage } from './store.js';
|
|
2090
|
+
export { readYear, listYears, setEpisodeWindow, episodeWindow } from './store.js';
|
|
1562
2091
|
export { lintCard } from './core/extract.js';
|
|
1563
2092
|
export { dedupeKey } from './adapters/qq-bridge.js';
|
|
1564
2093
|
export { createBridgeAdapter } from './adapters/qq-bridge.js';
|
|
@@ -1574,9 +2103,10 @@ export {
|
|
|
1574
2103
|
learn as learnWord, induce as induceWord, describeSensation,
|
|
1575
2104
|
} from './core/emotion.js';
|
|
1576
2105
|
|
|
1577
|
-
/* 记忆卡片 */
|
|
2106
|
+
/* 记忆卡片 + 两层老化 */
|
|
1578
2107
|
export {
|
|
1579
2108
|
makeCard, addCard, shouldCompact, CARD_THRESHOLD_CHARS, CARD_MAX_CHARS,
|
|
2109
|
+
COMPRESS_DAYS, FORGET_DAYS,
|
|
1580
2110
|
} from './core/memory.js';
|
|
1581
2111
|
|
|
1582
2112
|
/* 平台记忆 + 口味闭环 */
|