dsh-folia 1.1.0 → 1.3.0

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.
@@ -0,0 +1,835 @@
1
+ /**
2
+ * memory-db.js — 长期记忆 v2(SQLite + FTS5 + 衰减 + 关系 + 世界书)。
3
+ *
4
+ * 为什么是 node:sqlite:宿主 Node ≥22.12 自带 `node:sqlite`(本机实测 SQLite 3.50.4、
5
+ * FTS5 可用),因此**不需要**新增 better-sqlite3 这类原生依赖 —— 这正是任务书的硬约束。
6
+ *
7
+ * 每个人设一个库:`<persona>/memory/memory.db`(由 personaDir 决定根目录)。
8
+ *
9
+ * 表:
10
+ * events(id, persona_id, kind, text, importance 1-10, created_at, last_used_at,
11
+ * strength, pinned 0/1, source, tags, archived, embedding, vector_source)
12
+ * events_fts(text) -- FTS5 contentless_delete(存 bigram 分词后的索引串)
13
+ * relations(persona_id, entity, affinity -10..10, notes, updated_at)
14
+ * lore(id, persona_id, title, content, chunk_no, source, created_at)
15
+ * lore_fts(text)
16
+ * summaries(persona_id, period, text, created_at)
17
+ * meta(key, value)
18
+ *
19
+ * 中文为什么不是直接用 unicode61:FTS5 的默认分词器把连续中文当成**一个 token**,
20
+ * “咖啡”查不到“我喜欢喝咖啡”。所以入库前用与查询同一套 `tokenizeForIndex()` 做
21
+ * bigram 预分词(英文按词、中文按双字),索引串存进 events_fts —— BM25 排序照旧由
22
+ * SQLite 算。这是**明确的取舍**,写在迁移说明里,不假装是原生中文分词。
23
+ *
24
+ * 向量:有注入的 `embedder` 才写 embedding(列里同时记 vector_source='onnx' 或 'js-ngram');
25
+ * 没有 embedder 时用 JS 字符 n-gram 余弦做**排序补偿**,但不写 embedding 列 ——
26
+ * 不把“JS 兜底”冒充成 ONNX 向量。
27
+ *
28
+ * 所有 API 都是**同步**的(DatabaseSync 本身就同步);路由里调用不会卡事件循环太久
29
+ * (单库操作都是毫秒级,FTS 检索 top-8)。
30
+ */
31
+ import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
32
+ import { createRequire } from 'node:module';
33
+ import { dirname, join } from 'node:path';
34
+ import { personaDir } from './persona-store.js';
35
+
36
+ const require = createRequire(import.meta.url);
37
+
38
+ /** 与 persona-memory 的预算口径保持一致(1200 字 ≈ 800 token)。 */
39
+ export const MEMORY_DB_BUDGET = Object.freeze({
40
+ topK: 8,
41
+ budgetChars: 1200,
42
+ tokenBudget: 800,
43
+ recencyHalfLifeDays: 30,
44
+ archiveBelow: 0.05,
45
+ maxEventChars: 4000,
46
+ });
47
+
48
+ const SCHEMA = `
49
+ CREATE TABLE IF NOT EXISTS events(
50
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ persona_id TEXT NOT NULL,
52
+ kind TEXT NOT NULL DEFAULT 'event',
53
+ text TEXT NOT NULL,
54
+ importance INTEGER NOT NULL DEFAULT 5,
55
+ created_at INTEGER NOT NULL,
56
+ last_used_at INTEGER,
57
+ strength REAL NOT NULL DEFAULT 5,
58
+ pinned INTEGER NOT NULL DEFAULT 0,
59
+ source TEXT NOT NULL DEFAULT '',
60
+ tags TEXT NOT NULL DEFAULT '',
61
+ archived INTEGER NOT NULL DEFAULT 0,
62
+ embedding TEXT,
63
+ vector_source TEXT
64
+ );
65
+ CREATE INDEX IF NOT EXISTS idx_events_persona ON events(persona_id, created_at DESC);
66
+ CREATE INDEX IF NOT EXISTS idx_events_archived ON events(persona_id, archived);
67
+ CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(text, content='', contentless_delete=1);
68
+ CREATE TABLE IF NOT EXISTS relations(
69
+ persona_id TEXT NOT NULL,
70
+ entity TEXT NOT NULL,
71
+ affinity INTEGER NOT NULL DEFAULT 0,
72
+ notes TEXT NOT NULL DEFAULT '',
73
+ updated_at INTEGER NOT NULL,
74
+ PRIMARY KEY(persona_id, entity)
75
+ );
76
+ CREATE TABLE IF NOT EXISTS lore(
77
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
78
+ persona_id TEXT NOT NULL,
79
+ title TEXT NOT NULL DEFAULT '',
80
+ content TEXT NOT NULL,
81
+ chunk_no INTEGER NOT NULL DEFAULT 0,
82
+ source TEXT NOT NULL DEFAULT '',
83
+ created_at INTEGER NOT NULL
84
+ );
85
+ CREATE INDEX IF NOT EXISTS idx_lore_persona ON lore(persona_id, chunk_no);
86
+ CREATE VIRTUAL TABLE IF NOT EXISTS lore_fts USING fts5(text, content='', contentless_delete=1);
87
+ CREATE TABLE IF NOT EXISTS summaries(
88
+ persona_id TEXT NOT NULL,
89
+ period TEXT NOT NULL,
90
+ text TEXT NOT NULL,
91
+ created_at INTEGER NOT NULL,
92
+ PRIMARY KEY(persona_id, period)
93
+ );
94
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
95
+ `;
96
+
97
+ /* ── 可用性 / 路径 ───────────────────────────────────────────────────────── */
98
+
99
+ let sqliteModule;
100
+ let sqliteLoadError = '';
101
+ /** node:sqlite 是否可用(进程内缓存;失败原因只在诊断里出现一次)。 */
102
+ export function memoryDbAvailable() {
103
+ if (sqliteModule !== undefined) return Boolean(sqliteModule);
104
+ if (process.env.FOLIA_MEMORY_DB === '0' || process.env.FOLIA_MEMORY_DB === 'off') {
105
+ sqliteModule = null;
106
+ sqliteLoadError = 'disabled-by-env';
107
+ return false;
108
+ }
109
+ try {
110
+ // node:sqlite 是内置模块,createRequire 在 ESM 里也稳。
111
+ // 用 require 而不是顶层 import,保证「不可用 ⇒ 回退 JSONL」不会在模块加载期炸掉宿主。
112
+ sqliteModule = require('node:sqlite');
113
+ } catch (error) {
114
+ sqliteModule = null;
115
+ sqliteLoadError = String((error && error.message) || error);
116
+ }
117
+ return Boolean(sqliteModule);
118
+ }
119
+
120
+ /** `<persona>/memory/memory.db`;personaId 由 personaDir 负责清洗。 */
121
+ export function memoryDbPath(personaId) {
122
+ return join(personaDir(personaId), 'memory', 'memory.db');
123
+ }
124
+
125
+ /* ── 分词 / 估价 ─────────────────────────────────────────────────────────── */
126
+
127
+ /** 中文 bigram + 英文/数字词:入库与查询共用,保证两边口径一致。 */
128
+ export function tokenizeForIndex(text) {
129
+ const raw = String(text == null ? '' : text).toLowerCase();
130
+ const tokens = [];
131
+ for (const word of raw.match(/[a-z0-9]{2,}/g) || []) tokens.push(word);
132
+ const cjk = raw.replace(/[^\u4e00-\u9fff]/g, '');
133
+ for (let i = 0; i < cjk.length; i += 1) {
134
+ if (i + 1 < cjk.length) tokens.push(cjk.slice(i, i + 2));
135
+ }
136
+ // 单个汉字也要能命中(否则「猫」这类一字查询只能走 LIKE 兜底)
137
+ for (const ch of new Set(cjk)) tokens.push(ch);
138
+ return [...new Set(tokens)];
139
+ }
140
+
141
+ /** 检索报价:中文 1.5 字/token、英文词 1.3(与 persona-memory 同口径)。 */
142
+ export function estimateMemoryTokens(text) {
143
+ const raw = String(text || '');
144
+ const cjk = (raw.match(/[\u4e00-\u9fff]/g) || []).length;
145
+ const words = (raw.match(/[a-zA-Z0-9]+/g) || []).length;
146
+ return Math.ceil(cjk / 1.5 + words * 1.3 + Math.max(0, raw.length - cjk) * 0.05);
147
+ }
148
+
149
+ const clip = (value, max) => {
150
+ const chars = [...String(value == null ? '' : value)];
151
+ return chars.length > max ? chars.slice(0, max).join('') : chars.join('');
152
+ };
153
+
154
+ /** 字符 n-gram 余弦(没有 ONNX 时的兜底排序信号;不写库、不冒充向量)。 */
155
+ export function ngramCosine(a, b, n = 2) {
156
+ const grams = (text) => {
157
+ const raw = String(text || '').toLowerCase().replace(/\s+/g, '');
158
+ const map = new Map();
159
+ for (let i = 0; i < raw.length; i += 1) {
160
+ const gram = raw.slice(i, i + n);
161
+ if (gram.length < n) continue;
162
+ map.set(gram, (map.get(gram) || 0) + 1);
163
+ }
164
+ return map;
165
+ };
166
+ const left = grams(a);
167
+ const right = grams(b);
168
+ if (!left.size || !right.size) return 0;
169
+ let dot = 0;
170
+ let la = 0;
171
+ let lb = 0;
172
+ for (const value of left.values()) la += value * value;
173
+ for (const value of right.values()) lb += value * value;
174
+ for (const [gram, value] of left) {
175
+ const other = right.get(gram);
176
+ if (other) dot += value * other;
177
+ }
178
+ const denom = Math.sqrt(la) * Math.sqrt(lb);
179
+ return denom ? dot / denom : 0;
180
+ }
181
+
182
+ /* ── 连接管理 ───────────────────────────────────────────────────────────── */
183
+
184
+ /**
185
+ * **每次操作开一个连接、用完就关**(有意为之):
186
+ * · Windows 上打开的文件句柄会阻止 `rmSync` 删人设目录(`deletePersona` / `clearEvents`
187
+ * 都是整目录删除),长连接会让“删除人设”静默失败;
188
+ * · 单次 open 是亚毫秒级,聊天一轮只有个位数操作,不值得为它引入连接生命周期管理。
189
+ */
190
+ function openDb(personaId) {
191
+ const file = memoryDbPath(personaId);
192
+ if (!memoryDbAvailable()) {
193
+ throw Object.assign(new Error('memory-db-unavailable: ' + (sqliteLoadError || 'no node:sqlite')), { code: 'unavailable' });
194
+ }
195
+ mkdirSync(dirname(file), { recursive: true });
196
+ const db = new sqliteModule.DatabaseSync(file);
197
+ db.exec('PRAGMA journal_mode = WAL;');
198
+ db.exec('PRAGMA synchronous = NORMAL;');
199
+ db.exec('PRAGMA busy_timeout = 4000;');
200
+ db.exec(SCHEMA);
201
+ return db;
202
+ }
203
+
204
+ /** 判据/诊断用:当前没有常驻连接(连接按次打开、按次关闭)。 */
205
+ function withDb(personaId, fn) {
206
+ const db = openDb(personaId);
207
+ try {
208
+ return fn(db);
209
+ } finally {
210
+ try { db.close(); } catch { /* ignore */ }
211
+ }
212
+ }
213
+
214
+ /* ── 事件 ───────────────────────────────────────────────────────────────── */
215
+
216
+ /**
217
+ * 写一条事件。字段与 JSONL 时代兼容(ts ↔ created_at)。
218
+ * @returns {{id:number, ts:number, kind:string, text:string, importance:number, pinned:boolean, personaId:string}}
219
+ */
220
+ export function addEvent(personaId, raw = {}) {
221
+ const text = clip(raw.text, MEMORY_DB_BUDGET.maxEventChars).trim();
222
+ if (!text) throw Object.assign(new Error('bad-event'), { code: 'bad-event' });
223
+ const kind = ['chat', 'action', 'preference', 'event', 'observation', 'lore', 'treehole'].includes(String(raw.kind))
224
+ ? String(raw.kind) : 'event';
225
+ const importance = Math.max(1, Math.min(10, Math.round(Number(raw.importance) || 5)));
226
+ const ts = Number(raw.ts ?? raw.created_at) || Date.now();
227
+ const pinned = raw.pinned === true ? 1 : 0;
228
+ const source = clip(raw.source || '', 40);
229
+ const tags = Array.isArray(raw.tags) ? raw.tags.map((tag) => clip(tag, 20)).filter(Boolean).join(',') : clip(raw.tags || '', 120);
230
+ // strength 的语义是“衰减时间尺度(天)”:importance 越高忘得越慢;pinned 永不衰减。
231
+ const strength = Math.max(1, Number(raw.strength) || importance * 3);
232
+ const embedding = raw.embedding ? JSON.stringify(raw.embedding) : null;
233
+ const vectorSource = embedding ? clip(raw.vectorSource || 'js-ngram', 20) : null;
234
+ return withDb(personaId, (db) => {
235
+ const info = db.prepare(`INSERT INTO events
236
+ (persona_id, kind, text, importance, created_at, last_used_at, strength, pinned, source, tags, archived, embedding, vector_source)
237
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`)
238
+ .run(String(personaId), kind, text, importance, ts, ts, strength, pinned, source, tags, embedding, vectorSource);
239
+ const id = Number(info.lastInsertRowid);
240
+ db.prepare('INSERT INTO events_fts(rowid, text) VALUES (?, ?)')
241
+ .run(id, tokenizeForIndex(text).join(' '));
242
+ return { id, ts, kind, text, importance, pinned: pinned === 1, personaId: String(personaId), source, tags };
243
+ });
244
+ }
245
+
246
+ /** 单条事件(内部用)。 */
247
+ function eventRowToItem(row) {
248
+ return {
249
+ id: Number(row.id),
250
+ ts: Number(row.created_at),
251
+ kind: row.kind,
252
+ text: row.text,
253
+ importance: Number(row.importance),
254
+ pinned: row.pinned === 1,
255
+ source: row.source || '',
256
+ tags: row.tags || '',
257
+ archived: row.archived === 1,
258
+ strength: Number(row.strength) || 1,
259
+ lastUsedAt: Number(row.last_used_at) || 0,
260
+ personaId: row.persona_id,
261
+ };
262
+ }
263
+
264
+ /** FTS5 查询串:tokens 用 OR 连接(中文 bigram 已在两侧统一)。 */
265
+ function ftsQueryFor(query) {
266
+ const tokens = tokenizeForIndex(query);
267
+ if (!tokens.length) return '';
268
+ return tokens.slice(0, 24).map((token) => '"' + token.replace(/"/g, '""') + '"').join(' OR ');
269
+ }
270
+
271
+ /** 命中条数(诊断用)。 */
272
+ export function eventsCount(personaId) {
273
+ return withDb(personaId, (db) => Number(db.prepare('SELECT COUNT(*) AS n FROM events WHERE persona_id = ?').get(String(personaId)).n) || 0);
274
+ }
275
+
276
+ /**
277
+ * FTS5 + bm25 检索(只检索,不做预算/衰减排序 —— 那是 retrieve 的事)。
278
+ * 没有命中时返回空数组;query 为空返回最近事件。
279
+ */
280
+ export function search(personaId, query, options = {}) {
281
+ const limit = Math.max(1, Math.min(50, Number(options.limit) || 8));
282
+ const match = ftsQueryFor(query);
283
+ return withDb(personaId, (db) => {
284
+ if (!match) {
285
+ const rows = db.prepare(`SELECT * FROM events WHERE persona_id = ? AND archived = 0
286
+ ORDER BY created_at DESC LIMIT ?`).all(String(personaId), limit);
287
+ return rows.map(eventRowToItem);
288
+ }
289
+ let rows = [];
290
+ try {
291
+ rows = db.prepare(`SELECT e.*, bm25(events_fts) AS rank FROM events_fts
292
+ JOIN events e ON e.id = events_fts.rowid
293
+ WHERE events_fts MATCH ? AND e.persona_id = ? AND e.archived = 0
294
+ ORDER BY rank LIMIT ?`).all(match, String(personaId), limit);
295
+ } catch {
296
+ rows = [];
297
+ }
298
+ if (!rows.length) {
299
+ // 一字/生僻查询的兜底:LIKE(仍受 limit 限制,不扫全库返回)
300
+ const like = '%' + String(query).trim().slice(0, 40) + '%';
301
+ rows = db.prepare(`SELECT * FROM events WHERE persona_id = ? AND archived = 0 AND text LIKE ?
302
+ ORDER BY created_at DESC LIMIT ?`).all(String(personaId), like, limit);
303
+ }
304
+ return rows.map((row) => ({ ...eventRowToItem(row), rank: row.rank === undefined ? null : Number(row.rank) }));
305
+ });
306
+ }
307
+
308
+ /**
309
+ * 混合召回:FTS5 + recency(半衰期 30 天)+ importance + 衰减保留度;预算 1200 字 / top-8。
310
+ * @returns {{items:Array, tokens:number, chars:number, total:number, usedFts:boolean}}
311
+ */
312
+ export function retrieve(personaId, options = {}) {
313
+ const now = Number(options.now) || Date.now();
314
+ const topK = Math.max(1, Math.min(20, Number(options.topK) || MEMORY_DB_BUDGET.topK));
315
+ const budgetChars = Math.max(80, Number(options.budgetChars) || MEMORY_DB_BUDGET.budgetChars);
316
+ const query = String(options.query || '');
317
+ return withDb(personaId, (db) => {
318
+ const total = Number(db.prepare('SELECT COUNT(*) AS n FROM events WHERE persona_id = ? AND archived = 0').get(String(personaId)).n) || 0;
319
+ if (!total) return { items: [], tokens: 0, chars: 0, total: 0, usedFts: false };
320
+ const match = ftsQueryFor(query);
321
+ /**
322
+ * **混合候选池**(不是「FTS 命中就只看 FTS」):
323
+ * FTS top-60 ∪ 最近 60 条 ∪ 全部 pinned(最多 30)。
324
+ * 为什么必须并集:用户上一句刚说“记住我喜欢原神”,下一句问“今天桌面有点乱”时 FTS
325
+ * 只会命中一两条无关事件 —— 若此时不回看最近事件,pinned 偏好就被挤掉,人设立刻失忆。
326
+ * 这是 v1.2 实测到的真实缺陷(verify-pet-chat B①)。
327
+ */
328
+ const byId = new Map();
329
+ const addRows = (list) => {
330
+ for (const row of list) {
331
+ const key = Number(row.id);
332
+ if (!byId.has(key)) byId.set(key, row);
333
+ else if (row.rank !== undefined && byId.get(key).rank === undefined) byId.set(key, row);
334
+ }
335
+ };
336
+ if (match) {
337
+ try {
338
+ addRows(db.prepare(`SELECT e.*, bm25(events_fts) AS rank FROM events_fts
339
+ JOIN events e ON e.id = events_fts.rowid
340
+ WHERE events_fts MATCH ? AND e.persona_id = ? AND e.archived = 0
341
+ ORDER BY rank LIMIT 60`).all(match, String(personaId)));
342
+ } catch { /* FTS 语法/索引问题 ⇒ 只用最近事件兜底 */ }
343
+ }
344
+ addRows(db.prepare(`SELECT * FROM events WHERE persona_id = ? AND archived = 0
345
+ ORDER BY created_at DESC LIMIT 60`).all(String(personaId)));
346
+ addRows(db.prepare(`SELECT * FROM events WHERE persona_id = ? AND pinned = 1 AND archived = 0
347
+ ORDER BY created_at DESC LIMIT 30`).all(String(personaId)));
348
+ const rows = [...byId.values()];
349
+ const bestRank = rows.reduce((min, row) => (Number.isFinite(Number(row.rank)) && Number(row.rank) < 0 ? Math.min(min, Number(row.rank)) : min), 0);
350
+ const scored = rows.map((row) => {
351
+ const item = eventRowToItem(row);
352
+ const rank = Number(row.rank);
353
+ // bm25 越小越相关;用“相对最佳命中”做归一,避免绝对量纲随库大小漂移。
354
+ const relevance = Number.isFinite(rank) && rank < 0 && bestRank < 0
355
+ ? Math.max(0, Math.min(1, rank / bestRank))
356
+ : (match && Number.isFinite(rank) ? 0.2 : 0);
357
+ const ageDays = Math.max(0, (now - item.ts) / 86400000);
358
+ const recency = Math.pow(0.5, ageDays / MEMORY_DB_BUDGET.recencyHalfLifeDays);
359
+ const importance = Math.max(0, Math.min(1, item.importance / 10));
360
+ const retention = item.pinned ? 1 : Math.exp(-ageDays / Math.max(1, item.strength));
361
+ const semantic = query ? ngramCosine(query, item.text) : 0;
362
+ const score = item.pinned
363
+ ? 1
364
+ : (0.45 * relevance + 0.25 * recency + 0.2 * importance + 0.1 * retention) * (0.5 + 0.5 * retention)
365
+ + 0.05 * semantic;
366
+ return { ...item, relevance: Number(relevance.toFixed(4)), retention: Number(retention.toFixed(4)), score: Number(score.toFixed(4)) };
367
+ }).sort((a, b) => b.score - a.score);
368
+
369
+ const items = [];
370
+ let chars = 0;
371
+ let tokens = 0;
372
+ for (const row of scored) {
373
+ if (items.length >= topK) break;
374
+ const cost = [...row.text].length;
375
+ if (items.length && chars + cost > budgetChars) continue;
376
+ items.push(row);
377
+ chars += cost;
378
+ tokens += estimateMemoryTokens(row.text) + 4;
379
+ // 命中即“唤醒”:strength +1(pinned 不衰减也不加)
380
+ if (!row.pinned) {
381
+ try {
382
+ db.prepare('UPDATE events SET last_used_at = ?, strength = strength + 1 WHERE id = ?').run(now, row.id);
383
+ } catch { /* 记账失败不影响召回 */ }
384
+ }
385
+ }
386
+ return { items, tokens, chars, total, usedFts: Boolean(match) };
387
+ });
388
+ }
389
+
390
+ /**
391
+ * 艾宾浩斯衰减 tick:retention = exp(-days/strength);低于阈值归档(**不删**)。
392
+ * pinned 永不衰减;importance ≥ 8 的事件也不归档(“重要的事不该忘”)。
393
+ */
394
+ export function decayTick(personaId, options = {}) {
395
+ const now = Number(options.now) || Date.now();
396
+ return withDb(personaId, (db) => {
397
+ const rows = db.prepare('SELECT id, importance, created_at, last_used_at, strength, pinned FROM events WHERE persona_id = ? AND archived = 0')
398
+ .all(String(personaId));
399
+ let archived = 0;
400
+ let decayed = 0;
401
+ const update = db.prepare('UPDATE events SET archived = ? WHERE id = ?');
402
+ for (const row of rows) {
403
+ if (row.pinned === 1) continue;
404
+ const last = Number(row.last_used_at) || Number(row.created_at);
405
+ const days = Math.max(0, (now - last) / 86400000);
406
+ const strength = Math.max(1, Number(row.strength) || 1);
407
+ const retention = Math.exp(-days / strength);
408
+ if (retention < MEMORY_DB_BUDGET.archiveBelow && Number(row.importance) < 8) {
409
+ update.run(1, row.id);
410
+ archived += 1;
411
+ } else if (retention < 0.5) {
412
+ decayed += 1;
413
+ }
414
+ }
415
+ return { ok: true, archived, decayed, total: rows.length };
416
+ });
417
+ }
418
+
419
+ /** 全部事件(含归档;JSONL 兼容层/诊断用)。 */
420
+ export function allEvents(personaId, options = {}) {
421
+ const includeArchived = options.includeArchived !== false;
422
+ return withDb(personaId, (db) => {
423
+ const sql = 'SELECT * FROM events WHERE persona_id = ?' + (includeArchived ? '' : ' AND archived = 0')
424
+ + ' ORDER BY created_at ASC';
425
+ return db.prepare(sql).all(String(personaId)).map(eventRowToItem);
426
+ });
427
+ }
428
+
429
+ /** 事件列表(UI 时间线;新→旧,可按关键词过滤)。 */
430
+ export function listEvents(personaId, options = {}) {
431
+ const offset = Math.max(0, Number(options.offset) || 0);
432
+ const limit = Math.min(200, Math.max(1, Number(options.limit) || 50));
433
+ const query = String(options.q || '').trim();
434
+ return withDb(personaId, (db) => {
435
+ let rows;
436
+ let total;
437
+ if (query) {
438
+ const like = '%' + query + '%';
439
+ total = Number(db.prepare('SELECT COUNT(*) AS n FROM events WHERE persona_id = ? AND text LIKE ?').get(String(personaId), like).n) || 0;
440
+ rows = db.prepare(`SELECT * FROM events WHERE persona_id = ? AND text LIKE ?
441
+ ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(String(personaId), like, limit, offset);
442
+ } else {
443
+ total = eventsCount(personaId);
444
+ rows = db.prepare(`SELECT * FROM events WHERE persona_id = ?
445
+ ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(String(personaId), limit, offset);
446
+ }
447
+ return { total, offset, limit, items: rows.map(eventRowToItem) };
448
+ });
449
+ }
450
+
451
+ /** 删除单条事件(FTS 索引同步删)。 */
452
+ export function deleteEvent(personaId, eventId) {
453
+ const id = Number(eventId);
454
+ if (!Number.isFinite(id) || id <= 0) return { ok: false, error: 'not-found' };
455
+ return withDb(personaId, (db) => {
456
+ const row = db.prepare('SELECT id FROM events WHERE id = ? AND persona_id = ?').get(id, String(personaId));
457
+ if (!row) return { ok: false, error: 'not-found' };
458
+ db.prepare('DELETE FROM events_fts WHERE rowid = ?').run(id);
459
+ db.prepare('DELETE FROM events WHERE id = ?').run(id);
460
+ return { ok: true, id: String(eventId) };
461
+ });
462
+ }
463
+
464
+ /** 按本地日期(YYYY-MM-DD)删事件 —— “按日期回滚”。 */
465
+ export function deleteByDate(personaId, dateKey) {
466
+ const parts = String(dateKey || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
467
+ if (!parts) return { ok: false, error: 'bad-date', deleted: 0 };
468
+ const start = new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]), 0, 0, 0, 0).getTime();
469
+ const end = start + 86400000;
470
+ return withDb(personaId, (db) => {
471
+ const rows = db.prepare('SELECT id FROM events WHERE persona_id = ? AND created_at >= ? AND created_at < ?')
472
+ .all(String(personaId), start, end);
473
+ const delFts = db.prepare('DELETE FROM events_fts WHERE rowid = ?');
474
+ const del = db.prepare('DELETE FROM events WHERE id = ?');
475
+ for (const row of rows) { delFts.run(row.id); del.run(row.id); }
476
+ return { ok: true, deleted: rows.length, date: dateKey };
477
+ });
478
+ }
479
+
480
+ /** 回滚到某个时间点之后(更“版本化”的口径:保留 <= before 的事件)。 */
481
+ export function rollbackTo(personaId, beforeTs) {
482
+ const ts = Number(beforeTs);
483
+ if (!Number.isFinite(ts)) return { ok: false, error: 'bad-time', deleted: 0 };
484
+ return withDb(personaId, (db) => {
485
+ const rows = db.prepare('SELECT id FROM events WHERE persona_id = ? AND created_at > ?').all(String(personaId), ts);
486
+ const delFts = db.prepare('DELETE FROM events_fts WHERE rowid = ?');
487
+ const del = db.prepare('DELETE FROM events WHERE id = ?');
488
+ for (const row of rows) { delFts.run(row.id); del.run(row.id); }
489
+ return { ok: true, deleted: rows.length, before: ts };
490
+ });
491
+ }
492
+
493
+ export function clear(personaId) {
494
+ return withDb(personaId, (db) => {
495
+ const ids = db.prepare('SELECT id FROM events WHERE persona_id = ?').all(String(personaId));
496
+ const delFts = db.prepare('DELETE FROM events_fts WHERE rowid = ?');
497
+ for (const row of ids) delFts.run(row.id);
498
+ db.prepare('DELETE FROM events WHERE persona_id = ?').run(String(personaId));
499
+ db.prepare('DELETE FROM relations WHERE persona_id = ?').run(String(personaId));
500
+ const loreIds = db.prepare('SELECT id FROM lore WHERE persona_id = ?').all(String(personaId));
501
+ const delLoreFts = db.prepare('DELETE FROM lore_fts WHERE rowid = ?');
502
+ for (const row of loreIds) delLoreFts.run(row.id);
503
+ db.prepare('DELETE FROM lore WHERE persona_id = ?').run(String(personaId));
504
+ db.prepare('DELETE FROM summaries WHERE persona_id = ?').run(String(personaId));
505
+ return { ok: true };
506
+ });
507
+ }
508
+
509
+ /* ── 关系 / 好感度 ───────────────────────────────────────────────────────── */
510
+
511
+ const AFFINITY_MIN = -10;
512
+ const AFFINITY_MAX = 10;
513
+
514
+ /** 从一句对话里抽实体(尽量保守:只认明确的“喜欢/讨厌/在做/叫我”)。 */
515
+ export function extractEntities(text) {
516
+ const raw = String(text || '');
517
+ const out = [];
518
+ const push = (entity, delta, note) => {
519
+ const name = clip(String(entity || '').trim(), 24);
520
+ if (!name || name.length < 2) return;
521
+ out.push({ entity: name, delta, note: clip(note || '', 80) });
522
+ };
523
+ const like = raw.match(/(?:我|人家)?(?:很|最|超|特别)?(?:喜欢|爱看|爱玩|爱吃|爱听)\s*([^\s,,。!!??、]{2,12})/);
524
+ if (like) push(like[1], 1, '从对话抽到:用户喜欢');
525
+ const dislike = raw.match(/(?:我|人家)?(?:很|最|超|特别)?(?:不喜欢|讨厌|受不了|怕)\s*([^\s,,。!!??、]{2,12})/);
526
+ if (dislike) push(dislike[1], -1, '从对话抽到:用户不喜欢');
527
+ const working = raw.match(/(?:我在|我正在|最近在|这段时间在)(?:做|写|弄|搞|学|玩)\s*([^\s,,。!!??、]{2,16})/);
528
+ if (working) push(working[1], 0.5, '从对话抽到:最近在做');
529
+ const callMe = raw.match(/(?:叫我|称呼我|管我叫)\s*([^\s,,。!!??、]{1,12})/);
530
+ if (callMe) push(callMe[1], 0.5, '从对话抽到:称呼');
531
+ return out;
532
+ }
533
+
534
+ /** 关系 upsert:affinity 累加并夹在 -10..10;entity 按人设隔离。 */
535
+ export function upsertRelation(personaId, entity, delta = 0, note = '') {
536
+ const name = clip(String(entity || '').trim(), 24);
537
+ if (!name) return { ok: false, error: 'bad-entity' };
538
+ const now = Date.now();
539
+ return withDb(personaId, (db) => {
540
+ const current = db.prepare('SELECT affinity, notes FROM relations WHERE persona_id = ? AND entity = ?')
541
+ .get(String(personaId), name);
542
+ const next = Math.max(AFFINITY_MIN, Math.min(AFFINITY_MAX, Math.round((Number(current && current.affinity) || 0) + Number(delta || 0))));
543
+ const notes = clip(note || (current && current.notes) || '', 200);
544
+ db.prepare(`INSERT INTO relations(persona_id, entity, affinity, notes, updated_at) VALUES (?, ?, ?, ?, ?)
545
+ ON CONFLICT(persona_id, entity) DO UPDATE SET affinity = excluded.affinity, notes = excluded.notes, updated_at = excluded.updated_at`)
546
+ .run(String(personaId), name, next, notes, now);
547
+ return { ok: true, entity: name, affinity: next, notes, updatedAt: now };
548
+ });
549
+ }
550
+
551
+ /** 从一段对话里抽实体并写关系(路由在每轮聊天后调用)。 */
552
+ export function touchRelations(personaId, text) {
553
+ const found = extractEntities(text);
554
+ for (const item of found) upsertRelation(personaId, item.entity, item.delta, item.note);
555
+ return found;
556
+ }
557
+
558
+ export function listRelations(personaId, options = {}) {
559
+ const limit = Math.max(1, Math.min(100, Number(options.limit) || 50));
560
+ return withDb(personaId, (db) => db.prepare('SELECT * FROM relations WHERE persona_id = ? ORDER BY ABS(affinity) DESC, updated_at DESC LIMIT ?')
561
+ .all(String(personaId), limit).map((row) => ({
562
+ entity: row.entity,
563
+ affinity: Number(row.affinity),
564
+ notes: row.notes || '',
565
+ updatedAt: Number(row.updated_at) || 0,
566
+ })));
567
+ }
568
+
569
+ export function deleteRelation(personaId, entity) {
570
+ return withDb(personaId, (db) => {
571
+ const info = db.prepare('DELETE FROM relations WHERE persona_id = ? AND entity = ?').run(String(personaId), clip(entity, 24));
572
+ return { ok: Number(info.changes) > 0 };
573
+ });
574
+ }
575
+
576
+ /** 关系注入块(给 system prompt 用;没有人设数据返回空串)。 */
577
+ export function relationsPromptLine(personaId, limit = 8) {
578
+ const rows = listRelations(personaId, { limit });
579
+ if (!rows.length) return '';
580
+ return '你记得和这些对象的关系(好感度 -10..10;只作背景,不要报数值):\n'
581
+ + rows.map((row) => `- ${row.entity}:${row.affinity > 0 ? '好感 +' : row.affinity < 0 ? '好感 ' : '中性 '}${row.affinity}`
582
+ + (row.notes ? `(${row.notes})` : '')).join('\n');
583
+ }
584
+
585
+ /* ── 世界书(lore)──────────────────────────────────────────────────────── */
586
+
587
+ const LORE_CHUNK_MIN = 500;
588
+ const LORE_CHUNK_MAX = 800;
589
+
590
+ /** 把长文切成 500–800 字的块(按段落/句号优先,硬切兜底)。 */
591
+ export function chunkLore(text, options = {}) {
592
+ const raw = String(text || '').replace(/\r\n/g, '\n').trim();
593
+ if (!raw) return [];
594
+ const max = Math.max(LORE_CHUNK_MIN, Math.min(1200, Number(options.maxChars) || LORE_CHUNK_MAX));
595
+ const chunks = [];
596
+ let buffer = '';
597
+ const flush = () => {
598
+ const value = buffer.trim();
599
+ buffer = '';
600
+ if (value) chunks.push(value);
601
+ };
602
+ for (const paragraph of raw.split(/\n{2,}/)) {
603
+ const piece = paragraph.trim();
604
+ if (!piece) continue;
605
+ if ([...buffer].length + [...piece].length + 2 <= max) {
606
+ buffer += (buffer ? '\n\n' : '') + piece;
607
+ continue;
608
+ }
609
+ flush();
610
+ if ([...piece].length <= max) { buffer = piece; continue; }
611
+ // 长段落:按句号切,单句仍超长就硬切
612
+ for (const sentence of piece.split(/(?<=[。!?!?;;])/)) {
613
+ if (!sentence.trim()) continue;
614
+ if ([...buffer].length + [...sentence].length <= max) buffer += sentence;
615
+ else {
616
+ flush();
617
+ if ([...sentence].length <= max) buffer = sentence;
618
+ else {
619
+ let rest = sentence;
620
+ while ([...rest].length > max) {
621
+ chunks.push([...rest].slice(0, max).join(''));
622
+ rest = [...rest].slice(max).join('');
623
+ }
624
+ buffer = rest;
625
+ }
626
+ }
627
+ }
628
+ flush();
629
+ }
630
+ flush();
631
+ return chunks.filter((chunk) => [...chunk].length >= 30);
632
+ }
633
+
634
+ /**
635
+ * 导入世界书(角色卡/文档正文):分块入 lore + FTS。
636
+ * @returns {{ok:true, chunks:number, ids:number[]}}
637
+ */
638
+ export function addLore(personaId, input = {}) {
639
+ const content = String(input.content || '').trim();
640
+ if (!content) return { ok: false, error: 'empty-content', chunks: 0, ids: [] };
641
+ const title = clip(input.title || '世界书', 120);
642
+ const source = clip(input.source || '', 80);
643
+ const chunks = chunkLore(content, { maxChars: input.maxChars });
644
+ const now = Date.now();
645
+ return withDb(personaId, (db) => {
646
+ const ids = [];
647
+ chunks.forEach((chunk, index) => {
648
+ const info = db.prepare('INSERT INTO lore(persona_id, title, content, chunk_no, source, created_at) VALUES (?, ?, ?, ?, ?, ?)')
649
+ .run(String(personaId), title, chunk, index, source, now);
650
+ const id = Number(info.lastInsertRowid);
651
+ db.prepare('INSERT INTO lore_fts(rowid, text) VALUES (?, ?)').run(id, tokenizeForIndex(`${title} ${chunk}`).join(' '));
652
+ ids.push(id);
653
+ });
654
+ return { ok: true, chunks: chunks.length, ids };
655
+ });
656
+ }
657
+
658
+ /** 世界书检索:FTS top-3(注入用)或指定 limit。 */
659
+ export function searchLore(personaId, query, options = {}) {
660
+ const limit = Math.max(1, Math.min(20, Number(options.limit) || 3));
661
+ const match = ftsQueryFor(query);
662
+ return withDb(personaId, (db) => {
663
+ if (!match) {
664
+ return db.prepare('SELECT * FROM lore WHERE persona_id = ? ORDER BY created_at DESC LIMIT ?')
665
+ .all(String(personaId), limit).map((row) => ({ id: Number(row.id), title: row.title, content: row.content, chunkNo: Number(row.chunk_no), source: row.source }));
666
+ }
667
+ let rows = [];
668
+ try {
669
+ rows = db.prepare(`SELECT l.*, bm25(lore_fts) AS rank FROM lore_fts JOIN lore l ON l.id = lore_fts.rowid
670
+ WHERE lore_fts MATCH ? AND l.persona_id = ? ORDER BY rank LIMIT ?`).all(match, String(personaId), limit);
671
+ } catch { rows = []; }
672
+ return rows.map((row) => ({ id: Number(row.id), title: row.title, content: row.content, chunkNo: Number(row.chunk_no), source: row.source }));
673
+ });
674
+ }
675
+
676
+ export function listLore(personaId, options = {}) {
677
+ const limit = Math.max(1, Math.min(200, Number(options.limit) || 100));
678
+ return withDb(personaId, (db) => db.prepare('SELECT id, title, chunk_no, source, created_at, length(content) AS size FROM lore WHERE persona_id = ? ORDER BY created_at DESC LIMIT ?')
679
+ .all(String(personaId), limit).map((row) => ({
680
+ id: Number(row.id), title: row.title, chunkNo: Number(row.chunk_no), source: row.source, createdAt: Number(row.created_at), size: Number(row.size),
681
+ })));
682
+ }
683
+
684
+ export function deleteLore(personaId, loreId) {
685
+ const id = Number(loreId);
686
+ if (!Number.isFinite(id)) return { ok: false };
687
+ return withDb(personaId, (db) => {
688
+ const row = db.prepare('SELECT id FROM lore WHERE id = ? AND persona_id = ?').get(id, String(personaId));
689
+ if (!row) return { ok: false };
690
+ db.prepare('DELETE FROM lore_fts WHERE rowid = ?').run(id);
691
+ db.prepare('DELETE FROM lore WHERE id = ?').run(id);
692
+ return { ok: true };
693
+ });
694
+ }
695
+
696
+ /** lore 注入块(FTS top-3)。 */
697
+ export function lorePromptLine(personaId, query, limit = 3) {
698
+ const rows = searchLore(personaId, query, { limit });
699
+ if (!rows.length) return '';
700
+ return '【世界书命中】只作背景,不要整段复述:\n' + rows.map((row) => '- ' + clip(row.content, 400)).join('\n');
701
+ }
702
+
703
+ /* ── 摘要 ───────────────────────────────────────────────────────────────── */
704
+
705
+ export function saveSummary(personaId, period, text) {
706
+ const key = clip(period || 'latest', 20);
707
+ withDb(personaId, (db) => db.prepare(`INSERT INTO summaries(persona_id, period, text, created_at) VALUES (?, ?, ?, ?)
708
+ ON CONFLICT(persona_id, period) DO UPDATE SET text = excluded.text, created_at = excluded.created_at`)
709
+ .run(String(personaId), key, clip(text, 8000), Date.now()));
710
+ return { ok: true, period: key };
711
+ }
712
+
713
+ export function readSummary(personaId) {
714
+ return withDb(personaId, (db) => {
715
+ const row = db.prepare("SELECT text, created_at FROM summaries WHERE persona_id = ? AND period = 'latest'").get(String(personaId));
716
+ return row ? { text: row.text, updatedAt: Number(row.created_at) || 0 } : { text: '', updatedAt: 0 };
717
+ });
718
+ }
719
+
720
+ /* ── 统计 / 迁移 / 导出 ─────────────────────────────────────────────────── */
721
+
722
+ export function stats(personaId) {
723
+ return withDb(personaId, (db) => {
724
+ const get = (sql, ...args) => Number(db.prepare(sql).get(...args).n) || 0;
725
+ return {
726
+ ok: true,
727
+ personaId: String(personaId),
728
+ events: get('SELECT COUNT(*) AS n FROM events WHERE persona_id = ?', String(personaId)),
729
+ archived: get('SELECT COUNT(*) AS n FROM events WHERE persona_id = ? AND archived = 1', String(personaId)),
730
+ pinned: get('SELECT COUNT(*) AS n FROM events WHERE persona_id = ? AND pinned = 1', String(personaId)),
731
+ relations: get('SELECT COUNT(*) AS n FROM relations WHERE persona_id = ?', String(personaId)),
732
+ lore: get('SELECT COUNT(*) AS n FROM lore WHERE persona_id = ?', String(personaId)),
733
+ summaries: get('SELECT COUNT(*) AS n FROM summaries WHERE persona_id = ?', String(personaId)),
734
+ path: memoryDbPath(personaId),
735
+ };
736
+ });
737
+ }
738
+
739
+ /** 导出(JSON 可读;事件/关系/世界书/摘要/元信息)。 */
740
+ export function exportMemory(personaId) {
741
+ return withDb(personaId, (db) => {
742
+ const events = db.prepare('SELECT * FROM events WHERE persona_id = ? ORDER BY created_at').all(String(personaId));
743
+ const relations = db.prepare('SELECT * FROM relations WHERE persona_id = ? ORDER BY entity').all(String(personaId));
744
+ const lore = db.prepare('SELECT id, title, content, chunk_no, source, created_at FROM lore WHERE persona_id = ? ORDER BY chunk_no').all(String(personaId));
745
+ const summaries = db.prepare('SELECT * FROM summaries WHERE persona_id = ?').all(String(personaId));
746
+ return {
747
+ ok: true,
748
+ version: 2,
749
+ personaId: String(personaId),
750
+ exportedAt: Date.now(),
751
+ events: events.map(eventRowToItem),
752
+ relations: relations.map((row) => ({ entity: row.entity, affinity: Number(row.affinity), notes: row.notes, updatedAt: Number(row.updated_at) })),
753
+ lore: lore.map((row) => ({ id: Number(row.id), title: row.title, content: row.content, chunkNo: Number(row.chunk_no), source: row.source })),
754
+ summaries: summaries.map((row) => ({ period: row.period, text: row.text, createdAt: Number(row.created_at) })),
755
+ stats: stats(personaId),
756
+ };
757
+ });
758
+ }
759
+
760
+ /** meta 读写(迁移标记用)。 */
761
+ function readMeta(db, key) {
762
+ const row = db.prepare('SELECT value FROM meta WHERE key = ?').get(key);
763
+ return row ? row.value : '';
764
+ }
765
+ function writeMeta(db, key, value) {
766
+ db.prepare('INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
767
+ .run(key, String(value));
768
+ }
769
+
770
+ /**
771
+ * 从旧 JSONL 迁移(幂等:已迁移过就跳过;按 text+created_at 去重)。
772
+ * 保留 JSONL 原文件不动(只读备份),迁移失败由调用方回退旧路径。
773
+ * @returns {{ok:boolean, imported:number, skipped:number, reason?:string}}
774
+ */
775
+ export function migrateFromJsonl(personaId, options = {}) {
776
+ const dir = join(personaDir(personaId), 'memory');
777
+ const jsonlPath = options.eventsPath || join(dir, 'events.jsonl');
778
+ const summaryPath = options.summaryPath || join(dir, 'summary.json');
779
+ if (!existsSync(jsonlPath) && !existsSync(summaryPath)) return { ok: true, imported: 0, skipped: 0, reason: 'no-jsonl' };
780
+ return withDb(personaId, (db) => {
781
+ const marker = readMeta(db, 'jsonl_migrated_at');
782
+ if (marker) return { ok: true, imported: 0, skipped: 0, reason: 'already-migrated' };
783
+ let imported = 0;
784
+ let skipped = 0;
785
+ let summaryImported = false;
786
+ try {
787
+ if (existsSync(jsonlPath) && statSync(jsonlPath).size > 0) {
788
+ const text = readFileSync(jsonlPath, 'utf8');
789
+ const known = db.prepare('SELECT id FROM events WHERE persona_id = ? AND text = ? AND created_at = ?');
790
+ for (const line of text.split('\n')) {
791
+ if (!line.trim()) continue;
792
+ let raw;
793
+ try { raw = JSON.parse(line); } catch { skipped += 1; continue; }
794
+ const body = String((raw && raw.text) || '').trim();
795
+ if (!body) { skipped += 1; continue; }
796
+ const ts = Number(raw.ts) || Date.now();
797
+ if (known.get(String(personaId), body, ts)) { skipped += 1; continue; }
798
+ addEvent(personaId, {
799
+ text: body,
800
+ kind: raw.kind,
801
+ importance: raw.importance,
802
+ ts,
803
+ pinned: raw.pinned === true,
804
+ source: 'jsonl-migration',
805
+ tags: Array.isArray(raw.refs) ? raw.refs : [],
806
+ });
807
+ imported += 1;
808
+ }
809
+ }
810
+ if (existsSync(summaryPath)) {
811
+ try {
812
+ const doc = JSON.parse(readFileSync(summaryPath, 'utf8'));
813
+ if (doc && typeof doc.text === 'string' && doc.text.trim()) {
814
+ saveSummary(personaId, 'latest', doc.text);
815
+ summaryImported = true;
816
+ }
817
+ } catch { skipped += 1; }
818
+ }
819
+ writeMeta(db, 'jsonl_migrated_at', String(Date.now()));
820
+ writeMeta(db, 'jsonl_source', jsonlPath);
821
+ return { ok: true, imported, skipped, summaryImported };
822
+ } catch (error) {
823
+ return { ok: false, imported, skipped, reason: String((error && error.message) || error) };
824
+ }
825
+ });
826
+ }
827
+
828
+ /** 迁移标记(诊断用;不触发迁移)。 */
829
+ export function migrationInfo(personaId) {
830
+ return withDb(personaId, (db) => ({
831
+ migratedAt: Number(readMeta(db, 'jsonl_migrated_at')) || 0,
832
+ source: readMeta(db, 'jsonl_source') || '',
833
+ path: memoryDbPath(personaId),
834
+ }));
835
+ }