whale-memory-core 0.24.0 → 0.25.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,85 @@
1
+ // 逐行读 JSONL:不把整个文件读成一个字符串。
2
+ //
3
+ // 为什么要有这个:旧写法是 readFileSync 整读 + split('\n'),十万条时同时占着
4
+ // 「文件字符串 + 切出来的行数组 + 解析后的对象」三份内存,峰值能到几百 MB。
5
+ // 这里按 64KB 块读、按字节找换行,每行单独解码、解析完就丢掉文本。
6
+ //
7
+ // 按字节找换行是安全的:0x0A 不可能出现在多字节 UTF-8 序列的内部(续字节都 ≥ 0x80),
8
+ // 所以「按 0x0A 切字节」和「先整体解码再按 '\n' 切字符串」得到的是同一组行。
9
+ // 唯一差别是文件末尾被截断在多字节字符中间时,最后一行解码成 U+FFFD——和 readFileSync 一样。
10
+ //
11
+ // 同步与异步两条读法共用 lineSplitter:切行口径只写一次。
12
+
13
+ import fs from 'node:fs'
14
+
15
+ export const READ_CHUNK = 64 * 1024
16
+
17
+ // 字节块 → 行。onLine(text, offset, bytes):
18
+ // text 这一行的原样文本(不含换行符;行尾的 \r 保留,和 split('\n') 一致)
19
+ // offset 这一行在文件里的起始字节位置
20
+ // bytes 这一行的字节长度(不含换行符)
21
+ // 注意:push 收到的 chunk 可能被复用,回调里不能把 chunk 存下来(存 text 没问题,它是新字符串)。
22
+ export function lineSplitter(onLine) {
23
+ let pending = Buffer.alloc(0)
24
+ let pendingAt = 0
25
+ return {
26
+ push(chunk, chunkAt) {
27
+ const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk
28
+ let start = 0
29
+ for (;;) {
30
+ const nl = buf.indexOf(10, start)
31
+ if (nl === -1) break
32
+ onLine(buf.toString('utf8', start, nl), pendingAt + start, nl - start)
33
+ start = nl + 1
34
+ }
35
+ // 剩下没换行的一段留到下一块;整块都以换行结尾时 pending 清空
36
+ pending = start >= buf.length ? Buffer.alloc(0) : Buffer.from(buf.subarray(start))
37
+ pendingAt += start
38
+ },
39
+ end() {
40
+ if (!pending.length) return
41
+ const text = pending.toString('utf8')
42
+ const at = pendingAt
43
+ const bytes = pending.length
44
+ pending = Buffer.alloc(0)
45
+ onLine(text, at, bytes)
46
+ }
47
+ }
48
+ }
49
+
50
+ // 同步逐行:调用方自己 open / close(这样"文件不存在"在打开那一步就能报出来,
51
+ // 不会等第一次 next() 才冒出来)。一次只留 64KB 的读缓冲和一行文本。
52
+ export function* readLines(fd) {
53
+ const buf = Buffer.allocUnsafe(READ_CHUNK)
54
+ let lines = []
55
+ const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
56
+ let at = 0
57
+ for (;;) {
58
+ const n = fs.readSync(fd, buf, 0, READ_CHUNK, null)
59
+ if (!n) break
60
+ split.push(buf.subarray(0, n), at)
61
+ at += n
62
+ for (const line of lines) yield line
63
+ lines = []
64
+ }
65
+ split.end()
66
+ for (const line of lines) yield line
67
+ }
68
+
69
+ // 异步逐行:同上,块读走 fs/promises,不把事件循环卡住。
70
+ export async function* readLinesAsync(fh) {
71
+ const buf = Buffer.allocUnsafe(READ_CHUNK)
72
+ let lines = []
73
+ const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
74
+ let at = 0
75
+ for (;;) {
76
+ const { bytesRead } = await fh.read(buf, 0, READ_CHUNK, null)
77
+ if (!bytesRead) break
78
+ split.push(buf.subarray(0, bytesRead), at)
79
+ at += bytesRead
80
+ for (const line of lines) yield line
81
+ lines = []
82
+ }
83
+ split.end()
84
+ for (const line of lines) yield line
85
+ }
@@ -0,0 +1,39 @@
1
+ /** 指标快照:纯数据,可直接 JSON.stringify */
2
+ export interface MetricsSnapshot {
3
+ version: number
4
+ /** 起算时刻(ISO) */
5
+ since: string
6
+ /** 取快照的时刻(ISO) */
7
+ at: string
8
+ writes: { count: number; msTotal: number; msMax: number; msLast: number; msAvg: number }
9
+ recalls: {
10
+ count: number
11
+ hits: number
12
+ msTotal: number
13
+ msMax: number
14
+ msLast: number
15
+ msAvg: number
16
+ lastBackend: 'file' | 'sqlite' | 'other' | ''
17
+ backends: { file: number; sqlite: number; other: number }
18
+ }
19
+ badLines: { last: number; max: number; observations: number }
20
+ }
21
+
22
+ /** 记一次写入(ms:这次写入耗时,毫秒) */
23
+ export function recordWrite(sample?: { ms?: number }): void
24
+ /** 记一次召回(hits:返回条数;backend 只认 file / sqlite,其它一律记成 other) */
25
+ export function recordRecall(sample?: { ms?: number; hits?: number; backend?: string }): void
26
+ /** 记一次坏行观测(n:此刻的坏行数) */
27
+ export function recordBadLines(n?: number): void
28
+ export function snapshot(): MetricsSnapshot
29
+ export function reset(): void
30
+ export const VERSION: number
31
+ /** 进程内单例 */
32
+ export const metrics: {
33
+ recordWrite: typeof recordWrite
34
+ recordRecall: typeof recordRecall
35
+ recordBadLines: typeof recordBadLines
36
+ snapshot: typeof snapshot
37
+ reset: typeof reset
38
+ VERSION: number
39
+ }
package/lib/metrics.js ADDED
@@ -0,0 +1,116 @@
1
+ // 运行时指标:给宿主定期落盘用的几个数字,不记内容。
2
+ //
3
+ // 只存数字和固定枚举(backend 只有 file / sqlite / other 三种取值)。
4
+ // 这里**永远不写正文、查询串、经历 id**:指标常被写进日志、监控、落盘文件,
5
+ // 漏一条正文进去,等于把她的记忆抄了一份到别处。要证明这一点,见
6
+ // tests/metrics-runtime.test.mjs:那组用例会把整份快照序列化后逐字检查。
7
+ //
8
+ // 开销:一次 record* 就是给几个数字加一次,不分配对象、不取时间(耗时由调用方量好传进来);
9
+ // 只有 snapshot() 取一次 Date.now() 并拼出纯对象。时间源只用 Date.now()。
10
+ //
11
+ // 单例:进程内一份(模块级状态)。宿主 fork 出去的子进程各算各的,不跨进程汇总。
12
+ // 叶子模块:不 import 任何其它模块,免得和 self-experience.js 之类形成循环依赖。
13
+
14
+ export const VERSION = 1
15
+
16
+ // 起算时刻:snapshot 里的 since 用它,reset() 时重设
17
+ let startedAt = Date.now()
18
+
19
+ // 一块扁平的数字:观测路径只做 s.x += 1 这种原地加法,不建临时对象
20
+ const s = {
21
+ writes: 0, writeMs: 0, writeMax: 0, writeLast: 0,
22
+ recalls: 0, recallMs: 0, recallMax: 0, recallLast: 0, hits: 0,
23
+ file: 0, sqlite: 0, other: 0, lastBackend: '',
24
+ badLast: 0, badMax: 0, badObservations: 0
25
+ }
26
+
27
+ // 毫秒数:非有限值、负数一律当 0(观测错不能把汇总算成 NaN,落盘就废了)
28
+ function duration(v) {
29
+ const n = Number(v)
30
+ return Number.isFinite(n) && n > 0 ? n : 0
31
+ }
32
+
33
+ function count(v) {
34
+ const n = Number(v)
35
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
36
+ }
37
+
38
+ /** 记一次写入:{ ms } 是这次写入的耗时(毫秒)。 */
39
+ export function recordWrite({ ms } = {}) {
40
+ const d = duration(ms)
41
+ s.writes += 1
42
+ s.writeMs += d
43
+ s.writeLast = d
44
+ if (d > s.writeMax) s.writeMax = d
45
+ }
46
+
47
+ /** 记一次召回:{ ms, hits, backend }。hits 是这次返回的条数,backend 只认 file / sqlite。 */
48
+ export function recordRecall({ ms, hits, backend } = {}) {
49
+ const d = duration(ms)
50
+ s.recalls += 1
51
+ s.recallMs += d
52
+ s.recallLast = d
53
+ if (d > s.recallMax) s.recallMax = d
54
+ s.hits += count(hits)
55
+ // backend 必须是固定枚举:宿主传进来一个像 id 的字符串,也只落成 'other'
56
+ if (backend === 'file') { s.file += 1; s.lastBackend = 'file' }
57
+ else if (backend === 'sqlite') { s.sqlite += 1; s.lastBackend = 'sqlite' }
58
+ else { s.other += 1; s.lastBackend = 'other' }
59
+ }
60
+
61
+ /** 记一次坏行观测:n 是此刻 badLines / 各类事件读出来的坏行数(0 = 这次没有坏行)。 */
62
+ export function recordBadLines(n) {
63
+ const bad = count(n)
64
+ s.badLast = bad
65
+ s.badObservations += 1
66
+ if (bad > s.badMax) s.badMax = bad
67
+ }
68
+
69
+ const round3 = (n) => Math.round(n * 1000) / 1000
70
+ const avg = (total, n) => (n ? round3(total / n) : 0)
71
+
72
+ /**
73
+ * 当前快照:纯对象(数字 + ISO 字符串),可以直接 JSON.stringify 落盘。
74
+ * 每次返回新对象,调用方改它不会影响内部计数。
75
+ */
76
+ export function snapshot() {
77
+ return {
78
+ version: VERSION,
79
+ since: new Date(startedAt).toISOString(),
80
+ at: new Date().toISOString(),
81
+ writes: {
82
+ count: s.writes,
83
+ msTotal: round3(s.writeMs),
84
+ msMax: round3(s.writeMax),
85
+ msLast: round3(s.writeLast),
86
+ msAvg: avg(s.writeMs, s.writes)
87
+ },
88
+ recalls: {
89
+ count: s.recalls,
90
+ hits: s.hits,
91
+ msTotal: round3(s.recallMs),
92
+ msMax: round3(s.recallMax),
93
+ msLast: round3(s.recallLast),
94
+ msAvg: avg(s.recallMs, s.recalls),
95
+ lastBackend: s.lastBackend,
96
+ backends: { file: s.file, sqlite: s.sqlite, other: s.other }
97
+ },
98
+ badLines: {
99
+ last: s.badLast,
100
+ max: s.badMax,
101
+ observations: s.badObservations
102
+ }
103
+ }
104
+ }
105
+
106
+ /** 清回刚启动的样子(测试用;宿主换会话时可以调)。 */
107
+ export function reset() {
108
+ s.writes = 0; s.writeMs = 0; s.writeMax = 0; s.writeLast = 0
109
+ s.recalls = 0; s.recallMs = 0; s.recallMax = 0; s.recallLast = 0; s.hits = 0
110
+ s.file = 0; s.sqlite = 0; s.other = 0; s.lastBackend = ''
111
+ s.badLast = 0; s.badMax = 0; s.badObservations = 0
112
+ startedAt = Date.now()
113
+ }
114
+
115
+ /** 进程内单例:`metrics.recordWrite(...)` 和单独 import 的函数是同一份状态。 */
116
+ export const metrics = Object.freeze({ recordWrite, recordRecall, recordBadLines, snapshot, reset, VERSION })
@@ -88,6 +88,28 @@ export type StorageBackendName = 'file' | 'sqlite'
88
88
 
89
89
  export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean; allowCorrupt?: boolean; backend?: StorageBackendName }): Experience[]
90
90
 
91
+ /**
92
+ * 逐条读:不建全量数组,内存只跟一份小索引走(id / 日子 / 前 24 字 / 封存),产出的每条与 loadAll 逐字段相同。
93
+ * 代价是要把经历文件读两遍(跨行字段要看"别处有哪些 id")。backend='sqlite' 时退回整库快照(结果相同,没有内存收益)。
94
+ * 遍历期间文件被追加 → 抛 EXPERIENCE_CHANGED(不静默少返一条)。
95
+ */
96
+ export function iterate(dir: string, opts?: { asOf?: AsOf; backend?: StorageBackendName; allowCorrupt?: boolean; allowSealCorrupt?: boolean }): AsyncGenerator<Experience, void, unknown>
97
+
98
+ /** 分页游标:after 收上一页最后一个 id,也收 page 自己给的 { id, n }(文件里有重复 id 时才用得上 n) */
99
+ export type PageCursor = string | { id: string; n?: number }
100
+
101
+ /**
102
+ * 游标分页:after 给上一页最后一个 id,不给就是第一页。
103
+ * 每页与 loadAll 的对应切片逐条相同;索引按文件 size+mtime+asOf 认库,连翻同一份文件只建一次。
104
+ * 游标找不到(库被重建过)抛 PAGE_CURSOR_UNKNOWN,不静默从头开始。
105
+ */
106
+ export function page(dir: string, opts?: { limit?: number; after?: PageCursor | null; asOf?: AsOf; backend?: StorageBackendName }): Promise<{
107
+ rows: Experience[]
108
+ next: { id: string; n: number } | null
109
+ hasMore: boolean
110
+ total: number
111
+ }>
112
+
91
113
  /** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
92
114
  export function badLines(dir: string): number
93
115
 
@@ -1,5 +1,6 @@
1
1
  // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
2
  import fs from 'node:fs'
3
+ import fsp from 'node:fs/promises'
3
4
  import path from 'node:path'
4
5
  import crypto from 'node:crypto'
5
6
  import * as recallEvents from './recall-events.js'
@@ -12,26 +13,70 @@ import { queryTerms, requiredOverlap, matchedTerms, normalizeText, contentUnits,
12
13
  import { hybridRank } from './hybrid-recall.js'
13
14
  import { parseAsOf, before, dayOf } from './as-of.js'
14
15
  import { readSnapshot } from './sqlite-store.js'
16
+ import { readLines, readLinesAsync } from './jsonl-stream.js'
17
+ import * as metrics from './metrics.js'
15
18
 
16
19
  const FILE = 'self-experience.jsonl'
17
20
  const WEIGHTS = new Set(['important', 'normal', 'minor'])
18
21
 
19
22
  // 坏行不再静默跳过:返回解析失败的行数,展示路径(strict)遇到坏行直接拒绝。
20
23
  // 写入路径用非 strict:追加一条新记录不会碰坏行,坏行原样留在文件里等人工修复。
21
- function readAll(dir, { strict = false } = {}) {
22
- let raw
24
+ //
25
+ // 逐行读,不整读文件(见 jsonl-stream.js)。坏行口径一个字没改:只跳过 trim 后为空的行,
26
+ // 解析的是**原样那一行**(不先 trim,行首带 BOM 的行照旧算坏行)。
27
+ function* recordLines(dir, { withOffset = false } = {}) {
28
+ const file = path.join(dir, FILE)
29
+ let fd
23
30
  try {
24
- raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
31
+ fd = fs.openSync(file, 'r')
25
32
  } catch (error) {
26
- if (error.code === 'ENOENT') return { rows: [], bad: 0 }
33
+ if (error.code === 'ENOENT') return
27
34
  // 只有"还没有这个文件"能当空;权限、是目录、坏盘必须报出来,不能当成 0 条
28
35
  throw experienceUnreadable(error)
29
36
  }
37
+ try {
38
+ for (const line of readLines(fd)) {
39
+ if (!line.text.trim()) continue
40
+ let row
41
+ try { row = JSON.parse(line.text) } catch { row = undefined }
42
+ if (withOffset) yield row === undefined ? { bad: true, offset: line.offset, bytes: line.bytes } : { row, offset: line.offset, bytes: line.bytes }
43
+ else yield row === undefined ? { bad: true } : { row }
44
+ }
45
+ } finally {
46
+ fs.closeSync(fd)
47
+ }
48
+ }
49
+
50
+ // 同上,异步那份(iterate / page 用)。读不出来的错误同样要报出来。
51
+ // withOffset:分页要把每行在文件里的字节位置一起记下来(之后只回读这一页,不扫全文件)
52
+ async function* recordLinesAsync(dir, { withOffset = false } = {}) {
53
+ const file = path.join(dir, FILE)
54
+ let fh
55
+ try {
56
+ fh = await fsp.open(file, 'r')
57
+ } catch (error) {
58
+ if (error.code === 'ENOENT') return
59
+ throw experienceUnreadable(error)
60
+ }
61
+ try {
62
+ for await (const line of readLinesAsync(fh)) {
63
+ if (!line.text.trim()) continue
64
+ let row
65
+ try { row = JSON.parse(line.text) } catch { row = undefined }
66
+ if (withOffset) yield row === undefined ? { bad: true, offset: line.offset, bytes: line.bytes } : { row, offset: line.offset, bytes: line.bytes }
67
+ else yield row === undefined ? { bad: true } : { row }
68
+ }
69
+ } finally {
70
+ await fh.close()
71
+ }
72
+ }
73
+
74
+ function readAll(dir, { strict = false } = {}) {
30
75
  const rows = []
31
76
  let bad = 0
32
- for (const line of raw.split('\n').filter(line => line.trim())) {
33
- try { rows.push(JSON.parse(line)) }
34
- catch { bad += 1 }
77
+ for (const rec of recordLines(dir)) {
78
+ if (rec.bad) bad += 1
79
+ else rows.push(rec.row)
35
80
  }
36
81
  if (strict && bad > 0) throw experienceCorrupt(bad)
37
82
  return { rows, bad }
@@ -185,10 +230,13 @@ function identifyRaw(raw) {
185
230
  }
186
231
 
187
232
  // 出处的一句话摘要:只用来指路,全文用 read / currentView 看
188
- const brief = (r) => {
189
- const s = String((r.then && r.then.text) || '')
190
- return { id: r.id, day: r.day, text: [...s].length > 24 ? [...s].slice(0, 24).join('') + '…' : s }
233
+ // 索引里也存这一份(buildIndex 的 t24),两处必须同一个口径
234
+ const briefText = (s) => {
235
+ const t = String(s || '')
236
+ const chars = [...t]
237
+ return chars.length > 24 ? chars.slice(0, 24).join('') + '…' : t
191
238
  }
239
+ const brief = (r) => ({ id: r.id, day: r.day, text: briefText((r.then && r.then.text) || '') })
192
240
 
193
241
  // asOf:翻回那天的自己。只保留那一刻之前(含)写下的经历、后记、想起和选择;
194
242
  // 那之后发生的一律看不见。不传 asOf 就是现在的样子
@@ -237,15 +285,8 @@ function sqliteSource(dir) {
237
285
  }
238
286
  }
239
287
 
240
- // backend:'file'(默认,零行为变化)或 'sqlite'(读 memory.sqlite,要求 node:sqlite;拿不到就报错,不静默退回 file)
241
- export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false, backend = 'file' } = {}) {
242
- const until = parseAsOf(asOf)
243
- const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
244
- const src = backendName(backend) === 'sqlite' ? sqliteSource(dir) : fileSource(dir)
245
- const { rows: all } = identifyRaw(src.records(!rawMode))
246
- const rows = until === null ? all : all.filter((r) => before(r, until))
247
- if (!rows.length) return rows
248
-
288
+ // 事件侧:两个后端在这里分开,往上走的是同一套合并逻辑(同一份数据读出来逐字段相同)
289
+ function readSide(src, { until, rawMode, allowSealCorrupt }) {
249
290
  // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段。
250
291
  // 读不出来必须报出来(readEvents):否则会当成"她从没想起过"。
251
292
  // rawMode(按字节备份/恢复/计数)不看事件内容,读不出来也不该拦住备份。
@@ -267,100 +308,420 @@ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorru
267
308
  const sealedMap = src.sealed(until, !allowSealCorrupt)
268
309
  // 翻回那天时,她**现在**封存着的也不翻出来:封存说的是她现在不想被提起,而翻回那天正是在提起旧事。
269
310
  // 那时还没封存的,标成 afterAsOf(后来才封存),各处过滤照常生效;点名读仍然给,并写明是后来封存的
270
- let sealedNowMap = sealedMap
271
- if (until !== null) sealedNowMap = src.sealed(null, !allowSealCorrupt)
272
-
273
- const viewed = rows.map((r) => {
274
- const keys = r.formerId ? [r.id, r.formerId] : [r.id]
275
- // 同一个 id 出现两次时,事件只回填到最先写下的那条(duplicateOf):一次想起不该挂两条
276
- const duplicate = Boolean(r.duplicateOf)
277
- const extra = duplicate ? [] : keys.flatMap((k) => laterMap.get(k) || [])
278
- const merged = [...(r.later || []).filter((l) => before(l, until)), ...extra]
279
- .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
280
- const next = { ...r, later: merged }
281
- if (until !== null) {
282
- next.viewAsOf = new Date(until).toISOString()
283
- // 旧格式行内的 recalls 没有时间,放不到那天的时间线上
284
- delete next.recalls
285
- delete next.lastRecalledAt
286
- }
287
- let state = null
288
- if (!duplicate) {
289
- for (const k of keys) {
290
- const st = unfinishedMap.get(k)
291
- if (st) state = st
292
- }
293
- }
294
- if (state && next.then && next.then.unfinished) next.unfinishedState = state
311
+ const sealedNowMap = until === null ? sealedMap : src.sealed(null, !allowSealCorrupt)
312
+
313
+ // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
314
+ const linkMap = src.links(until, onEventError)
315
+ const chapterList = src.chapters(until, rawMode ? () => [] : null)
316
+
317
+ return { until, rawMode, counts, laterMap, unfinishedMap, sealedMap, sealedNowMap, linkMap, chapterList }
318
+ }
319
+
320
+ // 封存状态的口径只写这一份:loadAll / iterate / page 共用,不许各自推一遍
321
+ // (entry 和行对象形状一致:都有 id / formerId / sealed,所以两处都能喂进来)
322
+ function sealedOf(r, side) {
323
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
324
+ let sealed = r.sealed
325
+ for (const k of keys) {
326
+ const s = side.sealedMap.get(k)
327
+ if (s) sealed = s
328
+ }
329
+ if (!sealed && side.until !== null) {
295
330
  for (const k of keys) {
296
- const s = sealedMap.get(k)
297
- if (s) next.sealed = s
331
+ const s = side.sealedNowMap.get(k)
332
+ if (s) sealed = { ...s, afterAsOf: true }
298
333
  }
299
- if (!next.sealed && until !== null) {
300
- for (const k of keys) {
301
- const s = sealedNowMap.get(k)
302
- if (s) next.sealed = { ...s, afterAsOf: true }
303
- }
304
- }
305
- let count = 0
306
- let lastAt = ''
307
- if (!duplicate) {
308
- for (const k of keys) {
309
- const c = counts.get(k)
310
- if (!c) continue
311
- count += c.count
312
- if (c.lastAt > lastAt) lastAt = c.lastAt
313
- }
334
+ }
335
+ return sealed
336
+ }
337
+
338
+ // 一条记录 + 事件 → 读出来的那条经历。三条读路径共用这一份,保证逐字段相同。
339
+ function mergeRow(r, side) {
340
+ const until = side.until
341
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
342
+ // 同一个 id 出现两次时,事件只回填到最先写下的那条(duplicateOf):一次想起不该挂两条
343
+ const duplicate = Boolean(r.duplicateOf)
344
+ const extra = duplicate ? [] : keys.flatMap((k) => side.laterMap.get(k) || [])
345
+ const merged = [...(r.later || []).filter((l) => before(l, until)), ...extra]
346
+ .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
347
+ const next = { ...r, later: merged }
348
+ if (until !== null) {
349
+ next.viewAsOf = new Date(until).toISOString()
350
+ // 旧格式行内的 recalls 没有时间,放不到那天的时间线上
351
+ delete next.recalls
352
+ delete next.lastRecalledAt
353
+ }
354
+ let state = null
355
+ if (!duplicate) {
356
+ for (const k of keys) {
357
+ const st = side.unfinishedMap.get(k)
358
+ if (st) state = st
314
359
  }
315
- if (count) {
316
- next.recalls = count
317
- next.lastRecalledAt = lastAt || (until === null ? r.lastRecalledAt : '') || ''
360
+ }
361
+ if (state && next.then && next.then.unfinished) next.unfinishedState = state
362
+ const sealed = sealedOf(r, side)
363
+ if (sealed) next.sealed = sealed
364
+ let count = 0
365
+ let lastAt = ''
366
+ if (!duplicate) {
367
+ for (const k of keys) {
368
+ const c = side.counts.get(k)
369
+ if (!c) continue
370
+ count += c.count
371
+ if (c.lastAt > lastAt) lastAt = c.lastAt
318
372
  }
319
- return next
320
- })
373
+ }
374
+ if (count) {
375
+ next.recalls = count
376
+ next.lastRecalledAt = lastAt || (until === null ? r.lastRecalledAt : '') || ''
377
+ }
378
+ return next
379
+ }
380
+
381
+ // 指路用的摘要:封存了的经历不露摘要,别的回想里只说"一件你封存了的事",
382
+ // 不借着引用把它又提起来
383
+ function pointerOf(row) {
384
+ return row.sealed ? { id: row.id, day: row.day, sealed: true } : brief(row)
385
+ }
321
386
 
322
- // 出处(这条是从哪几件事想到的)和反向引用(后来有哪些回想提到它):都从 then.refs 派生
323
- // 封存了的经历不露摘要:别的回想里只说"一件你封存了的事",不借着引用把它又提起来
324
- const pointer = (r) => r.sealed ? { id: r.id, day: r.day, sealed: true } : brief(r)
325
- const byId = new Map()
387
+ // 同一个 key 被多行指到时,以文件里靠后那一行为准(和以前 byId.set 覆盖的顺序一致)
388
+ function putPointer(map, key, seq, p) {
389
+ const cur = map.get(key)
390
+ if (!cur || cur.seq <= seq) map.set(key, { seq, p })
391
+ }
392
+
393
+ // 「谁引用了谁」:出处(refsInfo)与反向引用(citedBy)都查这一份
394
+ // seq 是记录在文件里的顺序号:用来判断"引用的其实是它自己"
395
+ function buildCrossRef(pairs) {
396
+ const pointers = new Map()
326
397
  // 重复 id 不覆盖先写下的那条:指路一律指向它
327
- for (const r of viewed) {
328
- if (r.duplicateOf) continue
329
- byId.set(r.id, r)
330
- if (r.formerId) byId.set(r.formerId, r)
398
+ for (const { seq, row } of pairs) {
399
+ if (row.duplicateOf) continue
400
+ const p = pointerOf(row)
401
+ putPointer(pointers, row.id, seq, p)
402
+ if (row.formerId) putPointer(pointers, row.formerId, seq, p)
331
403
  }
332
- for (const r of viewed) {
333
- const refs = (r.then && Array.isArray(r.then.refs)) ? r.then.refs : []
404
+ const cited = new Map()
405
+ for (const { seq, row } of pairs) {
406
+ const refs = (row.then && Array.isArray(row.then.refs)) ? row.then.refs : []
334
407
  if (!refs.length) continue
335
- r.refsInfo = refs.map((id) => { const hit = byId.get(id); return hit ? pointer(hit) : { id, missing: true } })
336
408
  for (const id of refs) {
337
- const target = byId.get(id)
338
- if (!target || target === r) continue
339
- target.citedBy = [...(target.citedBy || []), pointer(r)]
409
+ const target = pointers.get(id)
410
+ if (!target || target.seq === seq) continue
411
+ const list = cited.get(target.seq)
412
+ if (list) list.push(pointerOf(row))
413
+ else cited.set(target.seq, [pointerOf(row)])
340
414
  }
341
415
  }
416
+ return { pointers, cited }
417
+ }
342
418
 
343
- // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
344
- const linkMap = src.links(until, onEventError)
345
- const chapterList = src.chapters(until, rawMode ? () => [] : null)
346
- for (const r of viewed) {
347
- const keys = r.formerId ? [r.id, r.formerId] : [r.id]
348
- const links = !r.duplicateOf && keys.flatMap((k) => linkMap.get(k) || [])
349
- .map((l) => {
350
- const other = byId.get(l.other)
351
- if (!other || other === r) return null
352
- // 另一头封存了:只给 id 和日子,连理由也不露,免得借联想又把它提起来
353
- if (other.sealed) return { id: other.id, day: other.day, sealed: true, linkDay: l.day }
354
- return { ...pointer(other), reason: l.reason, linkDay: l.day }
355
- })
356
- .filter(Boolean)
357
- if (links.length) r.links = links
358
- const ch = chapterEvents.chaptersOn(chapterList, r.day || '')
359
- if (ch.length) r.chapters = ch.map((c) => ({ id: c.id, name: c.name }))
419
+ // 出处(这条是从哪几件事想到的)和反向引用(后来有哪些回想提到它):都从 then.refs 派生
420
+ function attachRefs(row, seq, cross) {
421
+ const refs = (row.then && Array.isArray(row.then.refs)) ? row.then.refs : []
422
+ if (refs.length) {
423
+ row.refsInfo = refs.map((id) => { const hit = cross.pointers.get(id); return hit ? hit.p : { id, missing: true } })
360
424
  }
425
+ const cited = cross.cited.get(seq)
426
+ if (cited && cited.length) row.citedBy = cited
427
+ return row
428
+ }
429
+
430
+ // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
431
+ function attachLinks(row, seq, cross, side) {
432
+ const keys = row.formerId ? [row.id, row.formerId] : [row.id]
433
+ const links = !row.duplicateOf && keys.flatMap((k) => side.linkMap.get(k) || [])
434
+ .map((l) => {
435
+ const other = cross.pointers.get(l.other)
436
+ if (!other || other.seq === seq) return null
437
+ const o = other.p
438
+ // 另一头封存了:只给 id 和日子,连理由也不露,免得借联想又把它提起来
439
+ if (o.sealed) return { id: o.id, day: o.day, sealed: true, linkDay: l.day }
440
+ return { ...o, reason: l.reason, linkDay: l.day }
441
+ })
442
+ .filter(Boolean)
443
+ if (links.length) row.links = links
444
+ const ch = chapterEvents.chaptersOn(side.chapterList, row.day || '')
445
+ if (ch.length) row.chapters = ch.map((c) => ({ id: c.id, name: c.name }))
446
+ return row
447
+ }
448
+
449
+ // backend:'file'(默认,零行为变化)或 'sqlite'(读 memory.sqlite,要求 node:sqlite;拿不到就报错,不静默退回 file)
450
+ export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false, backend = 'file' } = {}) {
451
+ const until = parseAsOf(asOf)
452
+ const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
453
+ const src = backendName(backend) === 'sqlite' ? sqliteSource(dir) : fileSource(dir)
454
+ const raw = src.records(!rawMode)
455
+ // 坏行数只给指标(不记内容);一次读库观测一次,0 也记,修好之后指标才会回落
456
+ metrics.recordBadLines(raw.bad)
457
+ const { rows: all } = identifyRaw(raw)
458
+ const rows = until === null ? all : all.filter((r) => before(r, until))
459
+ if (!rows.length) return rows
460
+
461
+ const side = readSide(src, { until, rawMode, allowSealCorrupt })
462
+ const viewed = rows.map((r) => mergeRow(r, side))
463
+ const cross = buildCrossRef(viewed.map((row, seq) => ({ seq, row })))
464
+ for (let seq = 0; seq < viewed.length; seq++) attachLinks(attachRefs(viewed[seq], seq, cross), seq, cross, side)
361
465
  return viewed
362
466
  }
363
467
 
468
+ // ---------------------------------------------------------------- 规模:逐条读与分页
469
+ // loadAll 要把整个库读成数组,而它返回的正是这个数组:十万条时绕不开几百 MB。
470
+ // 需要"一条一条处理"的地方(导出、备份、体检、搬家)用 iterate:
471
+ // 内存只跟一份小索引走——每个 id 只留日子、前 24 字和封存状态,正文不进索引。
472
+ //
473
+ // 代价说清楚:为了填 refsInfo / citedBy / links 这些要看"别处有哪些 id"的字段,
474
+ // iterate 要把经历文件读两遍(loadAll 一遍就够,因为它本来就持有全部记录)。
475
+ // 另一条路是产出"没有跨行字段"的行:一趟就够,但读出来和 loadAll 不一致,
476
+ // 调用方得自己记住哪些字段没有——那更容易出错,所以没这么做。
477
+ //
478
+ // 遍历期间文件被改(并发追加):两遍的记录数对不上,直接抛 EXPERIENCE_CHANGED,
479
+ // 不静默少返一条。要"同一时刻的一次性快照"请用 loadAll。
480
+
481
+ function experienceChanged() {
482
+ const error = new Error('经历文件在遍历期间变了:两遍读到的记录数对不上。重跑一次,或改用 loadAll(同一时刻的一次性快照)。')
483
+ error.code = 'EXPERIENCE_CHANGED'
484
+ return error
485
+ }
486
+
487
+ // 第一遍:扫一遍记录,只留下"指路"需要的东西,正文解析完就丢掉。
488
+ // entries:asOf 范围内的记录,按文件顺序;bySeq:按记录序号索引(范围外/被过滤掉的是 null)
489
+ // 坏行这里**不抛**:只把条数记在 index.bad 上,由调用方按"这次是不是按字节抢救"决定抛不抛。
490
+ // 这样同一份索引(分页会缓存)在两种口径下都能用,不会把 raw 模式的结果漏给展示路径。
491
+ async function buildIndex(dir, { until }) {
492
+ const entries = []
493
+ const bySeq = []
494
+ const seenIds = new Set() // 所有主 id(重复 id 靠它标)
495
+ const explicitIds = new Set() // 文件里**显式写着**这个 id 的那些主 id(identifyRaw 里的 explicit)
496
+ const legacy = [] // 需要认领旧 id 的在范围记录:{ entry, formerId }
497
+ const owners = new Map() // 旧 id → [主 id]
498
+ let bad = 0
499
+ let seq = 0
500
+ for await (const rec of recordLinesAsync(dir, { withOffset: true })) {
501
+ if (rec.bad) { bad += 1; continue }
502
+ const mySeq = seq++
503
+ const row = normalize(rec.row)
504
+ if (!row || !row.then || !row.then.text) { bySeq[mySeq] = null; continue }
505
+ // 同一个 id 出现两次:只认先写下的那条(identifyRaw 就是这么标的)
506
+ const dup = seenIds.has(row.id)
507
+ if (!dup) seenIds.add(row.id)
508
+ if (!row.formerId) explicitIds.add(row.id)
509
+ else {
510
+ const list = owners.get(row.formerId)
511
+ if (list) list.push(row.id)
512
+ else owners.set(row.formerId, [row.id])
513
+ }
514
+ // asOf 只决定"在不在这一页里":重复 id 与旧 id 的判据用的是全部记录,和 identifyRaw 一致
515
+ if (until !== null && !before(row, until)) { bySeq[mySeq] = null; continue }
516
+ const entry = {
517
+ seq: mySeq,
518
+ offset: rec.offset,
519
+ bytes: rec.bytes,
520
+ id: row.id,
521
+ day: row.day,
522
+ t24: briefText(row.then.text),
523
+ formerId: row.formerId || '',
524
+ dup: dup ? row.id : '',
525
+ sealed: row.sealed,
526
+ refs: (row.then && Array.isArray(row.then.refs) && row.then.refs.length) ? row.then.refs : null
527
+ }
528
+ entries.push(entry)
529
+ bySeq[mySeq] = entry
530
+ if (row.formerId) legacy.push({ entry, formerId: row.formerId })
531
+ }
532
+ metrics.recordBadLines(bad)
533
+ return { entries, bySeq, total: seq, bad, seenIds, explicitIds, legacy, owners }
534
+ }
535
+
536
+ // 旧格式记录的 id 认领:只有一个旧记录用着它、也没有别的记录显式用着这个 id,才认领
537
+ // (判据和 identifyRaw 里 owners / explicit 那两条逐字相同)
538
+ function resolveLegacy(index) {
539
+ for (const item of index.legacy) {
540
+ const owners = index.owners.get(item.formerId) || []
541
+ if (owners.length !== 1 || index.explicitIds.has(item.formerId)) item.entry.formerId = ''
542
+ }
543
+ return index
544
+ }
545
+
546
+ // 从索引里还原"指路表":pointers(id / 前 24 字 / 封存)+ cited(谁引用了它)
547
+ function indexCrossRef(index, side) {
548
+ const pointers = new Map()
549
+ for (const e of index.entries) {
550
+ if (e.dup) continue
551
+ const sealed = sealedOf(e, side)
552
+ const p = sealed ? { id: e.id, day: e.day, sealed: true } : { id: e.id, day: e.day, text: e.t24 }
553
+ putPointer(pointers, e.id, e.seq, p)
554
+ if (e.formerId) putPointer(pointers, e.formerId, e.seq, p)
555
+ }
556
+ const cited = new Map()
557
+ for (const e of index.entries) {
558
+ if (!e.refs) continue
559
+ const sealed = sealedOf(e, side)
560
+ const p = sealed ? { id: e.id, day: e.day, sealed: true } : { id: e.id, day: e.day, text: e.t24 }
561
+ for (const id of e.refs) {
562
+ const target = pointers.get(id)
563
+ if (!target || target.seq === e.seq) continue
564
+ const list = cited.get(target.seq)
565
+ if (list) list.push(p)
566
+ else cited.set(target.seq, [p])
567
+ }
568
+ }
569
+ return { pointers, cited }
570
+ }
571
+
572
+ // 索引里存的是"精简版的一行",读出来的正文行要靠这两条对齐:重复 id、认领后的旧 id
573
+ function applyEntry(row, entry) {
574
+ if (entry.dup) row.duplicateOf = entry.dup
575
+ else delete row.duplicateOf
576
+ if (entry.formerId) row.formerId = entry.formerId
577
+ else delete row.formerId
578
+ return row
579
+ }
580
+
581
+ // 逐条读:不建全量数组,内存只跟索引走。
582
+ // 异步生成器:块读走 fs/promises,不把事件循环卡住(事件文件仍是同步读,与 loadAll 同一份代码)
583
+ // backend='sqlite' 时退回整库快照(结果与 loadAll 逐条相同,但没有内存收益):sqlite 的快照本来就整库进内存。
584
+ export async function* iterate(dir, { asOf = null, backend = 'file', allowCorrupt = false, allowSealCorrupt = false } = {}) {
585
+ const name = backendName(backend)
586
+ const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
587
+ if (name !== 'file') {
588
+ for (const row of loadAll(dir, { asOf, backend, allowCorrupt, allowSealCorrupt })) yield row
589
+ return
590
+ }
591
+ const until = parseAsOf(asOf)
592
+ const index = await buildIndex(dir, { until })
593
+ // 坏行:展示路径 fail closed,而且要在吐出第一条之前就拒绝(不许先给几条再抛)
594
+ if (index.bad && !rawMode) throw experienceCorrupt(index.bad)
595
+ if (!index.entries.length) return
596
+ const side = readSide(fileSource(dir), { until, rawMode, allowSealCorrupt })
597
+ resolveLegacy(index)
598
+ const cross = indexCrossRef(index, side)
599
+
600
+ let seq = 0
601
+ for await (const rec of recordLinesAsync(dir)) {
602
+ if (rec.bad) {
603
+ if (rawMode) continue
604
+ throw experienceCorrupt(1)
605
+ }
606
+ const mySeq = seq++
607
+ if (mySeq >= index.total) throw experienceChanged()
608
+ const entry = index.bySeq[mySeq]
609
+ if (!entry) continue
610
+ const row = normalize(rec.row)
611
+ if (!row || !row.then || !row.then.text) continue
612
+ applyEntry(row, entry)
613
+ const view = mergeRow(row, side)
614
+ yield attachLinks(attachRefs(view, mySeq, cross), mySeq, cross, side)
615
+ }
616
+ if (seq !== index.total) throw experienceChanged()
617
+ }
618
+
619
+ // 分页:after 是上一页最后一个 id(也收 page 自己给的 { id, n }:n = 那一页末尾连着几条同 id,
620
+ // 只在文件里有重复 id 时才用得上)。不给 after 就是第一页。
621
+ //
622
+ // 代价:一页 = 一次索引扫描 + 只读这一页的字节。索引按「文件 size + mtime + asOf」认库:
623
+ // 同一份没变过的文件连着翻页只建一次,否则十万条下每页都要重扫一遍(成了 O(n²))。
624
+ // 只留最近一份索引(换目录/文件一变就重来),避免长期占着一份几十 MB 的东西。
625
+ // 事件文件每次仍然现读(封存可能刚变),所以翻页看到的状态不会停在建索引那一刻。
626
+ let pageCache = { dir: null, key: '', until: null, index: null }
627
+
628
+ function recordsKey(dir) {
629
+ try {
630
+ const st = fs.statSync(path.join(dir, FILE))
631
+ return st.size + ':' + st.mtimeMs
632
+ } catch (error) {
633
+ if (error.code === 'ENOENT') return 'missing'
634
+ throw experienceUnreadable(error)
635
+ }
636
+ }
637
+
638
+ export async function page(dir, { limit = 50, after = null, asOf = null, backend = 'file', allowCorrupt = false, allowSealCorrupt = false } = {}) {
639
+ const size = Number(limit)
640
+ if (!Number.isInteger(size) || size <= 0) throw new Error('limit must be a positive integer.(limit 必须是正整数。)')
641
+ const until = parseAsOf(asOf)
642
+ const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
643
+ const name = backendName(backend)
644
+ if (name !== 'file') {
645
+ // sqlite:快照本来就整库在内存里,分页只能从全量里切(结果相同,但没有内存收益)
646
+ const all = loadAll(dir, { asOf, backend, allowCorrupt, allowSealCorrupt })
647
+ const ids = all.map((r) => r.id)
648
+ const start = cursorStart(ids, after)
649
+ const rows = all.slice(start, start + size)
650
+ const hasMore = start + size < all.length
651
+ return { rows, next: hasMore ? cursorOf(ids, start, size) : null, hasMore, total: all.length }
652
+ }
653
+ const key0 = recordsKey(dir)
654
+ let index = pageCache.dir === dir && pageCache.key === key0 && pageCache.until === until ? pageCache.index : null
655
+ if (!index) {
656
+ index = await buildIndex(dir, { until })
657
+ // 建的过程中文件又变了:这份索引已经对不上,别进缓存(下一页会重建)
658
+ if (recordsKey(dir) === key0) pageCache = { dir, key: key0, until, index }
659
+ }
660
+ if (index.bad && !rawMode) throw experienceCorrupt(index.bad)
661
+ const ids = index.entries.map((e) => e.id)
662
+ const start = cursorStart(ids, after)
663
+ const selected = index.entries.slice(start, start + size)
664
+ const total = index.entries.length
665
+ if (!selected.length) return { rows: [], next: null, hasMore: false, total }
666
+ const side = readSide(fileSource(dir), { until, rawMode, allowSealCorrupt })
667
+ resolveLegacy(index)
668
+ const cross = indexCrossRef(index, side)
669
+ const rows = await readEntries(dir, selected, side, cross)
670
+ const hasMore = start + selected.length < total
671
+ return { rows, next: hasMore ? cursorOf(ids, start, selected.length) : null, hasMore, total }
672
+ }
673
+
674
+ // 按索引里记下的字节位置把这一页的行读回来(只读这一页,不扫全文件)
675
+ async function readEntries(dir, selected, side, cross) {
676
+ let fh
677
+ try {
678
+ fh = await fsp.open(path.join(dir, FILE), 'r')
679
+ } catch (error) {
680
+ throw experienceUnreadable(error)
681
+ }
682
+ try {
683
+ let max = 0
684
+ for (const e of selected) if (e.bytes > max) max = e.bytes
685
+ const buf = Buffer.allocUnsafe(max + 1)
686
+ const rows = []
687
+ for (const e of selected) {
688
+ const { bytesRead } = await fh.read(buf, 0, e.bytes, e.offset)
689
+ let row
690
+ try { row = normalize(JSON.parse(buf.toString('utf8', 0, bytesRead))) } catch { row = null }
691
+ if (!row || !row.then || !row.then.text) throw experienceChanged()
692
+ applyEntry(row, e)
693
+ const view = mergeRow(row, side)
694
+ rows.push(attachLinks(attachRefs(view, e.seq, cross), e.seq, cross, side))
695
+ }
696
+ return rows
697
+ } finally {
698
+ await fh.close()
699
+ }
700
+ }
701
+
702
+ // 游标落在第几行之后:找不到这个 id 就说清楚,不静默从头开始(那会把一页重复一遍)
703
+ function cursorStart(ids, after) {
704
+ if (after === null || after === undefined || after === '') return 0
705
+ const cur = typeof after === 'string' ? { id: after, n: 1 } : after
706
+ const at = ids.indexOf(String(cur.id))
707
+ if (at < 0) {
708
+ const error = new Error('分页游标失效:找不到 id ' + String(cur.id) + '。用 after: null 从头开始,或换一个还在这一页里的 id。')
709
+ error.code = 'PAGE_CURSOR_UNKNOWN'
710
+ throw error
711
+ }
712
+ const n = Number.isInteger(cur.n) && cur.n > 0 ? cur.n : 1
713
+ return at + n
714
+ }
715
+
716
+ // 这一页的游标:n = 从这个 id **第一次出现**到这一页最后一行,一共走了几条。
717
+ // 重复 id 的时候只有这样才不漏、不重(只数"本页末尾连着几条"会让下一页原地打转)。
718
+ function cursorOf(ids, start, size) {
719
+ const lastAt = start + size - 1
720
+ const last = ids[lastAt]
721
+ const first = ids.indexOf(last)
722
+ return { id: last, n: lastAt - first + 1 }
723
+ }
724
+
364
725
  // 事后联想:她发现两件事有关,亲手连起来,并说清为什么。两条都必须存在;同一对只连一次
365
726
  export function linkExperiences(dir, { from, to, reason = '' } = {}) {
366
727
  if (!String(from || '').trim() || !String(to || '').trim()) return { ok: false, error: 'Need the ids of two experiences: from and to(需要 from 与 to 两条经历的 id)' }
@@ -440,7 +801,15 @@ function resolveRefs(dir, refs) {
440
801
 
441
802
  // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
442
803
  // refs:这条是从哪几件事想到的(回想、归纳时用)。写入时就校验,引用不存在的经历直接拒绝
443
- export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time', refs = [] }) {
804
+ export function addExperience(dir, input = {}) {
805
+ // 指标:写入延迟(含 refs 的存在性校验,那是这条路径真实的一部分)
806
+ const t0 = process.hrtime.bigint()
807
+ const row = addExperienceInner(dir, input)
808
+ metrics.recordWrite({ ms: Number(process.hrtime.bigint() - t0) / 1e6 })
809
+ return row
810
+ }
811
+
812
+ function addExperienceInner(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time', refs = [] }) {
444
813
  if (!String(text || '').trim()) throw new Error('text cannot be empty.(text 不能是空的。)')
445
814
  const safeText = tooLong('text', text, LIMITS.text)
446
815
  const safeScene = tooLong('scene', scene, LIMITS.scene)
@@ -568,7 +937,15 @@ export function currentView(dir, id, { asOf = null, backend = 'file' } = {}) {
568
937
  // 混合检索只用它排序(追问句本身几乎没有内容词时才用它补足门禁)。不传就是单轮,行为不变。
569
938
  // ranker='hybrid' 时 mode / gate / minOverlap / minRatio 都不参与(它有自己的覆盖率门槛,见 hybrid-recall.js);
570
939
  // 空查询在 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 } = {}) {
940
+ export function recall(dir, query, opts = {}) {
941
+ // 指标:召回延迟、返回条数、后端类型。只记成功返回的那次——抛错由调用方和 doctor 说
942
+ const t0 = process.hrtime.bigint()
943
+ const hits = recallInner(dir, query, opts)
944
+ metrics.recordRecall({ ms: Number(process.hrtime.bigint() - t0) / 1e6, hits: hits.length, backend: backendName(opts && opts.backend) })
945
+ return hits
946
+ }
947
+
948
+ function recallInner(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 } = {}) {
572
949
  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 不能一起用。)')
573
950
  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
951
  if (ranker !== 'literal' && ranker !== 'hybrid') {
@@ -74,6 +74,20 @@ export function sqliteAvailable() {
74
74
  // ---------------------------------------------------------------- 表结构
75
75
 
76
76
  export function ensureSchema(db) {
77
+ // 建表必须一次成。DDL 逐条自动提交的话,第一次建库时进程被杀(或盘满)会留下"有 records、没 events"
78
+ // 的半截库,之后读路径会永远报缺表。SQLite 的 DDL 在事务里可以整组回滚,包一层就好。
79
+ db.exec('BEGIN IMMEDIATE')
80
+ try {
81
+ createTables(db)
82
+ db.exec('COMMIT')
83
+ } catch (error) {
84
+ // 回滚本身也可能失败(连接已坏):不能盖掉真正的错误
85
+ try { db.exec('ROLLBACK') } catch { }
86
+ throw error
87
+ }
88
+ }
89
+
90
+ function createTables(db) {
77
91
  db.exec(`CREATE TABLE IF NOT EXISTS records (
78
92
  id TEXT PRIMARY KEY,
79
93
  day TEXT NOT NULL,
@@ -18,6 +18,12 @@ import path from 'node:path'
18
18
  import { AsyncLocalStorage } from 'node:async_hooks'
19
19
  import { DB_FILE, requireSqlite, openDatabase, insertRecord, insertEvent, recordExists, readEvents, readRecords, kindOf } from '../sqlite-store.js'
20
20
 
21
+ // 回滚本身失败时(盘满、连接已坏这类)不能把真正的错误盖掉:包一层,原错误优先。
22
+ // 这是 crash-drills 的复审发现:ROLLBACK 没包 try 时,SQLITE_FULL 之类的二次失败会顶掉原始错误。
23
+ function rollbackQuiet(db, sql = 'ROLLBACK') {
24
+ try { db.exec(sql) } catch { }
25
+ }
26
+
21
27
  export class SqliteBackend {
22
28
  #als = new AsyncLocalStorage()
23
29
  #tail = Promise.resolve()
@@ -73,8 +79,8 @@ export class SqliteBackend {
73
79
  db.exec('RELEASE ' + sp)
74
80
  return result
75
81
  } catch (error) {
76
- db.exec('ROLLBACK TO ' + sp)
77
- db.exec('RELEASE ' + sp)
82
+ rollbackQuiet(db, 'ROLLBACK TO ' + sp)
83
+ rollbackQuiet(db, 'RELEASE ' + sp)
78
84
  throw error
79
85
  }
80
86
  }
@@ -84,7 +90,7 @@ export class SqliteBackend {
84
90
  db.exec('COMMIT')
85
91
  return result
86
92
  } catch (error) {
87
- db.exec('ROLLBACK')
93
+ rollbackQuiet(db)
88
94
  throw error
89
95
  }
90
96
  }
@@ -174,8 +180,8 @@ export class SqliteBackend {
174
180
  db.exec('RELEASE ' + sp)
175
181
  return result
176
182
  } catch (error) {
177
- db.exec('ROLLBACK TO ' + sp)
178
- db.exec('RELEASE ' + sp)
183
+ rollbackQuiet(db, 'ROLLBACK TO ' + sp)
184
+ rollbackQuiet(db, 'RELEASE ' + sp)
179
185
  throw error
180
186
  }
181
187
  }
@@ -187,7 +193,7 @@ export class SqliteBackend {
187
193
  db.exec('COMMIT')
188
194
  return result
189
195
  } catch (error) {
190
- db.exec('ROLLBACK')
196
+ rollbackQuiet(db)
191
197
  throw error
192
198
  }
193
199
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.24.0",
3
+ "version": "0.25.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",