whale-memory-core 0.22.0 → 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.
@@ -29,6 +29,10 @@ export interface Chapter {
29
29
  export function eventsFile(memDir: string): string
30
30
  export function readAll(memDir: string): { rows: ChapterEvent[]; bad: number }
31
31
  export function chapters(memDir: string, opts?: { until?: number | null }): Chapter[]
32
+ /** 同 chapters,但输入是已经读出的行(不碰文件) */
33
+ export function chapterRows(rows: ChapterEvent[], opts?: { until?: number | null }): Chapter[]
34
+ /** 一行算不算合格的章节事件(文件与 SQLite 同一条判据) */
35
+ export function isValid(row: unknown): boolean
32
36
  /** 这一天落在哪些章节里(章节可以重叠) */
33
37
  export function chaptersOn(list: Chapter[], day: string): Chapter[]
34
38
  /** from 默认今天;同名同起点重复提交是 noop */
@@ -6,7 +6,9 @@ import { createLog, stamp } from './event-log.js'
6
6
  import { before, parseAsOf } from './as-of.js'
7
7
 
8
8
  export const ACTIONS = new Set(['open', 'rename', 'close'])
9
- const log = createLog('chapter-events.jsonl', { valid: (r) => Boolean(r.id && ACTIONS.has(r.action)) })
9
+ // 一行算不算合格的章节事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
10
+ export const isValid = (r) => Boolean(r && r.id && ACTIONS.has(r.action))
11
+ const log = createLog('chapter-events.jsonl', { valid: isValid })
10
12
  export const eventsFile = log.eventsFile
11
13
  export const readAll = log.readAll
12
14
  export const internals = { FILE: log.FILE }
@@ -30,8 +32,13 @@ function checkDay(v, label) {
30
32
 
31
33
  // 重放事件,得到每个章节现在(或截至 until)的样子
32
34
  export function chapters(memDir, { until = null } = {}) {
35
+ return chapterRows(readAll(memDir).rows, { until })
36
+ }
37
+
38
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
39
+ export function chapterRows(rows, { until = null } = {}) {
33
40
  const map = new Map()
34
- for (const r of readAll(memDir).rows) {
41
+ for (const r of rows) {
35
42
  if (!before(r, until)) continue
36
43
  if (r.action === 'open') map.set(r.id, { id: r.id, name: r.name, names: [r.name], from: r.from, to: r.to || '', note: r.note || '', openedAt: r.at })
37
44
  const c = map.get(r.id)
@@ -17,6 +17,11 @@ export function readAll(memDir: string): { rows: LaterEvent[]; bad: number }
17
17
  /** until:只要这一刻(毫秒时间戳)之前(含)的后记 */
18
18
  export function groupByExp(memDir: string, opts?: { until?: number | null }): Map<string, LaterEvent[]>
19
19
 
20
+ /** 同 groupByExp,但输入是已经读出的行(不碰文件) */
21
+ export function groupRows(rows: LaterEvent[], opts?: { until?: number | null }): Map<string, LaterEvent[]>
22
+ /** 一行算不算合格的后记事件(文件与 SQLite 同一条判据) */
23
+ export function isValid(row: unknown): boolean
24
+
20
25
  export function list(memDir: string, opts?: { id?: string; limit?: number }): LaterEvent[]
21
26
 
22
27
  export const internals: { FILE: string }
@@ -62,16 +62,25 @@ export function readAll(memDir) {
62
62
  if (!line.trim()) continue
63
63
  try {
64
64
  const r = JSON.parse(line)
65
- if (r && r.id && r.thought) rows.push(r)
65
+ if (isValid(r)) rows.push(r)
66
66
  else bad += 1
67
67
  } catch { bad += 1 }
68
68
  }
69
69
  return { rows, bad }
70
70
  }
71
71
 
72
+ // 一行算不算合格的后记事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
73
+ export function isValid(r) {
74
+ return Boolean(r && r.id && r.thought)
75
+ }
76
+
72
77
  // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
73
78
  export function groupByExp(memDir, { until = null } = {}) {
74
- const { rows } = readAll(memDir)
79
+ return groupRows(readAll(memDir).rows, { until })
80
+ }
81
+
82
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端从库里读出事件后走这里
83
+ export function groupRows(rows, { until = null } = {}) {
75
84
  const map = new Map()
76
85
  for (const r of rows) {
77
86
  if (!before(r, until)) continue
@@ -12,4 +12,8 @@ export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
12
12
  export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
13
  /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
14
  export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
+ /** 同 linksByExp,但输入是已经读出的行(不碰文件) */
16
+ export function linksRows(rows: LinkEvent[], opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
17
+ /** 一行算不算合格的联想事件(文件与 SQLite 同一条判据) */
18
+ export function isValid(row: unknown): boolean
15
19
  export const internals: { FILE: string }
@@ -4,7 +4,9 @@
4
4
  import { createLog, stamp } from './event-log.js'
5
5
  import { before } from './as-of.js'
6
6
 
7
- const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
7
+ // 一行算不算合格的联想事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
8
+ export const isValid = (r) => Boolean(r && r.from && r.to && r.reason)
9
+ const log = createLog('link-events.jsonl', { valid: isValid })
8
10
  export const eventsFile = log.eventsFile
9
11
  export const readAll = log.readAll
10
12
  export const internals = { FILE: log.FILE }
@@ -22,9 +24,14 @@ export function link(memDir, { from, to, reason }, opts = {}) {
22
24
 
23
25
  // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
26
  export function linksByExp(memDir, { until = null } = {}) {
27
+ return linksRows(readAll(memDir).rows, { until })
28
+ }
29
+
30
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
31
+ export function linksRows(rows, { until = null } = {}) {
25
32
  const map = new Map()
26
33
  const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
- for (const r of readAll(memDir).rows) {
34
+ for (const r of rows) {
28
35
  if (!before(r, until)) continue
29
36
  push(r.from, r.to, r)
30
37
  push(r.to, r.from, r)
@@ -20,6 +20,11 @@ export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
20
20
  /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
21
  export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
22
 
23
+ /** 同 countByExp,但输入是已经读出的行(不碰文件、不走缓存) */
24
+ export function countRows(rows: RecallEvent[], opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
25
+ /** 一行算不算合格的想起事件(文件与 SQLite 同一条判据) */
26
+ export function isValid(row: unknown): boolean
27
+
23
28
  export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
29
 
25
30
  export const internals: { FILE: string }
@@ -65,13 +65,18 @@ export function readAll(memDir) {
65
65
  if (!line.trim()) continue
66
66
  try {
67
67
  const r = JSON.parse(line)
68
- if (r && r.id) rows.push(r)
68
+ if (isValid(r)) rows.push(r)
69
69
  else bad += 1
70
70
  } catch { bad += 1 }
71
71
  }
72
72
  return { rows, bad }
73
73
  }
74
74
 
75
+ // 一行算不算合格的想起事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
76
+ export function isValid(r) {
77
+ return Boolean(r && r.id)
78
+ }
79
+
75
80
  // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
76
81
  const memo = new Map()
77
82
 
@@ -83,7 +88,13 @@ export function countByExp(memDir, { until = null } = {}) {
83
88
  const hit = until === null ? memo.get(memDir) : null
84
89
  if (hit && hit.stamp === stamp) return hit.map
85
90
 
86
- const { rows } = readAll(memDir)
91
+ const map = countRows(readAll(memDir).rows, { until })
92
+ if (until === null) memo.set(memDir, { stamp, map })
93
+ return map
94
+ }
95
+
96
+ // 同上,但输入是已经读出来的行(不碰文件、不走缓存):SQLite 后端走这里
97
+ export function countRows(rows, { until = null } = {}) {
87
98
  const map = new Map()
88
99
  for (const r of rows) {
89
100
  if (!before(r, until)) continue
@@ -92,7 +103,6 @@ export function countByExp(memDir, { until = null } = {}) {
92
103
  if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
93
104
  map.set(r.id, cur)
94
105
  }
95
- if (until === null) memo.set(memDir, { stamp, map })
96
106
  return map
97
107
  }
98
108
 
@@ -22,4 +22,8 @@ export function decide(memDir: string, opts: { id: string; action: SealAction; n
22
22
  export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
23
23
  /** 现在(或截至 until)仍封存着的经历;strict 时坏行会抛 SEAL_EVENTS_CORRUPT */
24
24
  export function sealedByExp(memDir: string, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
25
+ /** 同 sealedByExp,但输入是已经读出的 { rows, bad }(不碰文件);strict 时坏行同样抛 */
26
+ export function sealedFrom(read: { rows: SealEvent[]; bad: number }, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
27
+ /** 一行算不算合格的封存事件(文件与 SQLite 同一条判据) */
28
+ export function isValid(row: unknown): boolean
25
29
  export const internals: { FILE: string }
@@ -72,18 +72,27 @@ export function readAll(memDir) {
72
72
  if (!line.trim()) continue
73
73
  try {
74
74
  const r = JSON.parse(line)
75
- if (r && r.id && ACTIONS.has(r.action)) rows.push(r)
75
+ if (isValid(r)) rows.push(r)
76
76
  else bad += 1
77
77
  } catch { bad += 1 }
78
78
  }
79
79
  return { rows, bad }
80
80
  }
81
81
 
82
+ // 一行算不算合格的封存事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
83
+ export function isValid(r) {
84
+ return Boolean(r && r.id && ACTIONS.has(r.action))
85
+ }
86
+
82
87
  // 每个经历 id 现在是否封存着:只收最后一次是 seal 的;until 用于翻回那天(那时还没封存就不算)
83
88
  // strict:展示路径用。日志里有坏行时"某条经历唯一一次封存"可能正好坏掉,
84
89
  // 这时不能默认可见——把"状态未知"抛给调用方(fail closed)。
85
90
  export function sealedByExp(memDir, { until = null, strict = false } = {}) {
86
- const { rows, bad } = readAll(memDir)
91
+ return sealedFrom(readAll(memDir), { until, strict })
92
+ }
93
+
94
+ // 同上,但输入是已经读出来的 { rows, bad }(不碰文件):SQLite 后端走这里,坏行同样 fail closed
95
+ export function sealedFrom({ rows, bad }, { until = null, strict = false } = {}) {
87
96
  if (strict && bad > 0) {
88
97
  const error = new Error('封存日志有 ' + bad + ' 行无法解析,封存状态不确定')
89
98
  error.code = 'SEAL_EVENTS_CORRUPT'
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,206 @@
1
+ // SQLite 后端(阶段 1):用 Node 内置的 node:sqlite,不引入依赖。
2
+ //
3
+ // 要求 Node >= 22.5(node:sqlite 自 22.5 起可用)。拿不到 node:sqlite 时直接报错,
4
+ // 由调用方显式退回 file 后端——不装依赖、不静默降级。
5
+ //
6
+ // 两张数据表:records(id 主键 + day 索引 + 整行 json)和 events(seq 自增 + kind/exp_id 索引 + 整行 json)。
7
+ // 记录与事件都是不可变的,所以没有 UPDATE;换引擎不改变契约里的任何一条。
8
+ // 表结构、读写的同步内核在 ../sqlite-store.js(loadAll 是同步 API,要和这里共用同一份)。
9
+ //
10
+ // 事务的规矩(一个后端对象只有一条连接):
11
+ // · 同一时刻只有一个事务。别的调用方(不在这个事务的调用链里)的读写一律排队,等它结束——
12
+ // 不会悄悄并进别人的事务、跟着别人一起回滚,也读不到别人还没提交的东西;
13
+ // · 在事务自己的调用链里(transaction(fn) 的 fn 以及它 await 的一切):写入直接进这个事务;
14
+ // appendWithEvents / appendEvent / 嵌套的 transaction() 各自包一层 SAVEPOINT,
15
+ // 失败只撤掉自己这一组,外层可以接住错误继续;
16
+ // · 同一个事务里别并发跑两个嵌套分组(Promise.all 两个嵌套 transaction):SAVEPOINT 是栈,交错会乱。
17
+ import path from 'node:path'
18
+ import { AsyncLocalStorage } from 'node:async_hooks'
19
+ import { DB_FILE, requireSqlite, openDatabase, insertRecord, insertEvent, recordExists, readEvents, readRecords, kindOf } from '../sqlite-store.js'
20
+
21
+ export class SqliteBackend {
22
+ #als = new AsyncLocalStorage()
23
+ #tail = Promise.resolve()
24
+ #savepoints = 0
25
+
26
+ /** @param {string} dir */
27
+ constructor(dir) {
28
+ // 在 openBackend 这一步就报错:文档里「try sqlite / catch 退回 file」的写法才真的接得住
29
+ requireSqlite()
30
+ this.dir = dir
31
+ this.kind = 'sqlite'
32
+ this.file = path.join(dir, DB_FILE)
33
+ this.db = null
34
+ this.capabilities = { transactions: true, wal: true, engine: 'sqlite' }
35
+ }
36
+
37
+ /** 当前调用是不是在本对象正在进行的事务的调用链里 */
38
+ get inTransaction() {
39
+ return this.#als.getStore() === this
40
+ }
41
+
42
+ #open() {
43
+ if (!this.db) this.db = openDatabase(this.dir, { create: true })
44
+ return this.db
45
+ }
46
+
47
+ // 排队:同一时刻只跑一个(事务,或一次事务外的读写)
48
+ async #exclusive(task) {
49
+ const prev = this.#tail
50
+ let release
51
+ this.#tail = new Promise((resolve) => { release = resolve })
52
+ try {
53
+ await prev
54
+ return await task()
55
+ } finally {
56
+ release()
57
+ }
58
+ }
59
+
60
+ // 事务外:排队后自己开一个事务;事务里:直接跑
61
+ async #run(fn) {
62
+ if (this.inTransaction) return fn(this.#open())
63
+ return this.#exclusive(async () => fn(this.#open()))
64
+ }
65
+
66
+ // 一组同步写入要么全成、要么全不成:事务里用 SAVEPOINT,事务外用 BEGIN IMMEDIATE
67
+ #group(db, fn) {
68
+ if (this.inTransaction) {
69
+ const sp = 'wm_sp_' + (++this.#savepoints)
70
+ db.exec('SAVEPOINT ' + sp)
71
+ try {
72
+ const result = fn()
73
+ db.exec('RELEASE ' + sp)
74
+ return result
75
+ } catch (error) {
76
+ db.exec('ROLLBACK TO ' + sp)
77
+ db.exec('RELEASE ' + sp)
78
+ throw error
79
+ }
80
+ }
81
+ db.exec('BEGIN IMMEDIATE')
82
+ try {
83
+ const result = fn()
84
+ db.exec('COMMIT')
85
+ return result
86
+ } catch (error) {
87
+ db.exec('ROLLBACK')
88
+ throw error
89
+ }
90
+ }
91
+
92
+ /** @param {object} record */
93
+ async append(record) {
94
+ return this.#run((db) => insertRecord(db, record))
95
+ }
96
+
97
+ /**
98
+ * 追加一条事件(原样存这一行的 JSON,不改形状)。
99
+ * mustExist:先确认这条事件指向的经历都在库里(联想两头都查;章节不指向经历,不查);查和写在同一个事务里。
100
+ * 这是低层追加:不做「重复封存算 noop」这类业务判断,那些在上层。
101
+ */
102
+ async appendEvent(kind, row, { mustExist = false } = {}) {
103
+ const k = kindOf(kind)
104
+ return this.#run((db) => this.#group(db, () => {
105
+ if (mustExist && k.valid(row)) {
106
+ const missing = k.expIds(row).filter((id) => !recordExists(db, id))
107
+ if (missing.length) throw new Error('找不到这条经历:' + missing.join('、') + '(事件没有写入)')
108
+ }
109
+ return insertEvent(db, kind, row)
110
+ }))
111
+ }
112
+
113
+ /**
114
+ * 一条经历 + 它的若干事件,同一个事务写:任何一条失败(重复 id、事件不合格),整组都不落盘。
115
+ * 在 transaction() 里调用时同样成立(这一组包在 SAVEPOINT 里)。
116
+ * @param {object} record
117
+ * @param {{ kind: string, row: object }[]} events
118
+ */
119
+ async appendWithEvents(record, events = []) {
120
+ return this.#run((db) => this.#group(db, () => {
121
+ insertRecord(db, record)
122
+ for (const e of events) insertEvent(db, e && e.kind, e && e.row)
123
+ return record
124
+ }))
125
+ }
126
+
127
+ async all() {
128
+ return this.#run((db) => {
129
+ const { rows, bad } = readRecords(db)
130
+ // 坏数据整体失败,不当空
131
+ if (bad) throw new Error('memory.sqlite 里有 ' + bad + ' 条记录解析不了(拒绝当作空)')
132
+ return rows
133
+ })
134
+ }
135
+
136
+ /** 某一类事件,按追加顺序。坏行整体失败,不当空。 */
137
+ async events(kind) {
138
+ kindOf(kind)
139
+ return this.#run((db) => {
140
+ const { rows, bad } = readEvents(db, kind)
141
+ if (bad) throw new Error('memory.sqlite 里 ' + kind + ' 事件有 ' + bad + ' 条解析不了或不合格(拒绝当作空)')
142
+ return rows
143
+ })
144
+ }
145
+
146
+ /** @param {string} id */
147
+ async byId(id) {
148
+ return this.#run((db) => {
149
+ const row = db.prepare('SELECT json FROM records WHERE id = ?').get(String(id))
150
+ return row ? JSON.parse(row.json) : null
151
+ })
152
+ }
153
+
154
+ /** 按本地日取(契约里的 day 语义)。 */
155
+ async byDay(day) {
156
+ return this.#run((db) => db.prepare('SELECT json FROM records WHERE day = ? ORDER BY rowid').all(String(day)).map((r) => JSON.parse(r.json)))
157
+ }
158
+
159
+ async count() {
160
+ return this.#run((db) => db.prepare('SELECT COUNT(*) AS c FROM records').get().c)
161
+ }
162
+
163
+ /**
164
+ * 事务里跑一段(记录与事件都在同一个事务里)。失败自动回滚。
165
+ * 嵌套调用(在 fn 里再 transaction)是一层 SAVEPOINT:内层失败只撤内层,错误照常抛给外层。
166
+ */
167
+ async transaction(fn) {
168
+ if (this.inTransaction) {
169
+ const db = this.#open()
170
+ const sp = 'wm_sp_' + (++this.#savepoints)
171
+ db.exec('SAVEPOINT ' + sp)
172
+ try {
173
+ const result = await fn(this)
174
+ db.exec('RELEASE ' + sp)
175
+ return result
176
+ } catch (error) {
177
+ db.exec('ROLLBACK TO ' + sp)
178
+ db.exec('RELEASE ' + sp)
179
+ throw error
180
+ }
181
+ }
182
+ return this.#exclusive(async () => {
183
+ const db = this.#open()
184
+ db.exec('BEGIN IMMEDIATE')
185
+ try {
186
+ const result = await this.#als.run(this, () => fn(this))
187
+ db.exec('COMMIT')
188
+ return result
189
+ } catch (error) {
190
+ db.exec('ROLLBACK')
191
+ throw error
192
+ }
193
+ })
194
+ }
195
+
196
+ async close() {
197
+ // 事务里关连接会让外层事务永远等不到自己(排队等的正是它):直接拒绝
198
+ if (this.inTransaction) throw new Error('事务进行中不能 close()')
199
+ return this.#exclusive(async () => {
200
+ if (this.db) {
201
+ this.db.close()
202
+ this.db = null
203
+ }
204
+ })
205
+ }
206
+ }
@@ -26,4 +26,8 @@ export function decide(memDir: string, opts: { id: string; choice: UnfinishedCho
26
26
  export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
27
27
  /** until:按这一刻(毫秒时间戳)之前(含)的选择重放 */
28
28
  export function latestByExp(memDir: string, opts?: { until?: number | null }): Map<string, UnfinishedLatest>
29
+ /** 同 latestByExp,但输入是已经读出的行(不碰文件) */
30
+ export function latestRows(rows: UnfinishedEvent[], opts?: { until?: number | null }): Map<string, UnfinishedLatest>
31
+ /** 一行算不算合格的「没弄完」事件(文件与 SQLite 同一条判据) */
32
+ export function isValid(row: unknown): boolean
29
33
  export function countByExp(memDir: string): Map<string, number>
@@ -82,17 +82,26 @@ export function readAll(memDir) {
82
82
  if (!line.trim()) continue
83
83
  try {
84
84
  const r = JSON.parse(line)
85
- if (r && r.id && CHOICES.has(r.choice)) rows.push(r)
85
+ if (isValid(r)) rows.push(r)
86
86
  else bad += 1
87
87
  } catch { bad += 1 }
88
88
  }
89
89
  return { rows, bad }
90
90
  }
91
91
 
92
+ // 一行算不算合格的「没弄完」事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
93
+ export function isValid(r) {
94
+ return Boolean(r && r.id && CHOICES.has(r.choice))
95
+ }
96
+
92
97
  // 每个经历 id 的最新状态,附带完整的选择历史(渲染"中间放下过"要用)
93
98
  // until:按这一刻之前(含)的选择重放,「翻回那天的自己」用
94
99
  export function latestByExp(memDir, { until = null } = {}) {
95
- const { rows } = readAll(memDir)
100
+ return latestRows(readAll(memDir).rows, { until })
101
+ }
102
+
103
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
104
+ export function latestRows(rows, { until = null } = {}) {
96
105
  const map = new Map()
97
106
  for (const r of rows) {
98
107
  if (!before(r, until)) continue
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -136,7 +136,10 @@
136
136
  "./injection": {
137
137
  "types": "./lib/injection.d.ts",
138
138
  "default": "./lib/injection.js"
139
- }
139
+ },
140
+ "./storage/backend": "./lib/storage/backend.js",
141
+ "./storage/file-backend": "./lib/storage/file-backend.js",
142
+ "./storage/sqlite-backend": "./lib/storage/sqlite-backend.js"
140
143
  },
141
144
  "files": [
142
145
  "index.js",