whale-memory-core 0.21.1 → 0.23.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,192 @@
1
+ // 自主行动日志(self-actions):角色做过什么,以及这件事是谁发起的。
2
+ //
3
+ // 这一层只存事实,不做判断:
4
+ // · 动作是不是"她自己发起的",由调用方声明(source),这里不推断;
5
+ // · 结果好不好,由调用方声明(outcome);
6
+ // · 触发文本一个字都不存 —— 短句的哈希等于明文("第三章""继续"一查就知道)。
7
+ // 需要留痕时,调用方自己算 HMAC 再传 triggerDigest。
8
+ //
9
+ // 存储是只追加的一行一条 JSONL:写坏了只坏一行,历史不会被重写。
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+
13
+ import { withFileLock } from './file-lock.js'
14
+
15
+ export const FILE_NAME = 'self-actions.jsonl'
16
+ export const DEFAULT_MAX_LINES = 5000
17
+ export const SOURCES = Object.freeze(['asked', 'self', 'unknown'])
18
+ const LOCK_TIMEOUT_MS = 2000
19
+ const LOCKED_MESSAGE = 'The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)'
20
+
21
+ function fail(code, extra = {}) {
22
+ return { ok: false, code, ...extra }
23
+ }
24
+
25
+ function dayOf(at) {
26
+ return new Date(Number(at) || 0).toLocaleDateString('sv-SE')
27
+ }
28
+
29
+ function normalizeOutcome(value) {
30
+ const text = String(value ?? '').trim().toLowerCase()
31
+ return /^[a-z][a-z0-9_]{0,23}$/.test(text) ? text : 'unknown'
32
+ }
33
+
34
+ function appendLine(file, line) {
35
+ const fd = fs.openSync(file, 'a')
36
+ try {
37
+ // 末尾停在半行时先补换行:否则新行会粘在坏行后面,读的时候整行报废
38
+ const size = fs.fstatSync(fd).size
39
+ if (size > 0) {
40
+ const rfd = fs.openSync(file, 'r')
41
+ try {
42
+ const last = Buffer.alloc(1)
43
+ fs.readSync(rfd, last, 0, 1, size - 1)
44
+ if (last[0] !== 0x0a) fs.writeSync(fd, '\n')
45
+ } finally {
46
+ fs.closeSync(rfd)
47
+ }
48
+ }
49
+ const buf = Buffer.from(line, 'utf8')
50
+ let offset = 0
51
+ while (offset < buf.length) offset += fs.writeSync(fd, buf, offset, buf.length - offset)
52
+ fs.fsyncSync(fd)
53
+ } finally {
54
+ fs.closeSync(fd)
55
+ }
56
+ }
57
+
58
+ function readRows(file) {
59
+ let raw = ''
60
+ try {
61
+ raw = fs.readFileSync(file, 'utf8')
62
+ } catch (error) {
63
+ if (error && error.code === 'ENOENT') return { ok: true, rows: [], corrupt: 0 }
64
+ return fail('storage_error', { error })
65
+ }
66
+ const rows = []
67
+ let corrupt = 0
68
+ for (const line of raw.split('\n')) {
69
+ const trimmed = line.trim()
70
+ if (!trimmed) continue
71
+ try {
72
+ const row = JSON.parse(trimmed)
73
+ if (!row || typeof row !== 'object') throw new Error('bad')
74
+ if (!row.action || !Number.isFinite(Number(row.at))) throw new Error('bad')
75
+ rows.push(row)
76
+ } catch {
77
+ corrupt += 1
78
+ }
79
+ }
80
+ rows.sort((a, b) => Number(a.at) - Number(b.at))
81
+ return { ok: true, rows, corrupt }
82
+ }
83
+
84
+ /**
85
+ * 建一个日志实例。动作白名单由宿主给:不同产品词表不一样,这里不猜。
86
+ *
87
+ * @param {object} options
88
+ * @param {string} options.dir 数据目录
89
+ * @param {string[]} options.actions 允许记录的动作名
90
+ * @param {number} [options.maxLines=5000] 超过就拒绝写入(不裁剪历史)
91
+ */
92
+ export function createSelfActionLog({ dir, actions = [], maxLines = DEFAULT_MAX_LINES } = {}) {
93
+ const base = String(dir || '').trim()
94
+ const whitelist = new Set((Array.isArray(actions) ? actions : []).map((x) => String(x || '').trim()).filter(Boolean))
95
+ const file = path.join(base, FILE_NAME)
96
+ const limit = Number.isFinite(Number(maxLines)) && Number(maxLines) > 0 ? Number(maxLines) : DEFAULT_MAX_LINES
97
+
98
+ /**
99
+ * 记一条。source / outcome 都是调用方声明的,这里不推断。
100
+ *
101
+ * @param {object} input
102
+ * @param {string} input.action
103
+ * @param {'asked'|'self'|'unknown'} [input.source='unknown']
104
+ * @param {string} [input.outcome='ok']
105
+ * @param {string} [input.itemRef] 指向被操作对象的 id(可选)
106
+ * @param {number} [input.triggerLen] 触发文本长度(可选;不存文本本身)
107
+ * @param {string} [input.triggerDigest] 调用方自己算的摘要(可选,建议 HMAC)
108
+ * @param {number} [input.at] 时间戳;测试用
109
+ */
110
+ function record({ action = '', source = 'unknown', outcome = 'ok', itemRef = '', triggerLen, triggerDigest = '', at = Date.now() } = {}) {
111
+ const name = String(action || '').trim()
112
+ if (!base) return fail('invalid_input', { field: 'dir' })
113
+ if (!name) return fail('invalid_input', { field: 'action' })
114
+ if (whitelist.size && !whitelist.has(name)) return fail('invalid_input', { field: 'action', reason: 'not_in_whitelist' })
115
+
116
+ const ts = Number(at)
117
+ if (!Number.isFinite(ts)) return fail('invalid_input', { field: 'at' })
118
+
119
+ const row = {
120
+ v: 1,
121
+ at: ts,
122
+ day: dayOf(ts),
123
+ action: name.slice(0, 40),
124
+ source: SOURCES.includes(source) ? source : 'unknown',
125
+ outcome: normalizeOutcome(outcome),
126
+ ...(itemRef ? { itemRef: String(itemRef).slice(0, 64) } : {}),
127
+ ...(Number.isFinite(Number(triggerLen)) ? { triggerLen: Math.max(0, Math.floor(Number(triggerLen))) } : {}),
128
+ ...(triggerDigest ? { triggerDigest: String(triggerDigest).slice(0, 64) } : {}),
129
+ }
130
+
131
+ try { fs.mkdirSync(base, { recursive: true }) } catch (error) { return fail('storage_error', { error }) }
132
+ try {
133
+ return withFileLock(`${file}.lock`, () => {
134
+ const loaded = readRows(file)
135
+ if (!loaded.ok) return loaded
136
+ if (loaded.rows.length >= limit) return fail('limit', { limit })
137
+ appendLine(file, `${JSON.stringify(row)}\n`)
138
+ return { ok: true }
139
+ }, { timeoutMs: LOCK_TIMEOUT_MS })
140
+ } catch (error) {
141
+ if (String(error && error.message || '') === LOCKED_MESSAGE) return fail('busy')
142
+ return fail('storage_error', { error })
143
+ }
144
+ }
145
+
146
+ /** 读回来。过滤条件都可选;坏行跳过并给 corrupt 计数。 */
147
+ function read({ since, until, action = '', source = '', outcome = '', limit: take = 0 } = {}) {
148
+ const loaded = readRows(file)
149
+ if (!loaded.ok) return loaded
150
+ let rows = loaded.rows
151
+ if (Number.isFinite(Number(since))) rows = rows.filter((r) => Number(r.at) >= Number(since))
152
+ if (Number.isFinite(Number(until))) rows = rows.filter((r) => Number(r.at) <= Number(until))
153
+ if (action) rows = rows.filter((r) => r.action === action)
154
+ if (source) rows = rows.filter((r) => r.source === source)
155
+ if (outcome) rows = rows.filter((r) => r.outcome === outcome)
156
+ const n = Number(take) > 0 ? Number(take) : 0
157
+ const page = n ? rows.slice(-n) : rows
158
+ return { ok: true, total: rows.length, rows: page, corrupt: loaded.corrupt }
159
+ }
160
+
161
+ /** 统计:自己发起 / 被要求 / 无法判断,以及每天各多少。 */
162
+ function summarize({ now = Date.now(), days = 7 } = {}) {
163
+ const end = Number(now)
164
+ const start = end - Math.max(1, Number(days) || 7) * 86400000
165
+ const loaded = read({ since: start, until: end })
166
+ if (!loaded.ok) return loaded
167
+ const bySource = { self: 0, asked: 0, unknown: 0 }
168
+ const byOutcome = {}
169
+ const byAction = {}
170
+ const daily = new Map()
171
+ for (const row of loaded.rows) {
172
+ bySource[row.source] = (bySource[row.source] || 0) + 1
173
+ byOutcome[row.outcome] = (byOutcome[row.outcome] || 0) + 1
174
+ byAction[row.action] = (byAction[row.action] || 0) + 1
175
+ const day = row.day || dayOf(row.at)
176
+ if (!daily.has(day)) daily.set(day, { self: 0, asked: 0, unknown: 0 })
177
+ daily.get(day)[row.source] = (daily.get(day)[row.source] || 0) + 1
178
+ }
179
+ return {
180
+ ok: true,
181
+ windowDays: Math.max(1, Number(days) || 7),
182
+ total: loaded.rows.length,
183
+ bySource,
184
+ byOutcome,
185
+ byAction,
186
+ daily: [...daily.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, counts]) => ({ day, ...counts })),
187
+ corrupt: loaded.corrupt,
188
+ }
189
+ }
190
+
191
+ return { record, read, summarize, file, maxLines: limit }
192
+ }
@@ -83,7 +83,10 @@ export interface Experience {
83
83
 
84
84
  export const LIMITS: Record<string, number>
85
85
 
86
- export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean }): Experience[]
86
+ /** 读哪个容器:file(默认,JSONL)或 sqlite(memory.sqlite;拿不到 node:sqlite、没迁移、迁移后 JSONL 又变过都会抛错,不静默退回 file) */
87
+ export type StorageBackendName = 'file' | 'sqlite'
88
+
89
+ export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean; allowCorrupt?: boolean; backend?: StorageBackendName }): Experience[]
87
90
 
88
91
  /** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
89
92
  export function badLines(dir: string): number
@@ -114,7 +117,7 @@ export function reviseExperience(dir: string, opts: { id: string; thought: strin
114
117
 
115
118
  export function markRecalled(dir: string, id: string): boolean
116
119
 
117
- export function currentView(dir: string, id: string, opts?: { asOf?: AsOf }): Experience | null
120
+ export function currentView(dir: string, id: string, opts?: { asOf?: AsOf; backend?: StorageBackendName }): Experience | null
118
121
 
119
122
  export function recall(dir: string, query: string, opts?: {
120
123
  limit?: number
@@ -128,6 +131,8 @@ export function recall(dir: string, query: string, opts?: {
128
131
  includeSealed?: boolean
129
132
  /** strict 用哪套门槛:cover(默认,0.17 起)或 legacy(0.16 及以前,结果逐条一致) */
130
133
  gate?: 'cover' | 'legacy'
134
+ /** 读哪个容器(默认 file)。sqlite 下不能 mark:写路径还在 JSONL 上 */
135
+ backend?: StorageBackendName
131
136
  }): Experience[]
132
137
 
133
138
  /** 事后联想:两条都必须存在、必须写理由;同一对(不分方向)只连一次 */
@@ -10,6 +10,7 @@ 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
12
  import { parseAsOf, before, dayOf } from './as-of.js'
13
+ import { readSnapshot } from './sqlite-store.js'
13
14
 
14
15
  const FILE = 'self-experience.jsonl'
15
16
  const WEIGHTS = new Set(['important', 'normal', 'minor'])
@@ -152,7 +153,11 @@ function normalize(r) {
152
153
  // 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
153
154
  // strict:展示路径用,坏行直接抛(见 readAll)
154
155
  function identify(dir, { strict = false } = {}) {
155
- const raw = readAll(dir, { strict })
156
+ return identifyRaw(readAll(dir, { strict }))
157
+ }
158
+
159
+ // 同上,输入是已经读出来的 { rows, bad }(文件或 SQLite 都行)
160
+ function identifyRaw(raw) {
156
161
  const rows = raw.rows.map(normalize).filter((r) => r && r.then && r.then.text)
157
162
  const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
158
163
  const owners = new Map()
@@ -190,10 +195,53 @@ const brief = (r) => {
190
195
  // 坏行(self-experience.jsonl 里有解析不了的行)默认 fail closed:返回的部分经历会
191
196
  // 把"少了一条"装成"就这些",召回/书/体检都会当真。要按字节备份、恢复演练、计数这种
192
197
  // 不展示内容的工具,传 allowCorrupt(导出/恢复那条路走 allowSealCorrupt,含义相同)。
193
- export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false } = {}) {
198
+ // 数据从哪来:file(默认,原样走各模块的读文件函数,调用顺序与参数和以前一模一样)
199
+ // 或 sqlite(一次读事务拿到记录 + 六类事件的快照,再走同一套合并逻辑)。
200
+ // 合并逻辑只有一份,所以两个后端在同一份数据上读出来的结果逐条相同。
201
+ const BACKENDS = new Set(['file', 'sqlite'])
202
+
203
+ function backendName(backend) {
204
+ const name = backend === undefined || backend === null || backend === '' ? 'file' : String(backend)
205
+ if (!BACKENDS.has(name)) throw new Error('未知的存储后端:' + name + '(支持 file / sqlite)')
206
+ return name
207
+ }
208
+
209
+ function fileSource(dir) {
210
+ return {
211
+ records: (strict) => readAll(dir, { strict }),
212
+ recalls: (until, onError) => readEvents(dir, recallEvents.eventsFile, () => recallEvents.countByExp(dir, { until }), onError),
213
+ later: (until, onError) => readEvents(dir, laterEvents.eventsFile, () => laterEvents.groupByExp(dir, { until }), onError),
214
+ unfinished: (until, onError) => readEvents(dir, unfinishedEvents.eventsFile, () => unfinishedEvents.latestByExp(dir, { until }), onError),
215
+ sealed: (until, strict) => sealEvents.sealedByExp(dir, { until, strict }),
216
+ links: (until, onError) => readEvents(dir, linkEvents.eventsFile, () => linkEvents.linksByExp(dir, { until }), onError),
217
+ chapters: (until, onError) => readEvents(dir, chapterEvents.eventsFile, () => chapterEvents.chapters(dir, { until }), onError)
218
+ }
219
+ }
220
+
221
+ // 快照在这里一次读完:拿不到 node:sqlite、没迁移、库不全、JSONL 在迁移后又变过,都在这一步抛(见 sqlite-store.readSnapshot)
222
+ function sqliteSource(dir) {
223
+ const snap = readSnapshot(dir)
224
+ const ev = (kind) => snap.events[kind]
225
+ return {
226
+ records: (strict) => {
227
+ if (strict && snap.records.bad > 0) throw experienceCorrupt(snap.records.bad)
228
+ return snap.records
229
+ },
230
+ recalls: (until) => recallEvents.countRows(ev('recall').rows, { until }),
231
+ later: (until) => laterEvents.groupRows(ev('later').rows, { until }),
232
+ unfinished: (until) => unfinishedEvents.latestRows(ev('unfinished').rows, { until }),
233
+ sealed: (until, strict) => sealEvents.sealedFrom(ev('seal'), { until, strict }),
234
+ links: (until) => linkEvents.linksRows(ev('link').rows, { until }),
235
+ chapters: (until) => chapterEvents.chapterRows(ev('chapter').rows, { until })
236
+ }
237
+ }
238
+
239
+ // backend:'file'(默认,零行为变化)或 'sqlite'(读 memory.sqlite,要求 node:sqlite;拿不到就报错,不静默退回 file)
240
+ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false, backend = 'file' } = {}) {
194
241
  const until = parseAsOf(asOf)
195
242
  const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
196
- const { rows: all } = identify(dir, { strict: !rawMode })
243
+ const src = backendName(backend) === 'sqlite' ? sqliteSource(dir) : fileSource(dir)
244
+ const { rows: all } = identifyRaw(src.records(!rawMode))
197
245
  const rows = until === null ? all : all.filter((r) => before(r, until))
198
246
  if (!rows.length) return rows
199
247
 
@@ -201,13 +249,13 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
201
249
  // 读不出来必须报出来(readEvents):否则会当成"她从没想起过"。
202
250
  // rawMode(按字节备份/恢复/计数)不看事件内容,读不出来也不该拦住备份。
203
251
  const onEventError = rawMode ? () => new Map() : null
204
- const counts = readEvents(dir, recallEvents.eventsFile, () => recallEvents.countByExp(dir, { until }), onEventError)
252
+ const counts = src.recalls(until, onEventError)
205
253
 
206
254
  // 改主意:旧 later 数组 + later-events 事件,按时间合并
207
- const laterMap = readEvents(dir, laterEvents.eventsFile, () => laterEvents.groupByExp(dir, { until }), onEventError)
255
+ const laterMap = src.later(until, onEventError)
208
256
 
209
257
  // 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
210
- const unfinishedMap = readEvents(dir, unfinishedEvents.eventsFile, () => unfinishedEvents.latestByExp(dir, { until }), onEventError)
258
+ const unfinishedMap = src.unfinished(until, onEventError)
211
259
 
212
260
  // 她选择封存的:不再被主动想起,但还在。
213
261
  // 读不出来就抛出去,不能当成"什么都没封存"——否则正文可读、日志读不了时,
@@ -215,11 +263,11 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
215
263
  // strict:坏行也算"状态未知",展示路径必须 fail closed。
216
264
  // allowSealCorrupt:只给"按字节备份/恢复/计数"这种不展示内容的工具用;
217
265
  // 它们要能保住损坏现场,但不能把结果当"可见"用。
218
- const sealedMap = sealEvents.sealedByExp(dir, { until, strict: !allowSealCorrupt })
266
+ const sealedMap = src.sealed(until, !allowSealCorrupt)
219
267
  // 翻回那天时,她**现在**封存着的也不翻出来:封存说的是她现在不想被提起,而翻回那天正是在提起旧事。
220
268
  // 那时还没封存的,标成 afterAsOf(后来才封存),各处过滤照常生效;点名读仍然给,并写明是后来封存的
221
269
  let sealedNowMap = sealedMap
222
- if (until !== null) sealedNowMap = sealEvents.sealedByExp(dir, { strict: !allowSealCorrupt })
270
+ if (until !== null) sealedNowMap = src.sealed(null, !allowSealCorrupt)
223
271
 
224
272
  const viewed = rows.map((r) => {
225
273
  const keys = r.formerId ? [r.id, r.formerId] : [r.id]
@@ -292,8 +340,8 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
292
340
  }
293
341
 
294
342
  // 事后联想(两头都看得见)与人生章节(按 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)
343
+ const linkMap = src.links(until, onEventError)
344
+ const chapterList = src.chapters(until, rawMode ? () => [] : null)
297
345
  for (const r of viewed) {
298
346
  const keys = r.formerId ? [r.id, r.formerId] : [r.id]
299
347
  const links = !r.duplicateOf && keys.flatMap((k) => linkMap.get(k) || [])
@@ -496,8 +544,8 @@ export function markRecalled(dir, id) {
496
544
  }
497
545
 
498
546
  // asOf:看那天的这一条(那之后的后记、选择、想起都不算);那天还没写下就返回 null
499
- export function currentView(dir, id, { asOf = null } = {}) {
500
- const rows = loadAll(dir, { asOf })
547
+ export function currentView(dir, id, { asOf = null, backend = 'file' } = {}) {
548
+ const rows = loadAll(dir, { asOf, backend })
501
549
  return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
502
550
  }
503
551
 
@@ -511,9 +559,12 @@ export function currentView(dir, id, { asOf = null } = {}) {
511
559
  // 她封存了的经历不会被召回;includeSealed=true 只给"她自己要翻"这种明确场景用
512
560
  // gate:strict 下用哪套门槛。'cover'(默认,0.17 起)= 至少对上一个词 + 意思至少 70% 被接住;
513
561
  // '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' } = {}) {
562
+ // backend:读哪个容器(默认 file,见 loadAll)。写路径还没切到 sqlite:sqlite 下 mark=true 会把想起记到 JSONL、
563
+ // 库里看不见,所以直接拒绝,不留一笔两边对不上的账
564
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict', asOf = null, includeSealed = false, gate = 'cover', backend = 'file' } = {}) {
515
565
  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)
566
+ 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 后端。)')
567
+ const rows = loadAll(dir, { asOf, backend }).filter((r) => includeSealed || !r.sealed)
517
568
  const q = String(query || '')
518
569
  const parsed = queryTerms(q)
519
570
  const { terms } = parsed
@@ -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
+ }