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/selftest.mjs CHANGED
@@ -101,13 +101,47 @@ t('蜕皮后 memory.formerSelves 里查得到', () => {
101
101
  });
102
102
 
103
103
  console.log('\n── 记忆 ──');
104
- t('TTL 30 天到期进 forgotten', () => {
105
- const m = { episodes: [{ id: 'a', kind: 'episode', lastRecall: Date.now() - 31 * 86400000, consecutiveDays: 1, longTerm: false }], imagination: [], facts: {}, impressions: {}, forgotten: [] };
106
- settle(m);
104
+ t('30 天没人提 → 压扁成一句"大概"(不是删除)', () => {
105
+ const now = Date.now();
106
+ const m = {
107
+ episodes: [{ id: 'a', kind: 'episode', who: '扶摇', what: '你嘴真硬', at: now - 31 * 86400000, lastRecall: now - 31 * 86400000, consecutiveDays: 1, longTerm: false }],
108
+ imagination: [], facts: {}, impressions: {}, forgotten: [], cards: [],
109
+ };
110
+ settle(m, now);
111
+ assert.equal(m.episodes.length, 1, '不该被删掉');
112
+ assert.equal(m.episodes[0].compressed, true);
113
+ assert.ok(m.episodes[0].what.includes('记不清'), m.episodes[0].what);
114
+ assert.equal(m.forgotten.length, 0);
115
+ });
116
+
117
+ t('2 年没人提 → 才真的遗忘', () => {
118
+ const now = Date.now();
119
+ const DAY = 86400000;
120
+ const m = {
121
+ episodes: [{
122
+ id: 'a', kind: 'episode', who: '扶摇', what: '两年前的事',
123
+ at: now - 800 * DAY, lastRecall: now - 800 * DAY,
124
+ compressed: true, cardedAt: now - 800 * DAY, expiresAt: now - 70 * DAY,
125
+ consecutiveDays: 1, longTerm: false,
126
+ }],
127
+ imagination: [], facts: {}, impressions: {}, forgotten: [], cards: [],
128
+ };
129
+ settle(m, now);
107
130
  assert.equal(m.episodes.length, 0);
108
131
  assert.equal(m.forgotten.length, 1);
109
132
  });
110
133
 
134
+ t('一直被提起 → 压不了也忘不了', () => {
135
+ const now = Date.now();
136
+ const m = {
137
+ episodes: [{ id: 'a', kind: 'episode', what: '常聊的事', at: now - 500 * 86400000, lastRecall: now, consecutiveDays: 20, longTerm: false }],
138
+ imagination: [], facts: {}, impressions: {}, forgotten: [], cards: [],
139
+ };
140
+ settle(m, now);
141
+ assert.equal(m.episodes.length, 1);
142
+ assert.ok(!m.episodes[0].compressed, '不该被压扁');
143
+ });
144
+
111
145
  t('连续 15 天升级长期,永不衰减', () => {
112
146
  const m = { episodes: [{ id: 'b', kind: 'episode', lastRecall: Date.now() - 400 * 86400000, consecutiveDays: PROMOTE_DAYS, longTerm: true }], imagination: [], facts: {}, impressions: {}, forgotten: [] };
113
147
  settle(m);
package/store.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // 落盘:<dataDir>/brains/<id>/ 下的一组 JSON。
2
2
  //
3
3
  // 发布成包之后,路径不能写死到仓库里——宿主可能是任意目录。
4
- // 优先级:setDataDir() > 环境变量 FEIYU_DATA_DIR > 包所在仓库的 state/
4
+ // 优先级:setDataDir() > 环境变量 FEIYU_DATA_DIR > 用户目录(装进 node_modules 时)> 仓库 state/
5
5
 
6
6
  import fs from 'node:fs';
7
+ import os from 'node:os';
7
8
  import path from 'node:path';
8
9
  import { fileURLToPath } from 'node:url';
9
10
 
@@ -12,13 +13,29 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
12
13
  /** 包所在仓库根(老用法:桥接同目录)。发布后可能指向 node_modules,只作兜底。 */
13
14
  export const ROOT = path.resolve(HERE, '..', '..');
14
15
 
16
+ /**
17
+ * 装进 node_modules 时,ROOT 会指到 node_modules 里面——
18
+ * 数据写进去等于:升级/重装就丢,而且常常是只读。
19
+ * 这时改用用户目录。仓库内开发(不在 node_modules 里)保持原行为。
20
+ */
21
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/.test(ROOT);
22
+ const USER_FALLBACK = path.join(os.homedir(), '.feiyu-brain');
23
+
24
+ function defaultDataRoot() {
25
+ return IN_NODE_MODULES ? path.join(USER_FALLBACK, 'state') : path.join(ROOT, 'state');
26
+ }
27
+
28
+ function defaultRoleRoot() {
29
+ return IN_NODE_MODULES ? path.join(USER_FALLBACK, 'roles') : path.join(ROOT, 'roles');
30
+ }
31
+
15
32
  let dataRoot = process.env.FEIYU_DATA_DIR
16
33
  ? path.resolve(process.env.FEIYU_DATA_DIR)
17
- : path.join(ROOT, 'state');
34
+ : defaultDataRoot();
18
35
 
19
36
  let roleRoot = process.env.FEIYU_ROLE_DIR
20
37
  ? path.resolve(process.env.FEIYU_ROLE_DIR)
21
- : path.join(ROOT, 'roles');
38
+ : defaultRoleRoot();
22
39
 
23
40
  /** 宿主指定数据目录(推荐显式设置,别依赖包位置)。 */
24
41
  export function setDataDir(dir) {
@@ -29,6 +46,17 @@ export function dataDir() {
29
46
  return dataRoot;
30
47
  }
31
48
 
49
+ /** 数据目录是从哪来的:env / explicit / default */
50
+ export function dataDirSource() {
51
+ if (process.env.FEIYU_DATA_DIR) return 'env:FEIYU_DATA_DIR';
52
+ return IN_NODE_MODULES ? 'default:user-home' : 'default:repo';
53
+ }
54
+
55
+ /** 装进 node_modules 且在写包里——这是要报警的情况 */
56
+ export function isDataDirInsidePackage() {
57
+ return IN_NODE_MODULES && dataRoot.startsWith(ROOT + path.sep);
58
+ }
59
+
32
60
  /** 宿主指定角色卡目录(roles/<名字>.md)。 */
33
61
  export function setRoleDir(dir) {
34
62
  roleRoot = path.resolve(dir);
@@ -73,7 +101,70 @@ export function readJson(file, fallback = null) {
73
101
  }
74
102
  }
75
103
 
76
- /** 原子写:先写临时文件再 rename,避免半截文件。 */
104
+ /* ── 按年分片存 ───────────────────────────────────────────────
105
+ *
106
+ * brain.json 只放"她是谁"(人设/情绪/关系/卡片…),**不放经历**。
107
+ * 经历按年落进 brains/<id>/years/2026.jsonl。
108
+ *
109
+ * 为什么:一条活 16 年的鱼会有 1.7 万条经历,全塞一个 json 里
110
+ * 打开一次要解析几百 KB,越活越慢。分片 + 按窗口懒加载才是长期解。
111
+ */
112
+
113
+ const DAY = 24 * 60 * 60 * 1000;
114
+ let episodeWindowDays = 730; // 打开时加载最近多少天的经历
115
+
116
+ export function setEpisodeWindow(days) {
117
+ const n = Number(days);
118
+ if (Number.isFinite(n) && n > 0) episodeWindowDays = Math.floor(n);
119
+ }
120
+
121
+ export function episodeWindow() {
122
+ return episodeWindowDays;
123
+ }
124
+
125
+ export function yearsDir(id) {
126
+ return path.join(brainDir(id), 'years');
127
+ }
128
+
129
+ export function yearFile(id, year) {
130
+ return path.join(yearsDir(id), `${year}.jsonl`);
131
+ }
132
+
133
+ function yearOf(ms) {
134
+ return new Date(Number(ms) || Date.now()).getFullYear();
135
+ }
136
+
137
+ /** 把一个年份的经历写成 jsonl(整年重写:一年最多一千多条,可接受) */
138
+ function writeYearShard(id, year, list) {
139
+ ensureDir(yearsDir(id));
140
+ const file = yearFile(id, year);
141
+ if (!list.length) {
142
+ try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch { /* 删不掉也无所谓 */ }
143
+ return null;
144
+ }
145
+ const body = `${list.map((e) => JSON.stringify(e)).join('\n')}\n`;
146
+ const tmp = `${file}.${process.pid}.tmp`;
147
+ fs.writeFileSync(tmp, body, 'utf8');
148
+ fs.renameSync(tmp, file);
149
+ const ats = list.map((e) => Number(e.at) || 0).filter(Boolean);
150
+ return {
151
+ count: list.length,
152
+ from: ats.length ? Math.min(...ats) : 0,
153
+ to: ats.length ? Math.max(...ats) : 0,
154
+ };
155
+ }
156
+
157
+ function readYearShard(id, year) {
158
+ const file = yearFile(id, year);
159
+ if (!fs.existsSync(file)) return [];
160
+ const out = [];
161
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
162
+ const s = line.trim();
163
+ if (!s) continue;
164
+ try { out.push(JSON.parse(s)); } catch { /* 坏行跳过,不整年报废 */ }
165
+ }
166
+ return out;
167
+ }
77
168
  export function writeJsonAtomic(file, data) {
78
169
  ensureDir(path.dirname(file));
79
170
  const tmp = `${file}.${process.pid}.tmp`;
@@ -105,15 +196,46 @@ export function listBrains() {
105
196
 
106
197
  export function loadBrain(id) {
107
198
  const file = brainFile(id);
108
- const main = readJson(file, null);
109
- if (main) return main;
110
- // 主文件坏了就退到备份——评审说得对,单文件损坏不该等于丢档
111
- const bak = readJson(`${file}.bak`, null);
112
- if (bak) {
113
- try { writeJsonAtomic(file, bak); } catch { /* 修不回来也不影响这次读 */ }
114
- return bak;
199
+ let main = readJson(file, null);
200
+ if (!main) {
201
+ // 主文件坏了就退到备份——单文件损坏不该等于丢档
202
+ const bak = readJson(`${file}.bak`, null);
203
+ if (bak) {
204
+ main = bak;
205
+ try { writeJsonAtomic(file, bak); } catch { /* 修不回来也不影响这次读 */ }
206
+ }
207
+ }
208
+ if (!main) return null;
209
+
210
+ // ── 把窗口内的年份读回内存(更早的留在磁盘上,不加载)──
211
+ main.memory = main.memory ?? {};
212
+ const shards = main.memory.shards ?? {};
213
+ const cutoff = Date.now() - episodeWindowDays * DAY;
214
+ const eps = [];
215
+ for (const [y, meta] of Object.entries(shards)) {
216
+ const to = Number(meta?.to) || 0;
217
+ if (to && to < cutoff) continue; // 太老的年份:不加载
218
+ eps.push(...readYearShard(id, Number(y)));
115
219
  }
116
- return null;
220
+ // 防御:万一旧版本留下的 brain.json 里还有 episodes,也并进来
221
+ if (Array.isArray(main.memory.episodes) && main.memory.episodes.length) {
222
+ eps.push(...main.memory.episodes);
223
+ }
224
+ main.memory.episodes = eps.sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
225
+ return main;
226
+ }
227
+
228
+ /** 显式读某一年(翻旧账用) */
229
+ export function readYear(id, year) {
230
+ return readYearShard(id, Number(year));
231
+ }
232
+
233
+ /** 她有哪些年份的经历 */
234
+ export function listYears(id) {
235
+ const main = readJson(brainFile(id), null);
236
+ return Object.entries(main?.memory?.shards ?? {})
237
+ .map(([year, meta]) => ({ year: Number(year), ...meta }))
238
+ .sort((a, b) => a.year - b.year);
117
239
  }
118
240
 
119
241
  export function saveBrain(brain) {
@@ -121,6 +243,43 @@ export function saveBrain(brain) {
121
243
  try {
122
244
  if (fs.existsSync(file)) fs.copyFileSync(file, `${file}.bak`);
123
245
  } catch { /* 备份失败不影响写入 */ }
124
- writeJsonAtomic(file, brain);
246
+
247
+ // ── 经历按年分片,不进 brain.json ──
248
+ const eps = Array.isArray(brain.memory?.episodes) ? brain.memory.episodes : [];
249
+ const byYear = new Map();
250
+ for (const e of eps) {
251
+ const y = yearOf(e.at);
252
+ if (!byYear.has(y)) byYear.set(y, []);
253
+ byYear.get(y).push(e);
254
+ }
255
+
256
+ const shards = {};
257
+ for (const [y, list] of byYear) {
258
+ const meta = writeYearShard(brain.id, y, list);
259
+ if (meta) shards[y] = meta;
260
+ }
261
+ // 这一年被清空了(忘光了/搬家后没剩)→ 把文件删掉
262
+ try {
263
+ const dir = yearsDir(brain.id);
264
+ if (fs.existsSync(dir)) {
265
+ for (const f of fs.readdirSync(dir)) {
266
+ const y = Number(f.replace(/\.jsonl$/, ''));
267
+ if (Number.isFinite(y) && !shards[y]) {
268
+ try { fs.unlinkSync(path.join(dir, f)); } catch { /* 忽略 */ }
269
+ }
270
+ }
271
+ }
272
+ } catch { /* 读不到目录就算了 */ }
273
+
274
+ const out = {
275
+ ...brain,
276
+ memory: { ...(brain.memory ?? {}), shards },
277
+ };
278
+ delete out.memory.episodes; // 经历在 years/*.jsonl
279
+ delete out.memory.shards?.episodes; // 防御
280
+
281
+ writeJsonAtomic(file, out);
282
+ brain.memory = brain.memory ?? {};
283
+ brain.memory.shards = shards; // 内存对象保持一致
125
284
  return brain;
126
285
  }