whale-memory-core 0.24.0 → 0.26.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.
@@ -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') {
@@ -776,7 +1153,8 @@ export function renderTwoPart(entry, { now = new Date(), lang = 'zh' } = {}) {
776
1153
  return lines.join('\n')
777
1154
  }
778
1155
 
779
- export const internals = { WEIGHTS, FILE }
1156
+ // 给擦除(阶段 4)复用的内部口径:一行原样 → 她的一条经历(含旧格式的 id 推导)
1157
+ export const internals = { WEIGHTS, FILE, normalize, legacyId }
780
1158
  // 兼容旧调用:只要一句摘要的地方仍可用
781
1159
  // 宿主拿用户的原话直接来召回、再自动塞进提示词:默认走 strict 的新口径(cover)。
782
1160
  // 旧口径(legacy)在同批用例上编造率 27.8%(见 docs/eval.md),自动递回不能默认用它;