whale-memory-core 0.22.0 → 0.24.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.
@@ -9,7 +9,9 @@ import * as sealEvents from './seal-events.js'
9
9
  import * as linkEvents from './link-events.js'
10
10
  import * as chapterEvents from './chapter-events.js'
11
11
  import { queryTerms, requiredOverlap, matchedTerms, normalizeText, contentUnits, coverage, MIN_COVER } from './query-match.js'
12
+ import { hybridRank } from './hybrid-recall.js'
12
13
  import { parseAsOf, before, dayOf } from './as-of.js'
14
+ import { readSnapshot } from './sqlite-store.js'
13
15
 
14
16
  const FILE = 'self-experience.jsonl'
15
17
  const WEIGHTS = new Set(['important', 'normal', 'minor'])
@@ -152,7 +154,11 @@ function normalize(r) {
152
154
  // 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
153
155
  // strict:展示路径用,坏行直接抛(见 readAll)
154
156
  function identify(dir, { strict = false } = {}) {
155
- const raw = readAll(dir, { strict })
157
+ return identifyRaw(readAll(dir, { strict }))
158
+ }
159
+
160
+ // 同上,输入是已经读出来的 { rows, bad }(文件或 SQLite 都行)
161
+ function identifyRaw(raw) {
156
162
  const rows = raw.rows.map(normalize).filter((r) => r && r.then && r.then.text)
157
163
  const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
158
164
  const owners = new Map()
@@ -190,10 +196,53 @@ const brief = (r) => {
190
196
  // 坏行(self-experience.jsonl 里有解析不了的行)默认 fail closed:返回的部分经历会
191
197
  // 把"少了一条"装成"就这些",召回/书/体检都会当真。要按字节备份、恢复演练、计数这种
192
198
  // 不展示内容的工具,传 allowCorrupt(导出/恢复那条路走 allowSealCorrupt,含义相同)。
193
- export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false } = {}) {
199
+ // 数据从哪来:file(默认,原样走各模块的读文件函数,调用顺序与参数和以前一模一样)
200
+ // 或 sqlite(一次读事务拿到记录 + 六类事件的快照,再走同一套合并逻辑)。
201
+ // 合并逻辑只有一份,所以两个后端在同一份数据上读出来的结果逐条相同。
202
+ const BACKENDS = new Set(['file', 'sqlite'])
203
+
204
+ function backendName(backend) {
205
+ const name = backend === undefined || backend === null || backend === '' ? 'file' : String(backend)
206
+ if (!BACKENDS.has(name)) throw new Error('未知的存储后端:' + name + '(支持 file / sqlite)')
207
+ return name
208
+ }
209
+
210
+ function fileSource(dir) {
211
+ return {
212
+ records: (strict) => readAll(dir, { strict }),
213
+ recalls: (until, onError) => readEvents(dir, recallEvents.eventsFile, () => recallEvents.countByExp(dir, { until }), onError),
214
+ later: (until, onError) => readEvents(dir, laterEvents.eventsFile, () => laterEvents.groupByExp(dir, { until }), onError),
215
+ unfinished: (until, onError) => readEvents(dir, unfinishedEvents.eventsFile, () => unfinishedEvents.latestByExp(dir, { until }), onError),
216
+ sealed: (until, strict) => sealEvents.sealedByExp(dir, { until, strict }),
217
+ links: (until, onError) => readEvents(dir, linkEvents.eventsFile, () => linkEvents.linksByExp(dir, { until }), onError),
218
+ chapters: (until, onError) => readEvents(dir, chapterEvents.eventsFile, () => chapterEvents.chapters(dir, { until }), onError)
219
+ }
220
+ }
221
+
222
+ // 快照在这里一次读完:拿不到 node:sqlite、没迁移、库不全、JSONL 在迁移后又变过,都在这一步抛(见 sqlite-store.readSnapshot)
223
+ function sqliteSource(dir) {
224
+ const snap = readSnapshot(dir)
225
+ const ev = (kind) => snap.events[kind]
226
+ return {
227
+ records: (strict) => {
228
+ if (strict && snap.records.bad > 0) throw experienceCorrupt(snap.records.bad)
229
+ return snap.records
230
+ },
231
+ recalls: (until) => recallEvents.countRows(ev('recall').rows, { until }),
232
+ later: (until) => laterEvents.groupRows(ev('later').rows, { until }),
233
+ unfinished: (until) => unfinishedEvents.latestRows(ev('unfinished').rows, { until }),
234
+ sealed: (until, strict) => sealEvents.sealedFrom(ev('seal'), { until, strict }),
235
+ links: (until) => linkEvents.linksRows(ev('link').rows, { until }),
236
+ chapters: (until) => chapterEvents.chapterRows(ev('chapter').rows, { until })
237
+ }
238
+ }
239
+
240
+ // backend:'file'(默认,零行为变化)或 'sqlite'(读 memory.sqlite,要求 node:sqlite;拿不到就报错,不静默退回 file)
241
+ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false, backend = 'file' } = {}) {
194
242
  const until = parseAsOf(asOf)
195
243
  const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
196
- const { rows: all } = identify(dir, { strict: !rawMode })
244
+ const src = backendName(backend) === 'sqlite' ? sqliteSource(dir) : fileSource(dir)
245
+ const { rows: all } = identifyRaw(src.records(!rawMode))
197
246
  const rows = until === null ? all : all.filter((r) => before(r, until))
198
247
  if (!rows.length) return rows
199
248
 
@@ -201,13 +250,13 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
201
250
  // 读不出来必须报出来(readEvents):否则会当成"她从没想起过"。
202
251
  // rawMode(按字节备份/恢复/计数)不看事件内容,读不出来也不该拦住备份。
203
252
  const onEventError = rawMode ? () => new Map() : null
204
- const counts = readEvents(dir, recallEvents.eventsFile, () => recallEvents.countByExp(dir, { until }), onEventError)
253
+ const counts = src.recalls(until, onEventError)
205
254
 
206
255
  // 改主意:旧 later 数组 + later-events 事件,按时间合并
207
- const laterMap = readEvents(dir, laterEvents.eventsFile, () => laterEvents.groupByExp(dir, { until }), onEventError)
256
+ const laterMap = src.later(until, onEventError)
208
257
 
209
258
  // 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
210
- const unfinishedMap = readEvents(dir, unfinishedEvents.eventsFile, () => unfinishedEvents.latestByExp(dir, { until }), onEventError)
259
+ const unfinishedMap = src.unfinished(until, onEventError)
211
260
 
212
261
  // 她选择封存的:不再被主动想起,但还在。
213
262
  // 读不出来就抛出去,不能当成"什么都没封存"——否则正文可读、日志读不了时,
@@ -215,11 +264,11 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
215
264
  // strict:坏行也算"状态未知",展示路径必须 fail closed。
216
265
  // allowSealCorrupt:只给"按字节备份/恢复/计数"这种不展示内容的工具用;
217
266
  // 它们要能保住损坏现场,但不能把结果当"可见"用。
218
- const sealedMap = sealEvents.sealedByExp(dir, { until, strict: !allowSealCorrupt })
267
+ const sealedMap = src.sealed(until, !allowSealCorrupt)
219
268
  // 翻回那天时,她**现在**封存着的也不翻出来:封存说的是她现在不想被提起,而翻回那天正是在提起旧事。
220
269
  // 那时还没封存的,标成 afterAsOf(后来才封存),各处过滤照常生效;点名读仍然给,并写明是后来封存的
221
270
  let sealedNowMap = sealedMap
222
- if (until !== null) sealedNowMap = sealEvents.sealedByExp(dir, { strict: !allowSealCorrupt })
271
+ if (until !== null) sealedNowMap = src.sealed(null, !allowSealCorrupt)
223
272
 
224
273
  const viewed = rows.map((r) => {
225
274
  const keys = r.formerId ? [r.id, r.formerId] : [r.id]
@@ -292,8 +341,8 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
292
341
  }
293
342
 
294
343
  // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
295
- const linkMap = readEvents(dir, linkEvents.eventsFile, () => linkEvents.linksByExp(dir, { until }), onEventError)
296
- const chapterList = readEvents(dir, chapterEvents.eventsFile, () => chapterEvents.chapters(dir, { until }), rawMode ? () => [] : null)
344
+ const linkMap = src.links(until, onEventError)
345
+ const chapterList = src.chapters(until, rawMode ? () => [] : null)
297
346
  for (const r of viewed) {
298
347
  const keys = r.formerId ? [r.id, r.formerId] : [r.id]
299
348
  const links = !r.duplicateOf && keys.flatMap((k) => linkMap.get(k) || [])
@@ -496,8 +545,8 @@ export function markRecalled(dir, id) {
496
545
  }
497
546
 
498
547
  // asOf:看那天的这一条(那之后的后记、选择、想起都不算);那天还没写下就返回 null
499
- export function currentView(dir, id, { asOf = null } = {}) {
500
- const rows = loadAll(dir, { asOf })
548
+ export function currentView(dir, id, { asOf = null, backend = 'file' } = {}) {
549
+ const rows = loadAll(dir, { asOf, backend })
501
550
  return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
502
551
  }
503
552
 
@@ -511,10 +560,37 @@ export function currentView(dir, id, { asOf = null } = {}) {
511
560
  // 她封存了的经历不会被召回;includeSealed=true 只给"她自己要翻"这种明确场景用
512
561
  // gate:strict 下用哪套门槛。'cover'(默认,0.17 起)= 至少对上一个词 + 意思至少 70% 被接住;
513
562
  // 'legacy' = 0.16 及以前的口径(长查询要 60% 的两字词对上),排序也照旧。宿主想保持旧行为时用
514
- export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict', asOf = null, includeSealed = false, gate = 'cover' } = {}) {
563
+ // backend:读哪个容器(默认 file,见 loadAll)。写路径还没切到 sqlite:sqlite 下 mark=true 会把想起记到 JSONL、
564
+ // 库里看不见,所以直接拒绝,不留一笔两边对不上的账
565
+ // ranker:'literal'(默认,0.23.0 及以前的行为一个字都没改)或 'hybrid'(BM25 + 字符 n-gram + 小同义词表,
566
+ // 见 hybrid-recall.js)。实验性:指标没显著提升就不切默认,默认仍是字面检索。
567
+ // context:上一轮查询(字符串或数组)。宿主做多轮追问时把上下文一起递进来;字面检索把它拼到查询前面,
568
+ // 混合检索只用它排序(追问句本身几乎没有内容词时才用它补足门禁)。不传就是单轮,行为不变。
569
+ // ranker='hybrid' 时 mode / gate / minOverlap / minRatio 都不参与(它有自己的覆盖率门槛,见 hybrid-recall.js);
570
+ // 空查询在 hybrid 下返回空(字面检索的旧行为不变)。ranker 传 null / undefined 都按 literal 处理。
571
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict', asOf = null, includeSealed = false, gate = 'cover', backend = 'file', ranker = 'literal', context = null } = {}) {
515
572
  if (mark && asOf !== null && asOf !== undefined && asOf !== '') throw new Error('Looking back at an earlier day does not record a recall: mark and asOf cannot be used together.(翻回旧日子时不记「想起」:mark 和 asOf 不能一起用。)')
516
- const rows = loadAll(dir, { asOf }).filter((r) => includeSealed || !r.sealed)
517
- const q = String(query || '')
573
+ if (mark && backendName(backend) !== 'file') throw new Error('mark=true only works with the file backend for now: recalls are still written to JSONL.(写路径还没切到 sqlite:mark=true 目前只能配 file 后端。)')
574
+ if (ranker !== 'literal' && ranker !== 'hybrid') {
575
+ if (ranker === null || ranker === undefined) ranker = 'literal'
576
+ else throw new Error('ranker must be "literal" or "hybrid"(ranker 只能是 literal 或 hybrid)')
577
+ }
578
+ const rows = loadAll(dir, { asOf, backend }).filter((r) => includeSealed || !r.sealed)
579
+ const q0 = String(query || '')
580
+ const ctxText = Array.isArray(context) ? context.filter(Boolean).join(' ') : String(context || '')
581
+
582
+ // 混合检索:放行门槛仍是防编造那套(覆盖率),BM25 只重排;mark 的行为和字面检索一致
583
+ if (ranker === 'hybrid') {
584
+ const hits = hybridRank({ rows, query: q0, context: ctxText, limit })
585
+ if (!mark || !hits.length) return hits
586
+ const at = new Date().toISOString()
587
+ for (const r of hits) {
588
+ try { recallEvents.append(dir, { id: r.id, query: q0 }) } catch { /* 坏文件时不阻断召回 */ }
589
+ }
590
+ return hits.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
591
+ }
592
+
593
+ const q = ctxText ? ctxText + ' ' + q0 : q0
518
594
  const parsed = queryTerms(q)
519
595
  const { terms } = parsed
520
596
  const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
@@ -0,0 +1,289 @@
1
+ // SQLite 容器的同步内核(阶段 1 续):表结构、整库快照、写入。
2
+ //
3
+ // 为什么是同步的:loadAll / recall 是同步 API,宿主不用改一行;node:sqlite 的 DatabaseSync
4
+ // 本来就是同步的。node:sqlite 用 process.getBuiltinModule 同步取,取不到就**报错**,不静默退回 file。
5
+ // 这个文件只在真的要用 SQLite 时才去取 node:sqlite;只 import 它不会碰 node:sqlite(Node 20 照常能加载)。
6
+ //
7
+ // 换容器不换内容:记录和事件的 JSON 形状一个字不改,库里存的就是 JSONL 里那一行。
8
+ // 坏行口径也一样:事件用各自模块的 isValid 判,记录只看能不能解析——和读文件时完全同一条判据。
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import * as laterEvents from './later-events.js'
12
+ import * as sealEvents from './seal-events.js'
13
+ import * as recallEvents from './recall-events.js'
14
+ import * as unfinishedEvents from './unfinished-events.js'
15
+ import * as linkEvents from './link-events.js'
16
+ import * as chapterEvents from './chapter-events.js'
17
+
18
+ export const DB_FILE = 'memory.sqlite'
19
+ export const RECORDS_FILE = 'self-experience.jsonl'
20
+
21
+ const fileOf = (mod) => path.basename(mod.eventsFile('.'))
22
+
23
+ // 事件种类 → 原来的 JSONL 文件、合格判据、索引用的主体 id。
24
+ // 契约里点名的四类之外,loadAll 还读联想与章节两类;只搬一部分的话,sqlite 读出来会缺东西,所以六类一起搬。
25
+ // subject:建索引用。联想按 from,章节按章节 id(不是经历 id),其余按经历 id。
26
+ // expIds:这条事件指向哪些经历(mustExist 要逐一确认在)。联想两头都算;章节不指向经历。
27
+ export const EVENT_KINDS = Object.freeze({
28
+ later: { file: fileOf(laterEvents), valid: laterEvents.isValid, subject: (r) => r.id, expIds: (r) => [r.id] },
29
+ seal: { file: fileOf(sealEvents), valid: sealEvents.isValid, subject: (r) => r.id, expIds: (r) => [r.id] },
30
+ recall: { file: fileOf(recallEvents), valid: recallEvents.isValid, subject: (r) => r.id, expIds: (r) => [r.id] },
31
+ unfinished: { file: fileOf(unfinishedEvents), valid: unfinishedEvents.isValid, subject: (r) => r.id, expIds: (r) => [r.id] },
32
+ link: { file: fileOf(linkEvents), valid: linkEvents.isValid, subject: (r) => r.from, expIds: (r) => [r.from, r.to] },
33
+ chapter: { file: fileOf(chapterEvents), valid: chapterEvents.isValid, subject: (r) => r.id, expIds: () => [] }
34
+ })
35
+ export const KIND_NAMES = Object.freeze(Object.keys(EVENT_KINDS))
36
+
37
+ // 迁移时要对账的全部源文件:一条经历文件 + 六类事件文件
38
+ export const SOURCE_FILES = Object.freeze([RECORDS_FILE, ...KIND_NAMES.map((k) => EVENT_KINDS[k].file)])
39
+
40
+ export function kindOf(kind) {
41
+ // 只认自己的键:constructor / toString / __proto__ 这类原型上的名字不能混进来
42
+ const k = typeof kind === 'string' && Object.hasOwn(EVENT_KINDS, kind) ? EVENT_KINDS[kind] : null
43
+ if (!k) throw new Error('未知的事件类型:' + kind + '(支持 ' + KIND_NAMES.join(' / ') + ')')
44
+ return k
45
+ }
46
+
47
+ function coded(message, code, extra = {}) {
48
+ return Object.assign(new Error(message), { code }, extra)
49
+ }
50
+
51
+ // ---------------------------------------------------------------- node:sqlite
52
+
53
+ // 只用 process.getBuiltinModule(Node 22.3 起有):凡是有 node:sqlite 的版本(>= 22.5)都有它,
54
+ // 不需要 createRequire 兜底(也就不多引一个 node:module,宿主的高危模块检查不会因此拦这份内核)
55
+ function loadSqlite() {
56
+ let mod
57
+ try { mod = typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : undefined } catch { mod = undefined }
58
+ if (!mod || typeof mod.DatabaseSync !== 'function') {
59
+ throw coded('当前 Node 拿不到内置的 node:sqlite(需要 >= 22.5;22.13 起默认可用,22.5–22.12 要加 --experimental-sqlite;用 --no-experimental-sqlite 关掉了也会这样)。请改用 file 后端——这里不会替你静默降级。', 'SQLITE_UNAVAILABLE')
60
+ }
61
+ return mod
62
+ }
63
+
64
+ /** 拿不到 node:sqlite 就抛 SQLITE_UNAVAILABLE(不打开任何文件)。 */
65
+ export function requireSqlite() {
66
+ loadSqlite()
67
+ }
68
+
69
+ /** 这台机器上能不能用 SQLite 后端(不打开任何文件)。 */
70
+ export function sqliteAvailable() {
71
+ try { loadSqlite(); return true } catch { return false }
72
+ }
73
+
74
+ // ---------------------------------------------------------------- 表结构
75
+
76
+ export function ensureSchema(db) {
77
+ db.exec(`CREATE TABLE IF NOT EXISTS records (
78
+ id TEXT PRIMARY KEY,
79
+ day TEXT NOT NULL,
80
+ at TEXT NOT NULL,
81
+ json TEXT NOT NULL
82
+ )`)
83
+ db.exec('CREATE INDEX IF NOT EXISTS idx_records_day ON records(day)')
84
+ // 事件:seq 就是追加顺序(= 原 JSONL 里的行序);json 是那一行原样
85
+ db.exec(`CREATE TABLE IF NOT EXISTS events (
86
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
87
+ kind TEXT NOT NULL,
88
+ exp_id TEXT,
89
+ at TEXT,
90
+ json TEXT NOT NULL
91
+ )`)
92
+ db.exec('CREATE INDEX IF NOT EXISTS idx_events_kind_exp ON events(kind, exp_id)')
93
+ // 迁移时每个源文件的字节数:读的时候拿来判断 JSONL 在迁移之后有没有又被写过
94
+ db.exec(`CREATE TABLE IF NOT EXISTS sources (
95
+ file TEXT PRIMARY KEY,
96
+ size INTEGER NOT NULL,
97
+ migrated_at TEXT NOT NULL
98
+ )`)
99
+ }
100
+
101
+ /**
102
+ * 打开库。create=false 时库不存在就返回 null(读路径不许顺手建出一个空库)。
103
+ * 先取 node:sqlite 再看文件:拿不到 node:sqlite 时,不管库在不在都报错。
104
+ */
105
+ export function openDatabase(dir, { create = false } = {}) {
106
+ return openDatabaseFile(path.join(dir, DB_FILE), { create })
107
+ }
108
+
109
+ /** 同上,但直接给库文件路径(迁移先建在临时文件名上,对拍通过再改名)。建表失败时句柄当场关掉,不漏。 */
110
+ export function openDatabaseFile(file, { create = false } = {}) {
111
+ const { DatabaseSync } = loadSqlite()
112
+ if (!create && !fs.existsSync(file)) return null
113
+ if (create) fs.mkdirSync(path.dirname(file), { recursive: true })
114
+ const db = new DatabaseSync(file)
115
+ if (create) {
116
+ try {
117
+ db.exec('PRAGMA journal_mode = WAL')
118
+ db.exec('PRAGMA synchronous = NORMAL')
119
+ ensureSchema(db)
120
+ } catch (error) {
121
+ try { db.close() } catch { }
122
+ throw error
123
+ }
124
+ }
125
+ return db
126
+ }
127
+
128
+ export function tablesOf(db) {
129
+ return new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => r.name))
130
+ }
131
+
132
+ // ---------------------------------------------------------------- 写入(调用方负责事务)
133
+
134
+ export function insertRecord(db, record) {
135
+ if (!record || typeof record.id !== 'string' || !record.id) throw new Error('记录缺少 id')
136
+ try {
137
+ db.prepare('INSERT INTO records (id, day, at, json) VALUES (?, ?, ?, ?)')
138
+ .run(record.id, String(record.day || ''), String(record.at || ''), JSON.stringify(record))
139
+ } catch (error) {
140
+ // 同一个 id 写两次是调用方的 bug;契约里 id 永不复用,这里直接拒绝
141
+ if (String(error?.message || '').includes('UNIQUE')) throw new Error('id 已存在:' + record.id)
142
+ throw error
143
+ }
144
+ return record
145
+ }
146
+
147
+ export function insertEvent(db, kind, row) {
148
+ const k = kindOf(kind)
149
+ if (!k.valid(row)) throw new Error(kind + ' 事件不合格(缺必填字段),拒绝写入')
150
+ db.prepare('INSERT INTO events (kind, exp_id, at, json) VALUES (?, ?, ?, ?)')
151
+ .run(kind, String(k.subject(row) ?? ''), String(row.at ?? ''), JSON.stringify(row))
152
+ return row
153
+ }
154
+
155
+ export function recordExists(db, id) {
156
+ return Boolean(db.prepare('SELECT 1 AS ok FROM records WHERE id = ?').get(String(id)))
157
+ }
158
+
159
+ export function writeSources(db, sizes, at = new Date().toISOString()) {
160
+ const stmt = db.prepare('INSERT OR REPLACE INTO sources (file, size, migrated_at) VALUES (?, ?, ?)')
161
+ for (const [file, size] of Object.entries(sizes)) stmt.run(file, Number(size) || 0, at)
162
+ }
163
+
164
+ // ---------------------------------------------------------------- 读
165
+
166
+ /** 源文件现在的字节数;不存在算 0。读不出来(权限、是目录)就抛。 */
167
+ export function sourceSizes(dir) {
168
+ const out = {}
169
+ for (const name of SOURCE_FILES) {
170
+ try {
171
+ const st = fs.statSync(path.join(dir, name))
172
+ if (!st.isFile()) throw coded(name + ' 不是普通文件', 'EISDIR')
173
+ out[name] = st.size
174
+ } catch (error) {
175
+ if (error && error.code === 'ENOENT') out[name] = 0
176
+ else throw error
177
+ }
178
+ }
179
+ return out
180
+ }
181
+
182
+ // 一列 json 文本 → { rows, bad }:解析不了或不合格的算坏行(和读 JSONL 时同一条判据)
183
+ function parseColumn(texts, valid = null) {
184
+ const rows = []
185
+ let bad = 0
186
+ for (const text of texts) {
187
+ try {
188
+ const r = JSON.parse(text)
189
+ if (!valid || valid(r)) rows.push(r)
190
+ else bad += 1
191
+ } catch { bad += 1 }
192
+ }
193
+ return { rows, bad }
194
+ }
195
+
196
+ function emptySnapshot() {
197
+ const events = {}
198
+ for (const k of KIND_NAMES) events[k] = { rows: [], bad: 0 }
199
+ return { records: { rows: [], bad: 0 }, events }
200
+ }
201
+
202
+ /**
203
+ * 整库快照:一次读事务里把记录和六类事件全读出来,保证看到的是同一个时刻。
204
+ *
205
+ * fail closed 的几种情况(都抛,不返回空):
206
+ * · 拿不到 node:sqlite → SQLITE_UNAVAILABLE
207
+ * · 没有 memory.sqlite,但目录里有 JSONL 数据 → STORAGE_NOT_MIGRATED(没迁移过,不能当"她什么都没写")
208
+ * · 库是阶段 1 早期建的、没有事件表 → STORAGE_INCOMPLETE(记录在库里、事件不在,读一半就断)
209
+ * · JSONL 在迁移之后又变了(写路径还在 JSONL 上) → STORAGE_STALE(sqlite 读出来会少最新的东西)
210
+ * · 库本身读不出来 → STORAGE_UNREADABLE
211
+ * 目录里既没有库、也没有任何 JSONL 数据:如实返回空。
212
+ */
213
+ export function readSnapshot(dir) {
214
+ let db
215
+ try { db = openDatabase(dir) } catch (error) {
216
+ if (error && error.code === 'SQLITE_UNAVAILABLE') throw error
217
+ throw unreadable(error)
218
+ }
219
+ if (!db) {
220
+ const present = Object.entries(sourceSizes(dir)).filter(([, size]) => size > 0).map(([name]) => name)
221
+ if (present.length) {
222
+ throw coded('这个目录还没迁移到 SQLite(没有 ' + DB_FILE + '),但有 JSONL 数据:' + present.join('、') + '。先跑 tools/migrate-storage.mjs,或继续用 file 后端;不能当成"什么都没有"。', 'STORAGE_NOT_MIGRATED', { files: present })
223
+ }
224
+ return emptySnapshot()
225
+ }
226
+ try {
227
+ let tables
228
+ try { tables = tablesOf(db) } catch (error) { throw unreadable(error) }
229
+ if (!tables.has('records') || !tables.has('events')) {
230
+ throw coded(DB_FILE + ' 缺表(' + ['records', 'events'].filter((t) => !tables.has(t)).join('、') + '):多半是阶段 1 早期只搬了记录的库。移走它重新迁移,否则记录在库里、事件不在,读一半就断。', 'STORAGE_INCOMPLETE')
231
+ }
232
+ checkFresh(db, dir, tables.has('sources'))
233
+ let recordTexts
234
+ let eventRows
235
+ try {
236
+ db.exec('BEGIN')
237
+ try {
238
+ recordTexts = db.prepare('SELECT json FROM records ORDER BY rowid').all().map((r) => r.json)
239
+ eventRows = db.prepare('SELECT kind, json FROM events ORDER BY seq').all()
240
+ db.exec('COMMIT')
241
+ } catch (error) {
242
+ try { db.exec('ROLLBACK') } catch { }
243
+ throw error
244
+ }
245
+ } catch (error) { throw unreadable(error) }
246
+ const snap = emptySnapshot()
247
+ snap.records = parseColumn(recordTexts)
248
+ const texts = {}
249
+ for (const k of KIND_NAMES) texts[k] = []
250
+ // 不认识的事件种类(更新版本写进来的):契约里新增事件类型算兼容,这里不认识就不读,也不当坏行
251
+ for (const r of eventRows) if (texts[r.kind]) texts[r.kind].push(r.json)
252
+ for (const k of KIND_NAMES) snap.events[k] = parseColumn(texts[k], EVENT_KINDS[k].valid)
253
+ return snap
254
+ } finally {
255
+ try { db.close() } catch { }
256
+ }
257
+ }
258
+
259
+ function unreadable(cause) {
260
+ const error = coded('记忆库读不出来(' + DB_FILE + '):' + String(cause && cause.message ? cause.message : cause), 'STORAGE_UNREADABLE')
261
+ error.cause = cause
262
+ return error
263
+ }
264
+
265
+ // 只追加的文件,追加就一定变长:字节数对不上 = 迁移之后又写过(或被换过)。
266
+ // 库不是迁移来的(没有 sources)时,目录里任何 JSONL 数据都没进库,同样算对不上。
267
+ function checkFresh(db, dir, hasSources) {
268
+ const recorded = new Map()
269
+ if (hasSources) {
270
+ for (const r of db.prepare('SELECT file, size FROM sources').all()) recorded.set(r.file, Number(r.size))
271
+ }
272
+ const now = sourceSizes(dir)
273
+ const changed = SOURCE_FILES.filter((name) => now[name] !== (recorded.get(name) ?? 0))
274
+ if (changed.length) {
275
+ throw coded('memory.sqlite 和目录里的 JSONL 对不上:' + changed.join('、') + ' 在迁移之后变了(写路径还在 JSONL 上)。sqlite 读出来会少东西,所以拒绝;重新迁移,或继续用 file 后端。', 'STORAGE_STALE', { files: changed })
276
+ }
277
+ }
278
+
279
+ /** 某一类事件(按追加顺序)。坏行与不合格行计数,交给调用方决定要不要 fail closed。 */
280
+ export function readEvents(db, kind) {
281
+ const k = kindOf(kind)
282
+ const texts = db.prepare('SELECT json FROM events WHERE kind = ? ORDER BY seq').all(kind).map((r) => r.json)
283
+ return parseColumn(texts, k.valid)
284
+ }
285
+
286
+ /** 全部记录(按写入顺序),坏行计数。 */
287
+ export function readRecords(db) {
288
+ return parseColumn(db.prepare('SELECT json FROM records ORDER BY rowid').all().map((r) => r.json))
289
+ }
@@ -0,0 +1,39 @@
1
+ // 存储后端接口(阶段 1)
2
+ //
3
+ // 目的:把「记录存在哪」和「记录长什么样」分开。契约(docs/contract-v1-zh.md)
4
+ // 说记录不可变、追加写;引擎换成 SQLite 也不该改变契约里的任何一条。
5
+ //
6
+ // 两个后端都接管经历记录和六类事件(改主意/封存/想起/未完成/联想/章节):
7
+ // append / appendEvent / events / all / byId / byDay / count;sqlite 另有 appendWithEvents 与 transaction。
8
+ // 上层的写路径(addExperience 等)还没接到这里,仍直接写 JSONL——见 docs/storage-backend-zh.md 第六节。
9
+
10
+ /** @typedef {{ id: string, at: string, day: string, then: object, [k: string]: any }} Record */
11
+
12
+ /**
13
+ * 后端能力。调用方可以据此决定能不能依赖事务。
14
+ * @typedef {{ transactions: boolean, wal: boolean, engine: 'file'|'sqlite' }} Capabilities
15
+ */
16
+
17
+ /**
18
+ * 打开一个后端。
19
+ * @param {{ kind?: 'file'|'sqlite', dir: string }} options
20
+ */
21
+ export async function openBackend({ kind = 'file', dir } = {}) {
22
+ if (!dir) throw new Error('openBackend 需要 dir')
23
+ const name = String(kind || 'file')
24
+ if (name === 'file') {
25
+ const { FileBackend } = await import('./file-backend.js')
26
+ return new FileBackend(dir)
27
+ }
28
+ if (name === 'sqlite') {
29
+ const { SqliteBackend } = await import('./sqlite-backend.js')
30
+ return new SqliteBackend(dir)
31
+ }
32
+ throw new Error('未知的存储后端:' + name + '(支持 file / sqlite)')
33
+ }
34
+
35
+ /** 把后端里的记录读成一个数组;坏一条就整体失败(fail closed)。 */
36
+ export async function dumpRecords(backend) {
37
+ const rows = await backend.all()
38
+ return rows
39
+ }
@@ -0,0 +1,119 @@
1
+ // 文件后端:就是现在的 self-experience.jsonl + 各类事件 JSONL。行为与既有实现一致,
2
+ // 只是把「读整个文件」包成一个对象,方便和 SQLite 后端对拍。
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { withFileLock } from '../file-lock.js'
6
+ import { kindOf } from '../sqlite-store.js'
7
+
8
+ const FILE = 'self-experience.jsonl'
9
+
10
+ // 追加一行:末尾没换行先补一个(和各事件模块的写法一致)
11
+ function appendLine(file, value) {
12
+ const fd = fs.openSync(file, 'a+')
13
+ try {
14
+ const size = fs.fstatSync(fd).size
15
+ let separator = ''
16
+ if (size) {
17
+ const last = Buffer.alloc(1)
18
+ fs.readSync(fd, last, 0, 1, size - 1)
19
+ if (last[0] !== 10) separator = '\n'
20
+ }
21
+ fs.writeFileSync(fd, separator + JSON.stringify(value) + '\n', 'utf8')
22
+ } finally {
23
+ fs.closeSync(fd)
24
+ }
25
+ }
26
+
27
+ // 读一个 JSONL:坏行(含不合格行)直接抛错——展示路径不许把坏行当空。
28
+ // 坏行的口径必须和 loadAll 一模一样:trim 只用来跳过空行,解析的是**原样那一行**。
29
+ // 先 trim 再解析会把 BOM / 全角空格 / NBSP 包着的行救活,而 loadAll 把它当坏行——迁移就会把坏行搬进库。
30
+ function readLines(file, valid = null) {
31
+ let raw
32
+ try {
33
+ raw = fs.readFileSync(file, 'utf8')
34
+ } catch (error) {
35
+ if (error && error.code === 'ENOENT') return []
36
+ throw error
37
+ }
38
+ const out = []
39
+ const lines = raw.split('\n')
40
+ for (let i = 0; i < lines.length; i += 1) {
41
+ const line = lines[i]
42
+ if (!line.trim()) continue
43
+ let r
44
+ try {
45
+ r = JSON.parse(line)
46
+ } catch {
47
+ throw new Error(`${path.basename(file)} 第 ${i + 1} 行不是合法 JSON(拒绝当作空)`)
48
+ }
49
+ if (valid && !valid(r)) throw new Error(`${path.basename(file)} 第 ${i + 1} 行缺必填字段(拒绝当作空)`)
50
+ out.push(r)
51
+ }
52
+ return out
53
+ }
54
+
55
+ export class FileBackend {
56
+ /** @param {string} dir */
57
+ constructor(dir) {
58
+ this.dir = dir
59
+ this.kind = 'file'
60
+ this.capabilities = { transactions: false, wal: false, engine: 'file' }
61
+ this.file = path.join(dir, FILE)
62
+ }
63
+
64
+ /** @param {object} record */
65
+ async append(record) {
66
+ fs.mkdirSync(this.dir, { recursive: true })
67
+ appendLine(this.file, record)
68
+ return record
69
+ }
70
+
71
+ /**
72
+ * 追加一条事件到它自己的 JSONL(原样一行,不改形状),和各事件模块用同一把锁。
73
+ * mustExist:先确认指向的经历都在(联想两头都查;章节不指向经历,不查)。
74
+ * 文件后端没有事务,查和写之间不是原子的——要原子请用 sqlite 后端。
75
+ */
76
+ async appendEvent(kind, row, { mustExist = false } = {}) {
77
+ const k = kindOf(kind)
78
+ if (!k.valid(row)) throw new Error(kind + ' 事件不合格(缺必填字段),拒绝写入')
79
+ if (mustExist) {
80
+ const ids = new Set((await this.all()).map((r) => r && r.id))
81
+ const missing = k.expIds(row).filter((id) => !ids.has(id))
82
+ if (missing.length) throw new Error('找不到这条经历:' + missing.join('、') + '(事件没有写入)')
83
+ }
84
+ fs.mkdirSync(this.dir, { recursive: true })
85
+ const file = path.join(this.dir, k.file)
86
+ withFileLock(file + '.lock', () => appendLine(file, row))
87
+ return row
88
+ }
89
+
90
+ /** 全部记录。坏行直接抛错——展示路径不许把坏行当空。 */
91
+ async all() {
92
+ return readLines(this.file)
93
+ }
94
+
95
+ /** 某一类事件,按文件顺序。坏行、不合格行直接抛错。 */
96
+ async events(kind) {
97
+ const k = kindOf(kind)
98
+ return readLines(path.join(this.dir, k.file), k.valid)
99
+ }
100
+
101
+ /** @param {string} id */
102
+ async byId(id) {
103
+ const rows = await this.all()
104
+ return rows.find((r) => r && r.id === id) || null
105
+ }
106
+
107
+ /** 按本地日取:文件后端没有索引,走全量过滤 */
108
+ async byDay(day) {
109
+ return (await this.all()).filter((r) => r && r.day === String(day))
110
+ }
111
+
112
+ async count() {
113
+ return (await this.all()).length
114
+ }
115
+
116
+ async close() {
117
+ /* 文件后端没有连接要关 */
118
+ }
119
+ }