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/cli.mjs CHANGED
@@ -83,7 +83,7 @@ function isNoCard(e) {
83
83
  return /找不到角色卡/.test(String(e?.message ?? e));
84
84
  }
85
85
 
86
- function run() {
86
+ async function run() {
87
87
  const cmd = rawCmd || 'status';
88
88
 
89
89
  switch (cmd) {
@@ -156,6 +156,279 @@ function run() {
156
156
  return;
157
157
  }
158
158
 
159
+ case 'snapshot': {
160
+ const r = brain.snapshotBrain(ID, args[0]);
161
+ line(`已存档:${r.name}`);
162
+ line(r.file);
163
+ return;
164
+ }
165
+
166
+ case 'restore': {
167
+ const r = brain.restoreBrain(ID, args[0]);
168
+ if (!r.ok) {
169
+ line(`✘ ${r.reason}`);
170
+ if (r.available?.length) line(`可用:${r.available.join(', ')}`);
171
+ return;
172
+ }
173
+ line(`已退回 ${r.restored}`);
174
+ line(`体检:${r.check.verdict}`);
175
+ return;
176
+ }
177
+
178
+ case 'snapshots': {
179
+ const list = brain.listSnapshots(ID);
180
+ if (!list.length) { line('还没有快照。'); return; }
181
+ for (const s of list) line(` ${s.name} ${(s.size / 1024).toFixed(1)} KB`);
182
+ return;
183
+ }
184
+
185
+ case 'lint': {
186
+ const file = args[0];
187
+ let text = '';
188
+ if (file && fs.existsSync(file)) {
189
+ text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
190
+ } else {
191
+ const card = brain.resolveRoleCard();
192
+ if (!card?.text) { line('没有卡可体检;用法:npx feiyu lint <卡的路径>'); return; }
193
+ text = card.text;
194
+ line(`(体检当前卡:${card.file})`);
195
+ line();
196
+ }
197
+ const r = brain.lintCard(text);
198
+ line(`可抽成命题 ${r.units} 条:${Object.entries(r.byKind).map(([k, v]) => `${k} ${v}`).join(' / ') || '无'}`);
199
+ line(`被忽略 ${r.dropped.length} 行`);
200
+ line();
201
+ line('命题预览:');
202
+ for (const p of r.preview) line(` ${p}`);
203
+ if (r.suggestSplit.length) {
204
+ line();
205
+ line(`⚠️ 有 ${r.suggestSplit.length} 行更像操作手册,建议拆出人设:`);
206
+ for (const s of r.suggestSplit.slice(0, 10)) line(` · ${s.text}`);
207
+ }
208
+ return;
209
+ }
210
+
211
+ case 'import': {
212
+ const file = args[0];
213
+ if (!file || !fs.existsSync(file)) { line('用法:npx feiyu import <episodes.json>'); return; }
214
+ const list = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
215
+ const r = brain.importEpisodes(ID, Array.isArray(list) ? list : list.episodes);
216
+ line(`导入了 ${r.imported} 条(跳过 ${r.skipped}),现在共 ${r.total} 条经历。`);
217
+ return;
218
+ }
219
+
220
+ case 'migrate': {
221
+ const target = args[0];
222
+ if (!target || !fs.existsSync(target)) {
223
+ line('用法:npx feiyu migrate <文件或目录> [选项]');
224
+ line('');
225
+ line(' --all 整个目录一起搬(自动认格式)');
226
+ line(' --format jsonl|days|generic 只对单个文件生效');
227
+ line(' --dry-run 只看会搬多少,不写');
228
+ line(' --delete-source 搬完把原文件改名成 .migrated(不是删除)');
229
+ line('');
230
+ line('支持的格式:');
231
+ line(' jsonl 一行一条 {"sender":"谁","text":"说了什么","time":时间戳}');
232
+ line(' days 日记式 markdown:- 某人:说了什么');
233
+ line(' generic JSON 数组');
234
+ return;
235
+ }
236
+
237
+ const flag = (f) => {
238
+ const i = args.indexOf(f);
239
+ return i >= 0 ? args[i + 1] : undefined;
240
+ };
241
+ const dryRun = args.includes('--dry-run');
242
+ const deleteSource = args.includes('--delete-source');
243
+ const all = args.includes('--all') || fs.statSync(target).isDirectory();
244
+
245
+ const sniff = (f) => {
246
+ if (/\.jsonl$/i.test(f)) return 'jsonl';
247
+ if (/\.(md|txt)$/i.test(f)) return 'days';
248
+ if (/\.json$/i.test(f)) return 'generic';
249
+ return 'jsonl';
250
+ };
251
+ const collect = (p) => {
252
+ const st = fs.statSync(p);
253
+ if (!st.isDirectory()) return [p];
254
+ const out = [];
255
+ for (const name of fs.readdirSync(p)) {
256
+ const full = path.join(p, name);
257
+ if (fs.statSync(full).isDirectory()) out.push(...collect(full));
258
+ else if (/\.(md|jsonl|json|txt)$/i.test(name) && !name.endsWith('.migrated')) out.push(full);
259
+ }
260
+ return out.sort();
261
+ };
262
+
263
+ const files = collect(target);
264
+ if (!files.length) { line('这个目录里没有 .md / .jsonl / .json 可搬。'); return; }
265
+
266
+ if (!all) {
267
+ // 单文件:沿用原来的行为
268
+ const file = files[0];
269
+ const format = flag('--format') ?? sniff(file);
270
+ const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
271
+ const r = brain.migrateMemory(ID, { text, format, dryRun });
272
+ const p = r.report;
273
+ line(`格式 ${p.format} 解析出 ${p.parsed} 条 重复 ${p.duplicated} 条 将导入 ${p.willImport} 条`);
274
+ if (p.span) line(`时间跨度 ${p.span.from} → ${p.span.to}`);
275
+ if (p.parseErrorCount) {
276
+ line(`跳过 ${p.parseErrorCount} 行:`);
277
+ for (const e of p.parseErrors.slice(0, 5)) line(` 第 ${e.line} 行 ${e.reason}`);
278
+ }
279
+ if (dryRun) { line(''); line('(dry-run,什么都没写。去掉 --dry-run 才真搬)'); return; }
280
+ line('');
281
+ line(`✔ 导入了 ${r.imported} 条,现在共 ${r.total} 条经历。`);
282
+ line(`体检:${brain.identityCheck(ID).verdict}`);
283
+ return;
284
+ }
285
+
286
+ // 全量整合
287
+ const sources = files.map((f) => ({ path: f, text: fs.readFileSync(f, 'utf8').replace(/^\uFEFF/, ''), format: sniff(f) }));
288
+ const r = brain.migrateAll(ID, sources, { dryRun, deleteSource });
289
+ const p = r.report;
290
+ line(`扫到 ${p.files} 个文件 解析出 ${p.parsed} 条 重复 ${p.duplicated} 条 将导入 ${p.willImport} 条`);
291
+ if (p.span) line(`时间跨度 ${p.span.from} → ${p.span.to}`);
292
+ if (p.errorCount) {
293
+ line(`跳过 ${p.errorCount} 处:`);
294
+ for (const e of p.errors.slice(0, 5)) line(` ${path.basename(e.path || '?')} 第 ${e.line} 行 ${e.reason}`);
295
+ }
296
+ if (dryRun) {
297
+ line('');
298
+ line('(dry-run,什么都没写)');
299
+ line('真搬:去掉 --dry-run;想连原文件一起收走,加 --delete-source(改名 .migrated,不是删)');
300
+ return;
301
+ }
302
+ line('');
303
+ line(`✔ 全量导入 ${r.imported} 条,现在共 ${r.total} 条经历。`);
304
+ if (r.compacted) line(` 容量保护:最老的 ${r.compacted} 条已压成卡片 + 归档`);
305
+ if (r.renamed.length) {
306
+ line(` 原文件已改名 ${r.renamed.length} 个:`);
307
+ for (const n of r.renamed.slice(0, 5)) line(` ${path.basename(n)}`);
308
+ }
309
+ line(`体检:${r.check.verdict}`);
310
+ line('');
311
+ line('自检:npx feiyu verify');
312
+ return;
313
+ }
314
+
315
+ case 'verify': {
316
+ const r = brain.verifyMemory(ID);
317
+ line(`经历 ${r.episodes} 条(亲历 ${r.live} / 搬来 ${r.imported}) 卡片 ${r.cards} 认识 ${r.people} 个人`);
318
+ line(`体检:${r.check.verdict}`);
319
+ line(`回忆抽检:${Math.round(r.recallRate * 100)}%(${r.recall.filter((c) => c.found).length}/${r.recall.length})`);
320
+ for (const c of r.recall) line(` ${c.found ? '✔' : '✘'} 「${c.keyword}」`);
321
+ return;
322
+ }
323
+
324
+ case 'diary': {
325
+ const sub = args[0] || 'digest';
326
+ if (sub === 'write') {
327
+ const file = args[1];
328
+ if (!file || !fs.existsSync(file)) { line('用法:npx feiyu diary write <文本文件> [YYYY-MM-DD]'); return; }
329
+ const r = brain.writeDiary(ID, { date: args[2], text: fs.readFileSync(file, 'utf8') });
330
+ if (!r.ok) { line(`✘ ${r.reason}`); return; }
331
+ line(`${r.date} 的日记存好了(${r.chars} 字)`);
332
+ line(r.file);
333
+ return;
334
+ }
335
+ if (sub === 'read') {
336
+ const r = brain.readDiary(ID, args[1]);
337
+ if (!r) { line(`${args[1] || '今天'}还没有日记。`); return; }
338
+ line(r.text);
339
+ return;
340
+ }
341
+ if (sub === 'import') {
342
+ const dir = args[1];
343
+ if (!dir || !fs.existsSync(dir)) { line('用法:npx feiyu diary import <旧的日记目录>'); return; }
344
+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
345
+ const list = [];
346
+ for (const f of files) {
347
+ const m = /(\d{4}-\d{2}-\d{2})/.exec(f);
348
+ if (!m) continue;
349
+ list.push({ date: m[1], text: fs.readFileSync(path.join(dir, f), 'utf8') });
350
+ }
351
+ const r = brain.importDiary(ID, list);
352
+ line(`认出的日记 ${list.length} 篇,导入 ${r.imported},跳过 ${r.skipped}(已存在的不覆盖)`);
353
+ line(`现在一共有 ${r.days} 天日记。`);
354
+ return;
355
+ }
356
+ if (sub === 'list') {
357
+ const list = brain.listDiary(ID);
358
+ if (!list.length) { line('还没写过日记。'); return; }
359
+ for (const d of list) line(` ${d.date} ${(d.size / 1024).toFixed(1)} KB`);
360
+ return;
361
+ }
362
+ const d = brain.diaryDigest(ID, args[1]);
363
+ line(`【${d.date} 的素材】经历 ${d.episodes} 条,见了 ${d.people.length ? d.people.join('、') : '没人'},心情 ${d.mood || '平静'}`);
364
+ line();
365
+ line(d.draft);
366
+ line();
367
+ line(`👉 ${d.hint}`);
368
+ return;
369
+ }
370
+
371
+ case 'doctor': {
372
+ const { diagnose, applyFixes, formatReport } = await import('./lib/doctor.mjs');
373
+ const profile = args[0] || 'desktop';
374
+ const report = diagnose({ profile });
375
+ line(formatReport(report));
376
+ if (args.includes('--fix')) {
377
+ line('');
378
+ const done = applyFixes(report);
379
+ if (done.length) {
380
+ for (const d of done) line(`✔ ${d}`);
381
+ line('');
382
+ line('改完了。**完全退出 DSH 再启动**(宿主需要冷启动才认新 bundles)。');
383
+ } else {
384
+ line('没有能自动修的项。');
385
+ }
386
+ } else if (!report.ok) {
387
+ line('');
388
+ line('能自动修的加 --fix:npx feiyu doctor --fix(会改 profile 的 bundles 和工具白名单)');
389
+ }
390
+ return;
391
+ }
392
+
393
+ case 'serve': {
394
+ const { serve } = await import('./lib/serve.mjs');
395
+ const flag = (f) => {
396
+ const i = args.indexOf(f);
397
+ return i >= 0 ? args[i + 1] : undefined;
398
+ };
399
+ const port = Number(flag('--port') ?? 7788);
400
+ const token = flag('--token') ?? process.env.FEIYU_TOKEN ?? '';
401
+ const host = flag('--host') ?? '127.0.0.1';
402
+ const s = await serve(brain, { port, host, token, id: ID });
403
+ line(`边车起来了:${s.url}`);
404
+ line(`鱼:${ID}  token:${token ? '已设(要求 x-feiyu-token 头)' : '没设(只允许本机)'}`);
405
+ line('');
406
+ line('Python 这么接:');
407
+ line(` requests.post('${s.url}/wake', json={'id':'${ID}','sender':who,'text':msg})`);
408
+ line('');
409
+ line('接口:GET /health /status /version /identity /verify');
410
+ line(' POST /wake /observe /feel /diary /migrate /snapshot');
411
+ line('Ctrl+C 停。');
412
+ // 常驻
413
+ await new Promise(() => {});
414
+ return;
415
+ }
416
+
417
+ case 'vocab': {
418
+ const sub = args[0] || 'show';
419
+ if (sub === 'seed') {
420
+ const r = brain.seedVocab(ID);
421
+ line(`预装了 ${r.added} 个情绪词,现在会 ${r.total} 个,阶段 ${r.stage}`);
422
+ line('(新鱼用不到;老鱼搬进来不该从"哼哼"开始)');
423
+ return;
424
+ }
425
+ const v = brain.vocabOf(ID);
426
+ line(`阶段 ${v.stage} 会 ${v.words.length} 个词`);
427
+ if (v.words.length) line(v.words.join('、'));
428
+ if (v.stage === 1) line('(词不够 10 个,只会说"说不清";老鱼可以 npx feiyu vocab seed)');
429
+ return;
430
+ }
431
+
159
432
  case 'body': {
160
433
  const kind = args[0];
161
434
  const s = brain.snapshot(ID);
@@ -186,12 +459,12 @@ function run() {
186
459
  }
187
460
 
188
461
  default:
189
- line('用法:npx feiyu [status|brief|observe|settle|audit|spread|body|rebirth]');
462
+ line('用法:npx feiyu [status|brief|observe|settle|audit|spread|body|rebirth|snapshot|restore|snapshots|lint|import|migrate|verify|diary|doctor|serve|vocab]');
190
463
  }
191
464
  }
192
465
 
193
466
  try {
194
- run();
467
+ await run();
195
468
  } catch (e) {
196
469
  if (isNoCard(e)) {
197
470
  firstRunGuide();
package/cordis.patch.yml CHANGED
@@ -13,7 +13,37 @@
13
13
  name: feiyu-brain
14
14
  config:
15
15
  brainId: default
16
- # 她的档案放哪(留空 = 包同级的 state/,或环境变量 FEIYU_DATA_DIR)
16
+
17
+ # 她的档案放哪。
18
+ # 留空 = 环境变量 FEIYU_DATA_DIR;再没有就按包位置推——
19
+ # 仓库内开发 → <仓库>/state
20
+ # 装进 node_modules → 用户目录 ~/.feiyu-brain/state(不会写进只读的包目录)
17
21
  dataDir: ""
18
- # 角色卡目录(里面放 <名字>.md;留空 = 包同级的 roles/,或 FEIYU_ROLE_DIR)
22
+
23
+ # 角色卡目录(里面放 <名字>.md)。留空规则同上,落 ~/.feiyu-brain/roles。
19
24
  roleDir: ""
25
+
26
+ # 只注册你要的工具。不写 = 全注册(8 个)。
27
+ # 例:只要脑子不要那只开 App 的手 → [status, wake, observe, tick, feel, lint]
28
+ # tools: [status, wake, observe, tick]
29
+
30
+ # 影子模式:只写审计,不动人设、不落盘。想先看"会长成什么样"再决定接不接,用它。
31
+ shadow: false
32
+
33
+ # 遗忘策略:hard(默认,两层老化)| summarize(老化时额外压卡片)| archive(同 hard)| off(永不老化)
34
+ ttlPolicy: hard
35
+
36
+ # 三段生命周期(都是「多久没人提」,不是「存了多久」):
37
+ # 完整记忆 --21 天没人提--> 记忆卡片 --2 年没人提--> 遗忘
38
+ # 卡片被提一次 +30 天;连续提 15 天 → 长期记忆(2 年)→ 到期降回卡片,重新走一圈
39
+ compressDays: 21 # 完整期
40
+ forgetDays: 730 # 卡片期 / 长期期(2 年)
41
+
42
+ # 「此刻的她」多长。老鱼可以调到 600——代价是每轮多 300 字 token。
43
+ briefChars: 300
44
+
45
+ # 脑里最多存多少条经历,超了最老的按 20 条一张卡片压扁并归档。
46
+ maxEpisodes: 5000
47
+
48
+ # 情绪双源仲裁:brain(脑说了算)| host(宿主说了算,feel 只算不写)| blend(各一半)
49
+ moodPolicy: brain
package/core/body.js CHANGED
@@ -62,7 +62,7 @@ export const DEFAULT_SCOPE = {
62
62
  * @param {'phone'|'tablet'|'desktop'} opts.kind
63
63
  * @param {'owned'|'borrowed'|'emulator'} [opts.ownership]
64
64
  */
65
- export function createBody({ kind, ownership = 'owned', apps, scope } = {}) {
65
+ export function createBody({ kind, ownership = 'owned', apps, scope, owner = 'brain' } = {}) {
66
66
  if (!BODY_KINDS.includes(kind)) {
67
67
  throw new Error(`身体只能是 ${BODY_KINDS.join(' / ')}`);
68
68
  }
@@ -70,6 +70,8 @@ export function createBody({ kind, ownership = 'owned', apps, scope } = {}) {
70
70
  return {
71
71
  kind,
72
72
  ownership,
73
+ // 谁负责真的去动这台设备:'brain'(脑自己开 App)或 'host'(宿主已有 qq_phone_device 这类工具)
74
+ owner: owner === 'host' ? 'host' : 'brain',
73
75
  label: profile.label,
74
76
  screen: profile.screen,
75
77
  posture: profile.posture,
@@ -93,6 +95,16 @@ export function canDo(body, action = {}) {
93
95
  if (!body) return { ok: false, code: 'E_NO_BODY', reason: '没有身体,想而不得' };
94
96
  if (body.online === false) return { ok: false, code: 'E_OFFLINE', reason: `${body.label}没联网` };
95
97
 
98
+ // 设备归宿主管时,脑不抢——两套都能动设备,谁先谁后必须有个约定。
99
+ // 宿主确实要脑来动手时,显式传 force:true(等于宿主当场授权)。
100
+ if (body.owner === 'host' && action.force !== true && action.type && action.type !== 'screenshot') {
101
+ return {
102
+ ok: false,
103
+ code: 'E_HOST_OWNS',
104
+ reason: '这台设备归宿主管(body.owner=host);要脑动手请显式 force:true',
105
+ };
106
+ }
107
+
96
108
  const need = action.capability ?? CAPABILITY.OPERATE;
97
109
  if (need === CAPABILITY.MONEY && !action.approved) {
98
110
  return { ok: false, code: 'E_NEED_APPROVAL', reason: '花钱要用户批准 + 支付密码' };
package/core/bond.js ADDED
@@ -0,0 +1,186 @@
1
+ // 恩情:谁对我好,是我自己算出来的。
2
+ //
3
+ // 关系契约是"焊死的":主人永远是主人,优先级 100,不可解除。
4
+ // 但人不止一种关系——隔壁那个天天来充电的人、那个会开窗的人、
5
+ // 那个只是问一句"还好吗"的人,我对他们的感觉是不一样的。
6
+ //
7
+ // 这套东西不抢主人的位置,只回答一个问题:
8
+ // **这个人,我愿不愿意理。**
9
+ //
10
+ // 判定不是写死的分数,是**人格 + 情感**算出来的:
11
+ // · 心软高 → 容易被打动,涨得快
12
+ // · 敏感高 → 一点点好都记得住
13
+ // · 嘴硬高 → 涨得慢,但涨上去就不容易掉
14
+ //
15
+ // 所以同一件照顾的事,两条鱼的反应可以完全不同。
16
+
17
+ export const BOND_TIERS = ['stranger', 'acquaintance', 'familiar', 'close', 'family'];
18
+
19
+ /** 分档门槛 */
20
+ export const BOND_TIER_MIN = {
21
+ stranger: 0,
22
+ acquaintance: 10,
23
+ familiar: 30,
24
+ close: 60,
25
+ family: 85,
26
+ };
27
+
28
+ /** 上限 99 —— **永远低于关系契约的 100**,主人的位置不会被顶掉 */
29
+ export const BOND_MAX = 99;
30
+
31
+ const DAY_MS = 86400000;
32
+
33
+ function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); }
34
+
35
+ /**
36
+ * 她对"别人的好"有多敏感 —— 由人设算,不是常数。
37
+ * @returns {number} 0.05 ~ 1
38
+ */
39
+ export function bondSensitivity(traits = {}) {
40
+ const soft = Number(traits.心软 ?? 0.5);
41
+ const sens = Number(traits.敏感 ?? 0.5);
42
+ const hard = Number(traits.嘴硬 ?? 0.5);
43
+ const warm = Number(traits.活泼 ?? 0.5);
44
+ return clamp(0.25 + 0.45 * soft + 0.25 * sens - 0.35 * hard + 0.1 * warm, 0.05, 1);
45
+ }
46
+
47
+ /**
48
+ * 一件事让她对这个人的恩情涨多少。
49
+ *
50
+ * @param {object} o
51
+ * @param {object} o.traits 人设
52
+ * @param {number} [o.base] 基础分量:照顾 8 / 普通互动 1 / 只是被看到 0.3
53
+ * @param {number} [o.valence] 这事对她好不好(负数会扣)
54
+ */
55
+ export function bondDelta({ traits = {}, base = 1, valence = 1 } = {}) {
56
+ const s = bondSensitivity(traits);
57
+ return Number((base * s * (Number(valence) || 1)).toFixed(3));
58
+ }
59
+
60
+ /** 取某个人的恩情档位 */
61
+ export function bondTier(score = 0) {
62
+ let tier = 'stranger';
63
+ for (const t of BOND_TIERS) {
64
+ if (score >= BOND_TIER_MIN[t]) tier = t;
65
+ }
66
+ return tier;
67
+ }
68
+
69
+ /** 记一笔 */
70
+ export function addBond(memory, who, { delta = 0, at = Date.now(), what = '' } = {}) {
71
+ const name = String(who ?? '').trim();
72
+ if (!name || !Number.isFinite(Number(delta)) || Number(delta) === 0) return null;
73
+ if (!memory.bonds) memory.bonds = {};
74
+ const b = memory.bonds[name] ?? { score: 0, events: [], lastAt: 0 };
75
+ b.score = clamp(Number((b.score + Number(delta)).toFixed(2)), 0, BOND_MAX);
76
+ b.events = [...(b.events ?? []), { at, delta: Number(delta), what: String(what).slice(0, 40) }].slice(-50);
77
+ b.lastAt = at;
78
+ memory.bonds[name] = b;
79
+ return b;
80
+ }
81
+
82
+ /** 看她现在怎么称呼这个人 */
83
+ export function bondOf(memory, who) {
84
+ const name = String(who ?? '').trim();
85
+ const b = memory?.bonds?.[name];
86
+ if (!b) return { who: name, score: 0, tier: 'stranger', lastAt: 0, events: 0 };
87
+ return {
88
+ who: name,
89
+ score: Number(b.score.toFixed(1)),
90
+ tier: bondTier(b.score),
91
+ lastAt: Number(b.lastAt) || 0,
92
+ events: (b.events ?? []).length,
93
+ };
94
+ }
95
+
96
+ /** 恩情长期不用会淡一点(但不会归零——人对好是有底子的) */
97
+ export function decayBonds(memory, now = Date.now(), { perDay = 0.002, floor = 5 } = {}) {
98
+ for (const [name, b] of Object.entries(memory.bonds ?? {})) {
99
+ const days = Math.max(0, (now - (Number(b.lastAt) || now)) / DAY_MS);
100
+ if (days < 1) continue;
101
+ const next = Math.max(floor, Number(b.score) * (1 - perDay * Math.min(days, 365)));
102
+ b.score = Number(next.toFixed(2));
103
+ void name;
104
+ }
105
+ }
106
+
107
+ /** 有资格被标"不在了"的最低档:真的对我好过的人 */
108
+ export const ABSENT_MIN_TIER = 'close';
109
+
110
+ /**
111
+ * 给一个恩情够深的人标缺位。
112
+ *
113
+ * 为什么不是谁都能标:十五年擦灰、二十年晒太阳,才配得上"我记住他不在了"。
114
+ * 擦过一次灰的人走了,那是"没来",不是"不在了"。
115
+ *
116
+ * @returns {{ok:boolean, reason?:string, absence?:object}}
117
+ */
118
+ export function markBondAbsent(memory, who, { since = Date.now(), note = '', status = 'absent' } = {}) {
119
+ const name = String(who ?? '').trim();
120
+ if (!name) return { ok: false, reason: '没说谁' };
121
+ const b = bondOf(memory, name);
122
+ const rank = BOND_TIERS.indexOf(b.tier);
123
+ const need = BOND_TIERS.indexOf(ABSENT_MIN_TIER);
124
+ if (rank < need) {
125
+ return { ok: false, reason: `恩情还不够(${b.tier} ${b.score} < ${ABSENT_MIN_TIER})——那是"没来",不是"不在了"` };
126
+ }
127
+ if (!memory.absences) memory.absences = {};
128
+ const prev = memory.absences[name];
129
+ memory.absences[name] = {
130
+ who: name,
131
+ since: Number(prev?.since) || since,
132
+ note: String(note ?? prev?.note ?? '').slice(0, 60),
133
+ status,
134
+ at: Date.now(),
135
+ };
136
+ // 人物伞改词,但不删
137
+ for (const u of memory.umbrellas ?? []) {
138
+ if (u.topic === 'person' && u.who === name) {
139
+ u.absent = true;
140
+ u.text = `${name}:曾经一直在的人`;
141
+ }
142
+ }
143
+ // 纲里的措辞也跟上
144
+ for (const g of memory.gists ?? []) {
145
+ if (g.topic === 'person' && g.who === name) g.absent = true;
146
+ }
147
+ return { ok: true, absence: memory.absences[name], bond: b };
148
+ }
149
+
150
+ export function clearBondAbsent(memory, who) {
151
+ const name = String(who ?? '').trim();
152
+ if (memory.absences) delete memory.absences[name];
153
+ for (const u of memory.umbrellas ?? []) {
154
+ if (u.topic === 'person' && u.who === name && u.absent) {
155
+ u.absent = false;
156
+ u.text = `${name}:一直在的人`;
157
+ }
158
+ }
159
+ for (const g of memory.gists ?? []) {
160
+ if (g.topic === 'person' && g.who === name) g.absent = false;
161
+ }
162
+ return { ok: true, who: name };
163
+ }
164
+
165
+ export function bondAbsentOf(memory, who) {
166
+ return memory?.absences?.[String(who ?? '').trim()] ?? null;
167
+ }
168
+
169
+ /** 她心里对这个人的一句话(知道了"不在了"之后会换说法) */
170
+ export function bondLine(memory, who, { now = Date.now() } = {}) {
171
+ const b = bondOf(memory, who);
172
+ if (b.tier === 'stranger') return '';
173
+ const dead = bondAbsentOf(memory, who);
174
+ const days = b.lastAt ? Math.floor((now - b.lastAt) / DAY_MS) : 0;
175
+ const label = {
176
+ acquaintance: '算不上熟',
177
+ familiar: '算个熟人',
178
+ close: '对我挺好的',
179
+ family: '跟家里人一样',
180
+ }[b.tier] ?? '';
181
+ if (dead) {
182
+ const d = dead.since ? Math.floor((now - Number(dead.since)) / DAY_MS) : 0;
183
+ return `${b.who}:${label},${dead.note || '已经不在了'}${d > 0 ? `(${d} 天)` : ''}`;
184
+ }
185
+ return days > 180 ? `${b.who}:${label},但很久没来了` : `${b.who}:${label}`;
186
+ }