whale-memory-core 0.26.0 → 0.26.2

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.
package/lib/archive.js CHANGED
@@ -358,6 +358,17 @@ export function importArchive(fromDir, memDir, { force = false } = {}) {
358
358
  throw new Error('Export changed during import: ' + f.name + '(导入期间备份内容发生变化)')
359
359
  }
360
360
  }
361
+ // 恢复旧备份会把擦除"撤销":备份是擦除前打的,里面没有墓碑。导入时把现有目录的
362
+ // 墓碑与审计账本并进新目录,否则记录回来了、撤回记录没了(验收抓到的)。
363
+ for (const name of ['tombstones.jsonl', 'audit.jsonl']) {
364
+ const live = path.join(target, name)
365
+ if (!fs.existsSync(live)) continue
366
+ const readLines = (file) => fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim())
367
+ const staged = fs.existsSync(path.join(stage, name)) ? readLines(path.join(stage, name)) : []
368
+ const seen = new Set(staged)
369
+ const merged = staged.concat(readLines(live).filter((line) => !seen.has(line)))
370
+ fs.writeFileSync(path.join(stage, name), merged.join('\n') + (merged.length ? '\n' : ''), 'utf8')
371
+ }
361
372
  const loaded = loadAll(stage, { allowSealCorrupt: true })
362
373
 
363
374
  // 动手改目录之前先落盘日志:从这一刻起任何崩溃都能自动找回旧数据
package/lib/audit.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface AuditRow {
12
12
  }
13
13
 
14
14
  export const ACTIONS: readonly string[]
15
+ /** note 上限(字):审计只记动作,不记正文 */
16
+ export const LIMIT_NOTE: number
15
17
  export function eventsFile(memDir: string): string
16
18
  export function isValid(r: unknown): r is AuditRow
17
19
  /** 查询的 sha256:审计只留这个指纹,不留原文 */
package/lib/audit.js CHANGED
@@ -16,6 +16,8 @@ import { readLines } from './jsonl-stream.js'
16
16
  import { currentView, recall as recallInner } from './self-experience.js'
17
17
 
18
18
  const FILE = 'audit.jsonl'
19
+ // note 只给"这条是什么动作"用:限长,防止有人顺手把正文/查询原文塞进来
20
+ export const LIMIT_NOTE = 500
19
21
 
20
22
  // 动作:至少这三类。别的名字也收(新增动作算兼容),但必须是非空字符串
21
23
  export const ACTIONS = Object.freeze(['read', 'recall', 'erase'])
@@ -45,6 +47,9 @@ export function record(memDir, { at = new Date().toISOString(), actor, action, i
45
47
  ids: (Array.isArray(ids) ? ids : []).map(String),
46
48
  note: String(note ?? '')
47
49
  }
50
+ // note 限长:这里不是写正文的地方。ids / actor 的"不含正文"由宿主保证——库只认形状,
51
+ // 挡不住一个故意把原话当 id 传进来的宿主(文档里写明了)。
52
+ if ([...row.note].length > LIMIT_NOTE) throw new Error('审计的 note 太长(' + [...row.note].length + '/' + LIMIT_NOTE + ' 字):这里只写"是什么动作",不写正文或查询原文。(audit note is too long)')
48
53
  if (!isValid(row)) throw new Error('审计行不合格(需要 at / actor / action / ids / note),拒绝写入。(audit row is not valid)')
49
54
  fs.mkdirSync(memDir, { recursive: true })
50
55
  return withFileLock(eventsFile(memDir) + '.lock', () => {
package/lib/erase.d.ts CHANGED
@@ -22,6 +22,8 @@ export interface EraseResult {
22
22
  at: string
23
23
  /** 删除前那一行的 sha256 */
24
24
  hash?: string
25
+ /** 这次有没有墓碑在手:true = 确实撤回并留了墓碑(或之前已撤回);false = 本来就没有这条记录(id 可能抄错) */
26
+ tombstone: boolean
25
27
  actor?: string
26
28
  reason?: string
27
29
  removed: EraseRemoved
package/lib/erase.js CHANGED
@@ -10,12 +10,15 @@
10
10
  // · 先查后删:经历文件或要重写的事件文件里有坏行,**整次拒绝**——坏行说不清是不是那条,
11
11
  // 不能假装删干净了。擦除不做"尽量"。
12
12
  // · 文件原子:读全量 → 过滤 → 写 .tmp → rename(见 file-lock.writeFileAtomic),
13
- // 永远不会出现"写了一半"的经历文件。
14
- // · 幂等:第二次调用返回 { ok: true, alreadyGone: true },不再写第二条墓碑。
13
+ // 永远不会出现"写了一半"的经历文件;墓碑写下之前任何一步失败,改过的文件按原样放回去。
14
+ // · 先删事件、再删经历:万一进程在中间被杀,记录还在,重跑还能把墓碑补出来。
15
+ // · 幂等:第二次调用返回 { ok: true, alreadyGone: true, tombstone: true },不再写第二条墓碑;
16
+ // 本来就没有这条记录时返回 alreadyGone + `tombstone: false`(宿主能分清"已撤回"和"id 抄错了")。
15
17
  // · 只由宿主在"她本人或 Leo 明确要求"时调用;库不自动擦除,也没有定时清理。
16
18
  //
17
19
  // 做不到(文档里也写清):备份与快照里的历史副本不追溯;SQLite 删除后文件页里可能残留旧字节
18
- // (安全删除 / VACUUM 不在承诺里);多写者不承诺(同一目录并发写按契约本来就是单写者假设)。
20
+ // (安全删除 / VACUUM 不在承诺里);多写者不承诺(同一目录并发写按契约本来就是单写者假设);
21
+ // seal 事件的 note 是人的自由文本,可能提到原话,不在本函数删除范围内。
19
22
  import fs from 'node:fs'
20
23
  import path from 'node:path'
21
24
  import crypto from 'node:crypto'
@@ -110,7 +113,9 @@ function analyse(records, id) {
110
113
  return { infos, target }
111
114
  }
112
115
 
113
- function rewriteIfChanged(dir, name, lines, keep) {
116
+ // 改写一个文件(真正的删除动作)。写之前把原文记进 journal:任何一步失败都能原样放回去。
117
+ // 返回删掉的行数;一行都没删就不碰文件。
118
+ function rewriteTracked(dir, name, lines, keep, journal) {
114
119
  const kept = []
115
120
  let removed = 0
116
121
  for (const line of lines) {
@@ -118,10 +123,33 @@ function rewriteIfChanged(dir, name, lines, keep) {
118
123
  else removed += 1
119
124
  }
120
125
  if (!removed) return 0
121
- writeFileAtomic(path.join(dir, name), kept.length ? kept.join('\n') + '\n' : '')
126
+ const file = path.join(dir, name)
127
+ let before = null
128
+ try { before = fs.readFileSync(file, 'utf8') } catch { before = null }
129
+ journal.push({ name, before })
130
+ writeFileAtomic(file, kept.length ? kept.join('\n') + '\n' : '')
122
131
  return removed
123
132
  }
124
133
 
134
+ // 把 journal 里已经改过的文件按原样放回去(倒序)。只在墓碑写成功之前用:
135
+ // 墓碑一旦写下就代表"撤回了",再把记录放回去会变成"墓碑说有、文件里又有"。
136
+ function rollbackFiles(dir, journal) {
137
+ const failures = []
138
+ for (const item of [...journal].reverse()) {
139
+ const file = path.join(dir, item.name)
140
+ try {
141
+ // 已经和原文一样(比如那次写入本来就失败了)就不用再动它:省得把"写不进去"误报成"回滚失败"
142
+ const now = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null
143
+ if (now === item.before) continue
144
+ if (item.before === null) fs.rmSync(file, { force: true })
145
+ else writeFileAtomic(file, item.before)
146
+ } catch (error) {
147
+ failures.push(item.name + ':' + String(error && error.message ? error.message : error))
148
+ }
149
+ }
150
+ return failures
151
+ }
152
+
125
153
  /**
126
154
  * 整条撤回一条经历。
127
155
  *
@@ -147,8 +175,8 @@ export function eraseExperience(dir, { id, reason = '', actor = '', now = new Da
147
175
  // 1) 账本先看一遍:墓碑文件坏了就不知道撤回没撤回,宁可不猜
148
176
  const marks = tombstones.readAll(dir)
149
177
  if (marks.bad > 0) throw coded('墓碑文件有 ' + marks.bad + ' 行无法解析:先修好再撤回,不然没法确认这条是不是已经撤回过。(tombstones are corrupt)', 'ERASE_TOMBSTONES_CORRUPT', { bad: marks.bad })
150
- const old = marks.rows.find((r) => r.id === key)
151
- if (old) return { ok: true, id: key, alreadyGone: true, at: old.at, reason: old.reason, actor: old.actor, hash: old.hash, removed: emptyRemoved() }
178
+ const old = marks.rows.find((r) => r.id === key || (Array.isArray(r.ids) && r.ids.includes(key)))
179
+ if (old) return { ok: true, id: key, alreadyGone: true, at: old.at, reason: old.reason, actor: old.actor, hash: old.hash, tombstone: true, removed: emptyRemoved() }
152
180
 
153
181
  // 2) 读全量 + 预检:坏行 / 读不出来都整次拒绝,一个字节都不改
154
182
  const records = readLinesOf(dir, RECORDS)
@@ -170,48 +198,84 @@ export function eraseExperience(dir, { id, reason = '', actor = '', now = new Da
170
198
  hash = hashOfLine(doomed[0].line.text)
171
199
  if (doomed.length > 1) removed.duplicates = doomed.length - 1
172
200
  }
201
+ // 旧 id 上挂着的事件也要删:0.10 之前的后记/想起是挂在 12 位旧 id 上的,
202
+ // 用当前 id 撤回时如果不带上它,后记正文会留在盘上(独立复审抓到的)。
203
+ const formerIds = [...new Set(doomed.map((i) => (i.row && i.row.formerId ? String(i.row.formerId) : '')).filter(Boolean))]
204
+ // 墓碑记下这一条用过的所有 id(当前 id / 旧 id):按旧 id 撤回时,封存事件挂在当前 id 上,
205
+ // 体检要靠 ids 把两边对上(复审抓到的:只记 key 会让 doctor 永远红灯)。
206
+ // 共用旧 id:同一个旧 id 被两条以上经历用过,擦掉其中一条之后,剩下那条会"独占"这个旧 id,
207
+ // 旧后记就可能被算到它头上。旧数据里没有区分手段,所以这里把这种情况记进墓碑,让 doctor 提示。
208
+ const legacyCount = new Map()
209
+ for (const info of analysed.infos) {
210
+ if (!info.row || !info.rawFormerId) continue
211
+ legacyCount.set(info.rawFormerId, (legacyCount.get(info.rawFormerId) || 0) + 1)
212
+ }
213
+ const ambiguousIds = [...new Set(doomed.map((i) => i.rawFormerId).filter(Boolean))]
214
+ .filter((oldId) => (legacyCount.get(oldId) || 0) > 1)
173
215
 
174
- // 5) 经历文件:过滤 → 原子替换(没命中就不碰文件)
175
- removed.records = rewriteIfChanged(dir, RECORDS, records.lines, (line) => {
176
- const row = recordOf(line.row)
177
- return !(row && analysed.target.has(String(row.id)))
178
- })
216
+ const tombIds = [...new Set([key, ...analysed.target, ...formerIds])]
217
+ const eventIds = new Set(tombIds)
179
218
 
180
- // 6) 关联事件:later / recall / unfinished / link 一起清(seal 与 chapter 不动)
181
- const eventIds = new Set([key, ...analysed.target])
182
- for (const file of events) {
183
- removed[shortName(file.name)] = rewriteIfChanged(dir, file.name, file.lines, (line) => !eventIdsOf(line.row).some((x) => eventIds.has(x)))
184
- }
219
+ const journal = []
220
+ let tombstoned = false
221
+ try {
222
+ // 5) 先删事件、再删经历:万一进程在中间被杀,记录还在,重跑还能把墓碑补出来。
223
+ // 每一步写之前都把原文记进 journal;任何一步失败就整体放回去(墓碑写下之前)。
224
+ for (const file of events) {
225
+ removed[shortName(file.name)] = rewriteTracked(dir, file.name, file.lines, (line) => !eventIdsOf(line.row).some((x) => eventIds.has(x)), journal)
226
+ }
227
+ removed.records = rewriteTracked(dir, RECORDS, records.lines, (line) => {
228
+ const row = recordOf(line.row)
229
+ return !(row && analysed.target.has(String(row.id)))
230
+ }, journal)
185
231
 
186
- // 7) SQLite 副本:记录 + 事件一起删(seal 留),删完按擦除前是否对得上决定刷不刷 sources
187
- const sq = eraseFromStore(dir, [key, ...analysed.target], { refreshSources: store.fresh })
188
- if (sq.present) { removed.sqliteRecords = sq.records; removed.sqliteEvents = sq.events }
189
- removed.sqlite = Boolean(sq.present)
232
+ // 6) SQLite 副本:记录 + 事件一起删(seal 留),删完按擦除前是否对得上决定刷不刷 sources
233
+ const sq = eraseFromStore(dir, tombIds, { refreshSources: store.fresh })
234
+ if (sq.present) { removed.sqliteRecords = sq.records; removed.sqliteEvents = sq.events }
235
+ removed.sqlite = Boolean(sq.present)
190
236
 
191
- // 8) 什么都没找到:这次是"已经没了"(崩溃后重跑也走这里:顺手把残留事件清掉)
192
- if (!doomed.length) {
193
- if (!removed.records && !removed.later && !removed.recall && !removed.unfinished && !removed.link && !removed.sqliteRecords && !removed.sqliteEvents) {
194
- return { ok: true, id: key, alreadyGone: true, at: '', removed }
237
+ // 7) 什么都没找到:这次是"已经没了"(崩溃后重跑也走这里:顺手把残留事件清掉)
238
+ if (!doomed.length) {
239
+ // 记录行已经没了、但这次确实清掉了残留事件(崩溃后重跑会走这里):
240
+ // 既然真的删了东西,就要在审计里留一条,否则事后查不到任何痕迹(验收抓到的)。
241
+ const cleaned = Number(removed.records || 0) + Number(removed.sqliteRecords || 0) + Number(removed.sqliteEvents || 0) +
242
+ EVENT_FILES.reduce((n, name) => n + Number(removed[shortName(name)] || 0), 0)
243
+ if (cleaned > 0) {
244
+ try { audit.record(dir, { actor: actorText, action: 'erase', ids: [key], note: 'already-gone-cleanup' }) } catch { /* 审计失败不改变"已经删掉了"这个事实 */ }
195
245
  }
196
- // 记录已经不在了、事件/库里的残留清掉了:不写墓碑(我们从没看见过那条记录,写不出它的哈希)
197
- return { ok: true, id: key, alreadyGone: true, at: '', removed }
246
+ return { ok: true, id: key, alreadyGone: true, at: '', tombstone: false, removed }
198
247
  }
199
248
 
200
- // 9) 墓碑:删除成功之后才写(墓碑不会早于删除出现,谎报"已撤回")
201
- try {
202
- tombstones.append(dir, { v: 1, id: key, at, reason: String(reason).trim(), actor: actorText, hash })
203
- } catch (error) {
204
- throw coded('记录已经删掉了,但墓碑写失败:' + String(error && error.message ? error.message : error) + '。请先把墓碑补上再对外说"撤回了"。(tombstone write failed after erase)', 'ERASE_TOMBSTONE_FAILED', { cause: error, erased: true })
205
- }
249
+ // 8) 墓碑:删除成功之后才写(墓碑不会早于删除出现,谎报"已撤回")
250
+ // ids 记下"这一条经历在库里用过的所有 id"(当前 id + 旧 id),体检核对封存事件时用
251
+ try {
252
+ tombstones.append(dir, { v: 1, id: key, ids: tombIds, at, reason: String(reason).trim(), actor: actorText, hash, ...(ambiguousIds.length ? { ambiguousIds } : {}) })
253
+ } catch (error) {
254
+ throw coded('墓碑写失败:' + String(error && error.message ? error.message : error) + '。(tombstone write failed)', 'ERASE_TOMBSTONE_FAILED', { cause: error })
255
+ }
256
+ tombstoned = true
206
257
 
207
- // 10) 审计:只记 id 与动作,不记正文(reason 里有人的话,不往审计里抄)
208
- try {
209
- audit.record(dir, { actor: actorText, action: 'erase', ids: [key], note: 'tombstone' })
258
+ // 9) 审计:只记 id 与动作,不记正文(reason 里有人的话,不往审计里抄)
259
+ try {
260
+ audit.record(dir, { actor: actorText, action: 'erase', ids: [key], note: 'tombstone' })
261
+ } catch (error) {
262
+ throw coded('记录与墓碑都在,但审计追加失败:' + String(error && error.message ? error.message : error) + '。(audit write failed after erase)', 'ERASE_AUDIT_FAILED', { cause: error, erased: true })
263
+ }
264
+
265
+ return { ok: true, id: key, alreadyGone: false, at, hash, tombstone: true, actor: actorText, reason: String(reason).trim(), removed }
210
266
  } catch (error) {
211
- throw coded('记录与墓碑都在,但审计追加失败:' + String(error && error.message ? error.message : error) + '。(audit write failed after erase)', 'ERASE_AUDIT_FAILED', { cause: error, erased: true })
267
+ // 墓碑还没写下 = 这次撤回不算数:把改过的文件按原样放回去(SQLite 的事务自己回滚;
268
+ // 万一删除已经在库里提交过,回滚后库会判为过期、读路径 fail closed,重新迁移即可)
269
+ if (!tombstoned) {
270
+ const failures = rollbackFiles(dir, journal)
271
+ if (failures.length) {
272
+ throw coded(String(error && error.message ? error.message : error) + ';回滚失败:' + failures.join(';') + '(文件可能只删了一半,先别对外说撤回了)。(rollback failed)', 'ERASE_ROLLBACK_FAILED', { cause: error, rollback: failures })
273
+ }
274
+ // 回滚干净了:宿主看到的应该是"这次没撤成",而不是一个光秃秃的 EPERM
275
+ throw coded('擦除没有完成(改过的文件已按原样放回):' + String(error && error.message ? error.message : error) + '。(erase aborted, files rolled back)', (error && error.code) || 'ERASE_FAILED', { cause: error })
276
+ }
277
+ throw error
212
278
  }
213
-
214
- return { ok: true, id: key, alreadyGone: false, at, hash, actor: actorText, reason: String(reason).trim(), removed }
215
279
  })
216
280
  }
217
281
 
@@ -312,17 +312,36 @@ export function readRecords(db) {
312
312
  // 2. eraseFromStore():一个事务里删 records + events(seal 留着),提交后按需刷新 sources。
313
313
  // 墓碑写失败不回滚删除,这个取舍写在 docs/erase-audit-zh.md 里。
314
314
  //
315
- // 注意:SQLite 删除行之后,旧字节可能还留在文件页里(没有 VACUUM / secure_delete)。
315
+ // 注意:SQLite 删除行之后,旧字节可能还留在文件页里。擦除路径会先开 secure_delete(见 eraseFromStore);
316
+ // 其余删除路径不保证,所以"按原始字节能不能搜到正文"只对擦除做承诺。
316
317
  // 这不是"没擦掉",是"磁盘上的碎片不追溯"——和备份里的历史副本一样,文档里写明不承诺。
317
318
 
318
- /** 擦除前的体检:库不存在 = { present:false };存在但打不开/不全 = 抛;过期 = fresh:false。 */
319
- export function eraseReadiness(dir) {
319
+ // 库文件本身的存在性/形状:不存在 = null;是目录 / 0 字节 = 抛(不能当"没有库"糊弄过去)
320
+ function statDatabase(dir) {
320
321
  const file = path.join(dir, DB_FILE)
321
- let exists = false
322
- try { exists = fs.existsSync(file) } catch { exists = false }
322
+ let st
323
+ try {
324
+ st = fs.statSync(file)
325
+ } catch (error) {
326
+ if (error && error.code === 'ENOENT') return null
327
+ throw coded(DB_FILE + ' 读不出来:' + String(error && error.message ? error.message : error), 'STORAGE_UNREADABLE')
328
+ }
329
+ if (!st.isFile()) throw coded(DB_FILE + ' 不是普通文件(是目录?):不能当库用,先移走它。', 'STORAGE_UNREADABLE')
330
+ if (st.size === 0) throw coded(DB_FILE + ' 是 0 字节的空文件,不是完整的库(先移走它重新迁移)。', 'STORAGE_INCOMPLETE')
331
+ return st
332
+ }
333
+
334
+ /** 擦除前的体检:库不存在 = { present:false };存在但打不开/不全/0 字节 = 抛;过期 = fresh:false。 */
335
+ export function eraseReadiness(dir) {
323
336
  // 没有库就不碰 node:sqlite:Node 20 上擦一个只用 file 后端的目录必须照常能跑
324
- if (!exists) return { present: false, fresh: false }
325
- const db = openDatabase(dir)
337
+ if (!statDatabase(dir)) return { present: false, fresh: false }
338
+ let db
339
+ try {
340
+ db = openDatabase(dir)
341
+ } catch (error) {
342
+ if (error && error.code === 'SQLITE_UNAVAILABLE') throw error
343
+ throw unreadable(error)
344
+ }
326
345
  if (!db) return { present: false, fresh: false }
327
346
  try {
328
347
  let tables
@@ -330,8 +349,12 @@ export function eraseReadiness(dir) {
330
349
  if (!tables.has('records') || !tables.has('events')) {
331
350
  throw coded(DB_FILE + ' 缺表(' + ['records', 'events'].filter((t) => !tables.has(t)).join('、') + '):结构不全的库不能拿来擦,先移走它重新迁移。', 'STORAGE_INCOMPLETE')
332
351
  }
352
+ // sources 是"库和 JSONL 对不对得上"的唯一依据;没有它就没法判断过期,宁可拒绝
353
+ if (!tables.has('sources')) {
354
+ throw coded(DB_FILE + ' 缺 sources 表(阶段 1 早期建的库):没法判断这个库是不是过期,先移走它重新迁移。', 'STORAGE_INCOMPLETE')
355
+ }
333
356
  let fresh = true
334
- try { checkFresh(db, dir, tables.has('sources')) } catch (error) {
357
+ try { checkFresh(db, dir, true) } catch (error) {
335
358
  if (error && error.code === 'STORAGE_STALE') fresh = false
336
359
  else throw unreadable(error)
337
360
  }
@@ -341,24 +364,33 @@ export function eraseReadiness(dir) {
341
364
  }
342
365
  }
343
366
 
367
+ // 过期库擦完之后必须继续过期:把 sources 全都写成 -1 这个不可能等于真实字节数的哨兵。
368
+ // 只靠"不刷新"不够——JSONL 删小之后可能恰好缩回迁移时记的字节数,checkFresh 就会误判成"对得上"。
369
+ const STALE_SIZE = -1
370
+ function invalidateSources(db) {
371
+ const st = db.prepare('INSERT OR REPLACE INTO sources (file, size, migrated_at) VALUES (?, ?, ?)')
372
+ const at = new Date().toISOString()
373
+ for (const name of SOURCE_FILES) st.run(name, STALE_SIZE, at)
374
+ }
375
+
344
376
  /**
345
377
  * 从 SQLite 副本里删掉这些 id 的经历与关联事件(seal 保留,章节不指向经历所以不动)。
378
+ * 删除与 sources 更新在**同一个事务**里:要么都成,要么都不成(不会出现"记录删了、source 还挂着旧尺寸")。
346
379
  * @param {string} dir
347
380
  * @param {string[]} ids 要删的经历 id
348
- * @param {{ refreshSources?: boolean }} opts refreshSources:删完把 sources 的字节数刷成现在 JSONL 的大小
349
- * (只有擦除前库和 JSONL 对得上时才该这么做;否则会让一个缺记录的库看起来是新的)
381
+ * @param {{ refreshSources?: boolean }} opts refreshSources:擦除前库和 JSONL 对得上时才为 true
382
+ * (这时删完把 sources 的字节数刷成现在 JSONL 的大小;否则写 -1 哨兵,让库继续保持过期、读路径 fail closed)
350
383
  */
351
384
  export function eraseFromStore(dir, ids, { refreshSources = false } = {}) {
352
- const file = path.join(dir, DB_FILE)
353
- let exists = false
354
- try { exists = fs.existsSync(file) } catch { exists = false }
355
- if (!exists) return { present: false, records: 0, events: 0 }
385
+ if (!statDatabase(dir)) return { present: false, records: 0, events: 0 }
356
386
  const wanted = [...new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))]
357
387
  const db = openDatabase(dir)
358
388
  if (!db) return { present: false, records: 0, events: 0 }
359
389
  try {
360
390
  let records = 0
361
391
  let events = 0
392
+ // 擦除要把旧页里的字节也抹掉:否则被删的正文还留在库文件里(验收抓到的)
393
+ db.exec('PRAGMA secure_delete = ON')
362
394
  db.exec('BEGIN IMMEDIATE')
363
395
  try {
364
396
  const delRecord = db.prepare('DELETE FROM records WHERE id = ?')
@@ -375,12 +407,13 @@ export function eraseFromStore(dir, ids, { refreshSources = false } = {}) {
375
407
  events += Number(delSeq.run(row.seq).changes || 0)
376
408
  }
377
409
  }
410
+ if (refreshSources) writeSources(db, sourceSizes(dir))
411
+ else invalidateSources(db)
378
412
  db.exec('COMMIT')
379
413
  } catch (error) {
380
414
  try { db.exec('ROLLBACK') } catch { }
381
415
  throw error
382
416
  }
383
- if (refreshSources) writeSources(db, sourceSizes(dir))
384
417
  return { present: true, records, events }
385
418
  } finally {
386
419
  try { db.close() } catch { }
@@ -10,6 +10,8 @@ export interface Tombstone {
10
10
  actor: string
11
11
  /** 删除前那一行的 sha256(原样字节,不含行尾换行) */
12
12
  hash: string
13
+ /** 可选(阶段 4 复审后加):这一条经历在库里用过的所有 id(当前 id + 旧 id) */
14
+ ids?: string[]
13
15
  }
14
16
 
15
17
  export const eventsFile: (memDir: string) => string
package/lib/tombstones.js CHANGED
@@ -1,14 +1,18 @@
1
1
  // 墓碑(阶段 4):一条经历被**整条撤回**之后,只留这一行。
2
2
  //
3
- // 一行一个 { v: 1, id, at, reason, actor, hash }:
3
+ // 一行一个 { v: 1, id, at, reason, actor, hash, ids? }:
4
4
  // · id 被撤回那条经历的 id(不透明,永不复用;墓碑里留着它,才能核"这条存在过、被撤回了")
5
5
  // · at 撤回时间(ISO 8601)
6
6
  // · reason 为什么撤(人写的,短句;这是唯一由人提供的字段)
7
7
  // · actor 谁要求的(self / leo / host……,由宿主决定)
8
8
  // · hash 删除前那一行的 sha256(那一行原样字节,不含行尾换行;CRLF 的 \r 也不算)
9
+ // · ids 可选(阶段 4 复审后加):这一条经历在库里用过的所有 id(当前 id + 0.10 之前的旧 id)。
10
+ // 按旧 id 撤回时墓碑的 id 是旧 id,封存事件却挂在当前 id 上;体检靠这个字段把两边的账对上。
11
+ // 只加不减:老墓碑没有这个字段照样读。
9
12
  //
10
13
  // 墓碑**不含正文**,也**不能用来恢复**:它只说"有过这一条、什么时候、为什么没的"。
11
- // 只追加、不提供删除/清空的 API(库内 API 删不掉审计与墓碑;要动只能人拿编辑器来)。
14
+ // 只追加、不提供删除/清空的 API(库内 API 删不掉审计与墓碑;整目录导入是另一件事,
15
+ // archive.importArchive 会按导入包整体替换目录里的文件,见 docs/erase-audit-zh.md)。
12
16
  //
13
17
  // 为什么把墓碑单独放一个文件:撤回是破坏性操作,删除本身不可逆,唯一能事后核对的
14
18
  // 就是这一行。它必须比记录文件更难被顺手清掉,也必须一眼看得出只有 id 和哈希。
@@ -30,7 +34,8 @@ export function isValid(r) {
30
34
  typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) &&
31
35
  typeof r.reason === 'string' &&
32
36
  typeof r.actor === 'string' && r.actor.trim() &&
33
- typeof r.hash === 'string' && HASH.test(r.hash)
37
+ typeof r.hash === 'string' && HASH.test(r.hash) &&
38
+ (r.ids === undefined || (Array.isArray(r.ids) && r.ids.every((id) => typeof id === 'string' && id.trim())))
34
39
  )
35
40
  }
36
41
 
@@ -45,15 +50,20 @@ export function append(memDir, row) {
45
50
  return log.decide(memDir, () => ({ ...row })).row
46
51
  }
47
52
 
48
- // 某个 id 的墓碑;没有返回 null
53
+ // 某个 id 的墓碑(id 或 ids 里任一个对上);没有返回 null
49
54
  export function byId(memDir, id) {
50
55
  const key = String(id || '')
51
- return readAll(memDir).rows.find((r) => r.id === key) || null
56
+ return readAll(memDir).rows.find((r) => r.id === key || (Array.isArray(r.ids) && r.ids.includes(key))) || null
52
57
  }
53
58
 
54
- // 所有已撤回的 id(体检用来判断封存事件是不是指向一条"撤回过的"经历)
59
+ // 所有已撤回的 id(体检用来判断封存事件是不是指向一条"撤回过的"经历;id 与 ids 都算)
55
60
  export function ids(memDir) {
56
- return new Set(readAll(memDir).rows.map((r) => r.id))
61
+ const out = new Set()
62
+ for (const r of readAll(memDir).rows) {
63
+ out.add(r.id)
64
+ if (Array.isArray(r.ids)) for (const id of r.ids) out.add(id)
65
+ }
66
+ return out
57
67
  }
58
68
 
59
69
  // 坏行数(给 doctor / 诊断用):只给数字
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.26.0",
3
+ "version": "0.26.2",
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",