whale-memory-core 0.25.0 → 0.26.1

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/index.d.ts CHANGED
@@ -27,3 +27,8 @@ export * as changed from './lib/changed.js'
27
27
  export * as injection from './lib/injection.js'
28
28
  export * as selfActions from './lib/self-actions.js'
29
29
  export * as actionSource from './lib/action-source.js'
30
+ // 阶段 4:整条撤回(+ 墓碑)、审计、导出
31
+ export * as tombstones from './lib/tombstones.js'
32
+ export * as audit from './lib/audit.js'
33
+ export { eraseExperience } from './lib/erase.js'
34
+ export { exportMemory } from './lib/export-memory.js'
package/index.js CHANGED
@@ -29,3 +29,8 @@ export * as changed from './lib/changed.js'
29
29
  export * as selfActions from './lib/self-actions.js'
30
30
  export * as actionSource from './lib/action-source.js'
31
31
  export * as injection from './lib/injection.js'
32
+ // 阶段 4:整条撤回(+ 墓碑)、审计、导出
33
+ export * as tombstones from './lib/tombstones.js'
34
+ export * as audit from './lib/audit.js'
35
+ export { eraseExperience } from './lib/erase.js'
36
+ export { exportMemory } from './lib/export-memory.js'
package/lib/audit.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { AsOf, Experience, StorageBackendName } from './self-experience.js'
2
+
3
+ /** 审计行:只记 id 与动作,绝不记正文(召回只留查询的 sha256) */
4
+ export interface AuditRow {
5
+ at: string
6
+ /** 谁(self / leo / host……) */
7
+ actor: string
8
+ /** read / recall / erase(新增动作算兼容) */
9
+ action: string
10
+ ids: string[]
11
+ note: string
12
+ }
13
+
14
+ export const ACTIONS: readonly string[]
15
+ /** note 上限(字):审计只记动作,不记正文 */
16
+ export const LIMIT_NOTE: number
17
+ export function eventsFile(memDir: string): string
18
+ export function isValid(r: unknown): r is AuditRow
19
+ /** 查询的 sha256:审计只留这个指纹,不留原文 */
20
+ export function queryHash(query: unknown): string
21
+ export function record(memDir: string, row: { at?: string; actor: string; action: string; ids?: string[]; note?: string }): AuditRow
22
+ export function read(dir: string, opts?: { since?: string | Date | null; until?: string | Date | null; action?: string; actor?: string }): AuditRow[]
23
+ /** 坏行数(只数,不把整份读进内存) */
24
+ export function badLines(dir: string): number
25
+ /** 读一条并留 read 审计(找不到也留;返回 null) */
26
+ export function readRecord(dir: string, id: string, opts?: { actor: string; note?: string; backend?: StorageBackendName; asOf?: AsOf }): Experience | null
27
+ /** 召回一次并留 recall 审计(只留查询哈希 + 命中 id) */
28
+ export function recall(dir: string, query: string, opts?: {
29
+ actor: string
30
+ note?: string
31
+ limit?: number
32
+ backend?: StorageBackendName
33
+ includeSealed?: boolean
34
+ ranker?: 'literal' | 'hybrid' | null
35
+ gate?: 'cover' | 'legacy'
36
+ mode?: 'strict' | 'loose'
37
+ asOf?: AsOf
38
+ }): Experience[]
39
+ export function noteRead(dir: string, opts: { actor: string; ids?: string[]; note?: string }): AuditRow
40
+ export function noteRecall(dir: string, opts: { actor: string; ids?: string[]; query?: string; note?: string }): AuditRow
41
+ export const internals: { FILE: string }
package/lib/audit.js ADDED
@@ -0,0 +1,167 @@
1
+ // 审计(阶段 4):只追加的 audit.jsonl,一行一个 { at, actor, action, ids, note }。
2
+ //
3
+ // 目的只有一个:出了事能回答"谁在什么时候读过/召回/撤回过哪几条"。
4
+ // 因此它有两条硬规矩:
5
+ // 1. **不记正文**。正文、查询原文、经历的一句话摘要都不进来。召回只留查询的 sha256(note = "qsha256:<hex>")。
6
+ // 2. **库内 API 删不掉它**。这里只导出追加与只读查询,没有删除/清空/改写;要动只能人拿编辑器来。
7
+ //
8
+ // 不自动挂在读路径上:loadAll / recall 是纯读(备份、体检、评测都靠它们),在库里偷偷写文件
9
+ // 会让"读"不再只读,也会让只读盘上的库直接报错。宿主在"要留痕"的那个边界调 noteRead / noteRecall;
10
+ // eraseExperience 自己写 erase 那一条。
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import crypto from 'node:crypto'
14
+ import { withFileLock } from './file-lock.js'
15
+ import { readLines } from './jsonl-stream.js'
16
+ import { currentView, recall as recallInner } from './self-experience.js'
17
+
18
+ const FILE = 'audit.jsonl'
19
+ // note 只给"这条是什么动作"用:限长,防止有人顺手把正文/查询原文塞进来
20
+ export const LIMIT_NOTE = 500
21
+
22
+ // 动作:至少这三类。别的名字也收(新增动作算兼容),但必须是非空字符串
23
+ export const ACTIONS = Object.freeze(['read', 'recall', 'erase'])
24
+
25
+ export const eventsFile = (memDir) => path.join(memDir, FILE)
26
+
27
+ export function isValid(r) {
28
+ return Boolean(
29
+ r &&
30
+ typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) &&
31
+ typeof r.actor === 'string' && r.actor.trim() &&
32
+ typeof r.action === 'string' && r.action.trim() &&
33
+ Array.isArray(r.ids) && r.ids.every((id) => typeof id === 'string') &&
34
+ typeof r.note === 'string'
35
+ )
36
+ }
37
+
38
+ // 查询哈希:只留指纹,不留原文(查询里经常带着她写的原话)
39
+ export const queryHash = (query) => crypto.createHash('sha256').update(String(query ?? ''), 'utf8').digest('hex')
40
+
41
+ // 追加一条:先校验再写;锁内只 append,不重读整个文件(审计会越来越长)
42
+ export function record(memDir, { at = new Date().toISOString(), actor, action, ids = [], note = '' } = {}) {
43
+ const row = {
44
+ at: String(at),
45
+ actor: String(actor ?? '').trim(),
46
+ action: String(action ?? '').trim(),
47
+ ids: (Array.isArray(ids) ? ids : []).map(String),
48
+ note: String(note ?? '')
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)')
53
+ if (!isValid(row)) throw new Error('审计行不合格(需要 at / actor / action / ids / note),拒绝写入。(audit row is not valid)')
54
+ fs.mkdirSync(memDir, { recursive: true })
55
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
56
+ const file = eventsFile(memDir)
57
+ let prefix = ''
58
+ try {
59
+ const st = fs.statSync(file)
60
+ if (st.size) {
61
+ const fd = fs.openSync(file, 'r')
62
+ const buf = Buffer.alloc(1)
63
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
64
+ fs.closeSync(fd)
65
+ if (buf[0] !== 10) prefix = '\n'
66
+ }
67
+ } catch { }
68
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
69
+ return row
70
+ })
71
+ }
72
+
73
+ // 读一次(宿主在"她要看这一条"的边界调它):返回记录(找不到返回 null),并留一条 read 审计
74
+ export function readRecord(dir, id, { actor, note = '', backend = 'file', asOf = null } = {}) {
75
+ const row = currentView(dir, String(id), { asOf, backend })
76
+ record(dir, { actor, action: 'read', ids: [String(id)], note })
77
+ return row
78
+ }
79
+
80
+ // 召回一次并留一条 recall 审计:只留查询哈希 + 命中 id,不留查询原文
81
+ export function recall(dir, query, { actor, note = '', ...opts } = {}) {
82
+ const hits = recallInner(dir, query, opts)
83
+ record(dir, { actor, action: 'recall', ids: hits.map((r) => r.id), note: note || 'qsha256:' + queryHash(query) })
84
+ return hits
85
+ }
86
+
87
+ // 坏行数(给 doctor / 诊断用):只数,不返回任何一行——审计可能很长,体检不该把整份读进内存
88
+ export function badLines(dir) {
89
+ let fd
90
+ try {
91
+ fd = fs.openSync(eventsFile(dir), 'r')
92
+ } catch (error) {
93
+ if (error && error.code === 'ENOENT') return 0
94
+ const wrapped = new Error('审计文件读不出来(' + FILE + '):' + String(error && error.message ? error.message : error))
95
+ wrapped.code = 'AUDIT_UNREADABLE'
96
+ wrapped.cause = error
97
+ throw wrapped
98
+ }
99
+ let bad = 0
100
+ try {
101
+ for (const line of readLines(fd)) {
102
+ if (!line.text.trim()) continue
103
+ let row
104
+ try { row = JSON.parse(line.text) } catch { bad += 1; continue }
105
+ if (!isValid(row)) bad += 1
106
+ }
107
+ } finally {
108
+ fs.closeSync(fd)
109
+ }
110
+ return bad
111
+ }
112
+
113
+ // 只读查询:按动作 / 按人 / 按时间(ISO 或 Date,左闭右开),按追加顺序返回
114
+ export function read(dir, { since = null, until = null, action = '', actor = '' } = {}) {
115
+ const from = since === null || since === undefined || since === '' ? null : ms(since, 'since')
116
+ const to = until === null || until === undefined || until === '' ? null : ms(until, 'until')
117
+ const wantAction = String(action || '')
118
+ const wantActor = String(actor || '')
119
+ const rows = []
120
+ let bad = 0
121
+ let fd
122
+ try {
123
+ fd = fs.openSync(eventsFile(dir), 'r')
124
+ } catch (error) {
125
+ if (error && error.code === 'ENOENT') return []
126
+ const wrapped = new Error('审计文件读不出来(' + FILE + '):' + String(error && error.message ? error.message : error))
127
+ wrapped.code = 'AUDIT_UNREADABLE'
128
+ wrapped.cause = error
129
+ throw wrapped
130
+ }
131
+ try {
132
+ for (const line of readLines(fd)) {
133
+ if (!line.text.trim()) continue
134
+ let row
135
+ try { row = JSON.parse(line.text) } catch { bad += 1; continue }
136
+ if (!isValid(row)) { bad += 1; continue }
137
+ const t = Date.parse(row.at)
138
+ if (from !== null && t < from) continue
139
+ if (to !== null && t >= to) continue
140
+ if (wantAction && row.action !== wantAction) continue
141
+ if (wantActor && row.actor !== wantActor) continue
142
+ rows.push(row)
143
+ }
144
+ } finally {
145
+ fs.closeSync(fd)
146
+ }
147
+ // 坏行不静默:审计读不完整时宁可报错,也不给一份"看起来没问题"的审计
148
+ if (bad > 0) {
149
+ const error = new Error('审计文件有 ' + bad + ' 行无法解析或不合格:这份审计不完整,不能当真。(' + bad + ' unreadable audit line(s))')
150
+ error.code = 'AUDIT_CORRUPT'
151
+ error.bad = bad
152
+ throw error
153
+ }
154
+ return rows
155
+ }
156
+
157
+ function ms(v, name) {
158
+ const t = v instanceof Date ? v.getTime() : Date.parse(String(v))
159
+ if (!Number.isFinite(t)) throw new Error(name + ' 不是合法时间(用 ISO 时间或 Date)。(invalid audit time filter)')
160
+ return t
161
+ }
162
+
163
+ // 宿主边界用的顺手别名(名字直白一点,别让调用方去记 action 字符串)
164
+ export const noteRead = (dir, { actor, ids, note = '' } = {}) => record(dir, { actor, action: 'read', ids, note })
165
+ export const noteRecall = (dir, { actor, ids, query = '', note = '' } = {}) => record(dir, { actor, action: 'recall', ids, note: note || 'qsha256:' + queryHash(query) })
166
+
167
+ export const internals = { FILE }
package/lib/erase.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ export interface EraseRemoved {
2
+ /** 删掉了几行经历(重复 id 的副本会一起删) */
3
+ records: number
4
+ later: number
5
+ recall: number
6
+ unfinished: number
7
+ link: number
8
+ /** 文件里同一个 id 出现多次时,除第一行外多删了几行 */
9
+ duplicates?: number
10
+ /** 目录里有 memory.sqlite 时,是否也删了库里的副本 */
11
+ sqlite: boolean
12
+ sqliteRecords: number
13
+ sqliteEvents: number
14
+ }
15
+
16
+ export interface EraseResult {
17
+ ok: true
18
+ id: string
19
+ /** 第二次(或本来就没有):没删任何东西,也没再写墓碑 */
20
+ alreadyGone: boolean
21
+ /** 撤回时间(ISO 8601);alreadyGone 且从没写过墓碑时是空串 */
22
+ at: string
23
+ /** 删除前那一行的 sha256 */
24
+ hash?: string
25
+ /** 这次有没有墓碑在手:true = 确实撤回并留了墓碑(或之前已撤回);false = 本来就没有这条记录(id 可能抄错) */
26
+ tombstone: boolean
27
+ actor?: string
28
+ reason?: string
29
+ removed: EraseRemoved
30
+ }
31
+
32
+ /**
33
+ * 整条撤回:记录 + later / recall / unfinished / link 事件物理删除,seal 事件保留,
34
+ * 成功后在 tombstones.jsonl 留一块墓碑(id / 时间 / 原因 / 哈希,不含正文)。
35
+ *
36
+ * 幂等;坏行 / 读不出来 / SQLite 副本删不了都整次拒绝(不许只删一半)。
37
+ * 只由宿主在"她本人或 Leo 明确要求"时调用;库不自动擦除。
38
+ */
39
+ export function eraseExperience(dir: string, opts: { id: string; reason: string; actor: string; now?: Date | string }): EraseResult
40
+ export const internals: { RECORDS: string; EVENT_FILES: string[] }
package/lib/erase.js ADDED
@@ -0,0 +1,269 @@
1
+ // 整条撤回(阶段 4):把一条经历连同挂在它身上的事件从库里物理删掉,只留一块墓碑。
2
+ //
3
+ // 为什么允许删除、但不允许改:契约里"记录不可变"防的是**篡改历史**(把当时写的话换掉)。
4
+ // 整条撤回是另一件事:她(或 Leo)明确要求"这件事不要再留在库里",那就整条拿掉;
5
+ // 拿掉之后留一行墓碑(id / 时间 / 原因 / 哈希),让"这条存在过、被撤回了"仍然可核。
6
+ //
7
+ // 守住的几条:
8
+ // · 不改别的记录:没被撤回的行**一个字节都不动**(含它引用了被撤回那条的 then.refs——
9
+ // 那是她当时写下的原文,不许替她删改;读的时候那段引用会显示"找不到了")。
10
+ // · 先查后删:经历文件或要重写的事件文件里有坏行,**整次拒绝**——坏行说不清是不是那条,
11
+ // 不能假装删干净了。擦除不做"尽量"。
12
+ // · 文件原子:读全量 → 过滤 → 写 .tmp → rename(见 file-lock.writeFileAtomic),
13
+ // 永远不会出现"写了一半"的经历文件;墓碑写下之前任何一步失败,改过的文件按原样放回去。
14
+ // · 先删事件、再删经历:万一进程在中间被杀,记录还在,重跑还能把墓碑补出来。
15
+ // · 幂等:第二次调用返回 { ok: true, alreadyGone: true, tombstone: true },不再写第二条墓碑;
16
+ // 本来就没有这条记录时返回 alreadyGone + `tombstone: false`(宿主能分清"已撤回"和"id 抄错了")。
17
+ // · 只由宿主在"她本人或 Leo 明确要求"时调用;库不自动擦除,也没有定时清理。
18
+ //
19
+ // 做不到(文档里也写清):备份与快照里的历史副本不追溯;SQLite 删除后文件页里可能残留旧字节
20
+ // (安全删除 / VACUUM 不在承诺里);多写者不承诺(同一目录并发写按契约本来就是单写者假设);
21
+ // seal 事件的 note 是人的自由文本,可能提到原话,不在本函数删除范围内。
22
+ import fs from 'node:fs'
23
+ import path from 'node:path'
24
+ import crypto from 'node:crypto'
25
+ import { withFileLock, writeFileAtomic } from './file-lock.js'
26
+ import { readLines } from './jsonl-stream.js'
27
+ import * as tombstones from './tombstones.js'
28
+ import * as audit from './audit.js'
29
+ import { internals as expInternals } from './self-experience.js'
30
+ import { eraseReadiness, eraseFromStore } from './sqlite-store.js'
31
+
32
+ const RECORDS = 'self-experience.jsonl'
33
+ // 挂在这条经历上的事件文件:撤回了就一起删。
34
+ // seal-events 不删:封存是"别再主动提起"的状态记录,不是正文;删了反而让"曾经封存过"这段历史断掉。
35
+ // chapter-events 不删:章节按日子命名一段时间,不指向某一条经历(见 link/chapter 的事件格式)。
36
+ const EVENT_FILES = ['later-events.jsonl', 'recall-events.jsonl', 'unfinished-events.jsonl', 'link-events.jsonl']
37
+ const LIMIT_REASON = 500
38
+
39
+ const coded = (message, code, extra = {}) => Object.assign(new Error(message), { code }, extra)
40
+
41
+ function readLinesOf(dir, name) {
42
+ const file = path.join(dir, name)
43
+ let fd
44
+ try {
45
+ fd = fs.openSync(file, 'r')
46
+ } catch (error) {
47
+ if (error && error.code === 'ENOENT') return { exists: false, lines: [], bad: 0 }
48
+ throw coded('要擦除的文件读不出来(' + name + '):' + String(error && error.message ? error.message : error), 'ERASE_UNREADABLE', { cause: error })
49
+ }
50
+ try {
51
+ const lines = []
52
+ let bad = 0
53
+ for (const line of readLines(fd)) {
54
+ if (!line.text.trim()) continue
55
+ let row
56
+ try { row = JSON.parse(line.text) } catch { row = undefined; bad += 1 }
57
+ lines.push({ text: line.text, row })
58
+ }
59
+ return { exists: true, lines, bad }
60
+ } finally {
61
+ fs.closeSync(fd)
62
+ }
63
+ }
64
+
65
+ // 一行算不算"她的一条经历"(口径与 self-experience.normalize 一致;这里用它的实现,不另抄一份)
66
+ function recordOf(row) {
67
+ if (!row || typeof row !== 'object') return null
68
+ const normalized = expInternals.normalize(row)
69
+ return normalized && normalized.then && normalized.then.text ? normalized : null
70
+ }
71
+
72
+ // 事件行指向了哪些经历 id:联想是 from/to,其余三类是 id
73
+ function eventIdsOf(row) {
74
+ if (!row || typeof row !== 'object') return []
75
+ const out = []
76
+ for (const key of ['id', 'from', 'to']) if (row[key] !== undefined && row[key] !== null) out.push(String(row[key]))
77
+ return out
78
+ }
79
+
80
+ const hashOfLine = (text) => crypto.createHash('sha256').update(String(text).replace(/\r$/, ''), 'utf8').digest('hex')
81
+
82
+ // 把经历文件解析成一行一条,并按 identifyRaw 同一套规则认领旧 id。
83
+ // 返回 { infos, target, ambiguous }:target 是要删掉的**当前 id** 集合(含通过旧 id 认领到的)
84
+ function analyse(records, id) {
85
+ const key = String(id)
86
+ const infos = records.lines.map((line) => {
87
+ const row = recordOf(line.row)
88
+ return { line, row, rawFormerId: row && row.formerId ? String(row.formerId) : '' }
89
+ })
90
+ const owners = new Map()
91
+ const explicit = new Set()
92
+ for (const info of infos) {
93
+ if (!info.row) continue
94
+ if (!info.row.formerId) explicit.add(info.row.id)
95
+ else {
96
+ const list = owners.get(info.row.formerId)
97
+ if (list) list.push(info.row.id)
98
+ else owners.set(info.row.formerId, [info.row.id])
99
+ }
100
+ }
101
+ // 同一个旧 id 被几条经历共用:不猜,报错让她用当前 id
102
+ if ((owners.get(key) || []).length > 1 && !explicit.has(key)) {
103
+ throw coded('这个旧 id 有好几条经历共用(' + key + '):先用 read 看一下当前 id 再撤回。(legacy id is ambiguous)', 'ERASE_AMBIGUOUS_ID')
104
+ }
105
+ for (const info of infos) {
106
+ if (info.row && info.row.formerId && (owners.get(info.row.formerId).length !== 1 || explicit.has(info.row.formerId))) info.row.formerId = ''
107
+ }
108
+ const target = new Set([key])
109
+ for (const info of infos) {
110
+ if (!info.row) continue
111
+ if (info.row.formerId === key) target.add(String(info.row.id))
112
+ }
113
+ return { infos, target }
114
+ }
115
+
116
+ // 改写一个文件(真正的删除动作)。写之前把原文记进 journal:任何一步失败都能原样放回去。
117
+ // 返回删掉的行数;一行都没删就不碰文件。
118
+ function rewriteTracked(dir, name, lines, keep, journal) {
119
+ const kept = []
120
+ let removed = 0
121
+ for (const line of lines) {
122
+ if (keep(line)) kept.push(line.text)
123
+ else removed += 1
124
+ }
125
+ if (!removed) return 0
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' : '')
131
+ return removed
132
+ }
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
+
153
+ /**
154
+ * 整条撤回一条经历。
155
+ *
156
+ * @param {string} dir 记忆目录
157
+ * @param {{ id: string, reason: string, actor: string, now?: Date|string }} opts
158
+ * id:要撤回的经历 id(也收 0.10 之前那个唯一对应的旧 id)
159
+ * reason:为什么撤回(人写的短句,写进墓碑;不写正文)
160
+ * actor:谁要求的(self / leo / host……,写进墓碑与审计)
161
+ * @returns {{ ok: true, id: string, alreadyGone: boolean, at: string, hash?: string, removed: object }}
162
+ */
163
+ export function eraseExperience(dir, { id, reason = '', actor = '', now = new Date() } = {}) {
164
+ const key = String(id || '').trim()
165
+ if (!key) throw new Error('需要 id:说清要撤回哪一条经历。(missing id)')
166
+ if (!String(reason || '').trim()) throw new Error('需要 reason:撤回是破坏性操作,必须说清为什么(会写进墓碑)。(missing reason)')
167
+ if (String(reason).length > LIMIT_REASON) throw new Error('reason 太长(' + String(reason).length + '/' + LIMIT_REASON + ' 字)。(reason is too long)')
168
+ if (!String(actor || '').trim()) throw new Error('需要 actor:说清是谁要求的(self / leo / host……)。(missing actor)')
169
+ const actorText = String(actor).trim()
170
+ const at = (now instanceof Date ? now : new Date(now)).toISOString()
171
+
172
+ fs.mkdirSync(dir, { recursive: true })
173
+ // 同一目录的撤回串行化;它跟事件文件各自的锁不是同一把,但擦除本身是单写者操作
174
+ return withFileLock(path.join(dir, 'erase.lock'), () => {
175
+ // 1) 账本先看一遍:墓碑文件坏了就不知道撤回没撤回,宁可不猜
176
+ const marks = tombstones.readAll(dir)
177
+ if (marks.bad > 0) throw coded('墓碑文件有 ' + marks.bad + ' 行无法解析:先修好再撤回,不然没法确认这条是不是已经撤回过。(tombstones are corrupt)', 'ERASE_TOMBSTONES_CORRUPT', { bad: marks.bad })
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() }
180
+
181
+ // 2) 读全量 + 预检:坏行 / 读不出来都整次拒绝,一个字节都不改
182
+ const records = readLinesOf(dir, RECORDS)
183
+ if (records.bad > 0) throw coded('经历文件有 ' + records.bad + ' 行无法解析:撤回没法保证删干净,先修好或先备份。(records are corrupt)', 'ERASE_RECORDS_CORRUPT', { bad: records.bad })
184
+ const events = EVENT_FILES.map((name) => ({ name, ...readLinesOf(dir, name) }))
185
+ const badEvent = events.find((e) => e.bad > 0)
186
+ if (badEvent) throw coded('事件文件 ' + badEvent.name + ' 有 ' + badEvent.bad + ' 行无法解析:撤回没法保证删干净,先修好再撤回。(events are corrupt)', 'ERASE_EVENTS_CORRUPT', { file: badEvent.name, bad: badEvent.bad })
187
+
188
+ // 3) 目录里有 SQLite 副本:先确认它打不开/不全(那就整次拒绝,不许只删一半),
189
+ // 顺便记下它跟 JSONL 对不对得上——决定删完要不要刷新 sources
190
+ const store = eraseReadiness(dir)
191
+
192
+ // 4) 认领要删的 id(含旧 id),并取出删除前那一行的哈希
193
+ const analysed = analyse(records, key)
194
+ const doomed = analysed.infos.filter((info) => info.row && analysed.target.has(String(info.row.id)))
195
+ const removed = emptyRemoved()
196
+ let hash = ''
197
+ if (doomed.length) {
198
+ hash = hashOfLine(doomed[0].line.text)
199
+ if (doomed.length > 1) removed.duplicates = doomed.length - 1
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
+ const tombIds = [...new Set([key, ...analysed.target, ...formerIds])]
207
+ const eventIds = new Set(tombIds)
208
+
209
+ const journal = []
210
+ let tombstoned = false
211
+ try {
212
+ // 5) 先删事件、再删经历:万一进程在中间被杀,记录还在,重跑还能把墓碑补出来。
213
+ // 每一步写之前都把原文记进 journal;任何一步失败就整体放回去(墓碑写下之前)。
214
+ for (const file of events) {
215
+ removed[shortName(file.name)] = rewriteTracked(dir, file.name, file.lines, (line) => !eventIdsOf(line.row).some((x) => eventIds.has(x)), journal)
216
+ }
217
+ removed.records = rewriteTracked(dir, RECORDS, records.lines, (line) => {
218
+ const row = recordOf(line.row)
219
+ return !(row && analysed.target.has(String(row.id)))
220
+ }, journal)
221
+
222
+ // 6) SQLite 副本:记录 + 事件一起删(seal 留),删完按擦除前是否对得上决定刷不刷 sources
223
+ const sq = eraseFromStore(dir, tombIds, { refreshSources: store.fresh })
224
+ if (sq.present) { removed.sqliteRecords = sq.records; removed.sqliteEvents = sq.events }
225
+ removed.sqlite = Boolean(sq.present)
226
+
227
+ // 7) 什么都没找到:这次是"已经没了"(崩溃后重跑也走这里:顺手把残留事件清掉)
228
+ if (!doomed.length) return { ok: true, id: key, alreadyGone: true, at: '', tombstone: false, removed }
229
+
230
+ // 8) 墓碑:删除成功之后才写(墓碑不会早于删除出现,谎报"已撤回")
231
+ // ids 记下"这一条经历在库里用过的所有 id"(当前 id + 旧 id),体检核对封存事件时用
232
+ try {
233
+ tombstones.append(dir, { v: 1, id: key, ids: tombIds, at, reason: String(reason).trim(), actor: actorText, hash })
234
+ } catch (error) {
235
+ throw coded('墓碑写失败:' + String(error && error.message ? error.message : error) + '。(tombstone write failed)', 'ERASE_TOMBSTONE_FAILED', { cause: error })
236
+ }
237
+ tombstoned = true
238
+
239
+ // 9) 审计:只记 id 与动作,不记正文(reason 里有人的话,不往审计里抄)
240
+ try {
241
+ audit.record(dir, { actor: actorText, action: 'erase', ids: [key], note: 'tombstone' })
242
+ } catch (error) {
243
+ throw coded('记录与墓碑都在,但审计追加失败:' + String(error && error.message ? error.message : error) + '。(audit write failed after erase)', 'ERASE_AUDIT_FAILED', { cause: error, erased: true })
244
+ }
245
+
246
+ return { ok: true, id: key, alreadyGone: false, at, hash, tombstone: true, actor: actorText, reason: String(reason).trim(), removed }
247
+ } catch (error) {
248
+ // 墓碑还没写下 = 这次撤回不算数:把改过的文件按原样放回去(SQLite 的事务自己回滚;
249
+ // 万一删除已经在库里提交过,回滚后库会判为过期、读路径 fail closed,重新迁移即可)
250
+ if (!tombstoned) {
251
+ const failures = rollbackFiles(dir, journal)
252
+ if (failures.length) {
253
+ throw coded(String(error && error.message ? error.message : error) + ';回滚失败:' + failures.join(';') + '(文件可能只删了一半,先别对外说撤回了)。(rollback failed)', 'ERASE_ROLLBACK_FAILED', { cause: error, rollback: failures })
254
+ }
255
+ // 回滚干净了:宿主看到的应该是"这次没撤成",而不是一个光秃秃的 EPERM
256
+ throw coded('擦除没有完成(改过的文件已按原样放回):' + String(error && error.message ? error.message : error) + '。(erase aborted, files rolled back)', (error && error.code) || 'ERASE_FAILED', { cause: error })
257
+ }
258
+ throw error
259
+ }
260
+ })
261
+ }
262
+
263
+ function emptyRemoved() {
264
+ return { records: 0, later: 0, recall: 0, unfinished: 0, link: 0, sqlite: false, sqliteRecords: 0, sqliteEvents: 0 }
265
+ }
266
+
267
+ const shortName = (file) => file.replace(/-events\.jsonl$/, '')
268
+
269
+ export const internals = { RECORDS, EVENT_FILES }
@@ -0,0 +1,18 @@
1
+ import type { StorageBackendName } from './self-experience.js'
2
+
3
+ /**
4
+ * 导出记忆为 JSONL 文本(一行一条,末尾带换行;没有记录时返回空字符串)。
5
+ * 每一行就是 loadAll 在同条件下返回的那一条,唯一差别是封存状态记成 sealed: true(不导出封存理由)。
6
+ * 只读:不写回任何数据文件,也不写审计/墓碑。
7
+ */
8
+ export function exportMemory(dir: string, opts?: {
9
+ /** 只导出这个人的(匹配 then.state.personId / then.state.person / 顶层 personId) */
10
+ personId?: string
11
+ /** 按本地日截,含端点 */
12
+ from?: string | Date | null
13
+ to?: string | Date | null
14
+ /** 默认 true(封存内容照样导出,标 sealed: true);false = 完全排除封存内容 */
15
+ includeSealed?: boolean
16
+ backend?: StorageBackendName
17
+ }): string
18
+ export const internals: { personOf: (row: unknown) => string }
@@ -0,0 +1,69 @@
1
+ // 导出(阶段 4):把记忆库导成 JSONL。
2
+ //
3
+ // 和"书 / 回顾"那种展示型导出不同:这是**整份数据口径**——封存的内容默认也导出,
4
+ // 只是打上 sealed: true(不给封存理由,理由里可能有她写下的原话)。
5
+ // 要"只导没封存的",传 includeSealed: false。
6
+ //
7
+ // 每一行就是 loadAll 在同条件(backend / 封存口径)下返回的那一条,唯一差别是封存状态记成 true。
8
+ // 因此"导出与同条件全量读逐条一致"是可验证的(tests/erase-audit-export.test.mjs)。
9
+ //
10
+ // 只读:不写回任何数据文件,不建目录,不追加审计/墓碑。
11
+ //
12
+ // 规模:整份导出必然要把全部记录读进内存(loadAll 就是这个代价)。十万条以上、内存吃紧时,
13
+ // 用 self-experience.iterate 一条一条自己写文件——这条路径不替你猜"要流到哪去"。
14
+ import { loadAll } from './self-experience.js'
15
+ import { parseAsOf, dayOf } from './as-of.js'
16
+
17
+ // from / to 按"本地日"截,含端点;'2026-11-01' 与完整 ISO 都收
18
+ function dayBound(value, name) {
19
+ if (value === null || value === undefined || value === '') return ''
20
+ try {
21
+ return dayOf(parseAsOf(value))
22
+ } catch (error) {
23
+ throw new Error(name + ' 不是合法日期(用 2026-11-01 这样的日期或完整 ISO 时间)。(invalid ' + name + ')')
24
+ }
25
+ }
26
+
27
+ // 一条记录属于谁:v1 记录本身不带 person 字段;只有宿主把 personId 写进 then.state 时才有意义
28
+ const personOf = (row) => String(
29
+ (row && row.then && row.then.state && row.then.state.personId) ||
30
+ (row && row.then && row.then.state && row.then.state.person) ||
31
+ (row && row.personId) ||
32
+ ''
33
+ )
34
+
35
+ /**
36
+ * 导出记忆为 JSONL 文本(一行一条,末尾带换行;没有记录时返回空字符串)。
37
+ *
38
+ * @param {string} dir 记忆目录
39
+ * @param {{ personId?: string, from?: string|Date|null, to?: string|Date|null, includeSealed?: boolean, backend?: 'file'|'sqlite' }} opts
40
+ * personId:只导出这个人的(匹配 then.state.personId / then.state.person / 顶层 personId)
41
+ * from / to:按本地日截,含端点
42
+ * includeSealed:默认 true(封存内容照样导出,标 sealed: true);false = 完全排除封存内容
43
+ * backend:读哪个容器(默认 file;sqlite 的可用性/过期规则与 loadAll 相同)
44
+ * @returns {string}
45
+ */
46
+ export function exportMemory(dir, { personId = '', from = null, to = null, includeSealed = true, backend = 'file' } = {}) {
47
+ const fromDay = dayBound(from, 'from')
48
+ const toDay = dayBound(to, 'to')
49
+ if (fromDay && toDay && fromDay > toDay) throw new Error('from 不能晚于 to。(from is after to)')
50
+ const who = String(personId || '')
51
+ const rows = loadAll(dir, { backend })
52
+ const out = []
53
+ for (const row of rows) {
54
+ const day = String((row && row.day) || '')
55
+ if (fromDay && day < fromDay) continue
56
+ if (toDay && day > toDay) continue
57
+ if (who && personOf(row) !== who) continue
58
+ if (row.sealed) {
59
+ if (!includeSealed) continue
60
+ // 封存理由(seal.note)不导出:那是"封存之后才写下的",不是记录本身
61
+ out.push(JSON.stringify({ ...row, sealed: true }))
62
+ } else {
63
+ out.push(JSON.stringify(row))
64
+ }
65
+ }
66
+ return out.length ? out.join('\n') + '\n' : ''
67
+ }
68
+
69
+ export const internals = { personOf }
@@ -1,6 +1,6 @@
1
1
  // 她选择的遗忘:封存 / 解封。一行一个 { id, at, day, action, note? },只追加
2
2
  // 封存不是删除:原文、后记、选择都还在;只是不再被主动想起(召回、醒来、别的回想里的摘要都避开它)
3
- // 要真的抹掉,仍然只有 purge 整库删除
3
+ // 要真的抹掉一条,用 eraseExperience(阶段 4:整条撤回 + 墓碑);封存事件本身不删
4
4
  import fs from 'node:fs'
5
5
  import path from 'node:path'
6
6
  import { withFileLock } from './file-lock.js'
@@ -213,4 +213,11 @@ export interface RecallContextItem {
213
213
  /** 宿主拿用户原话自动召回用;默认 gate 为 cover(0.17 起),升级不改变自动递回的行为 */
214
214
  export function recallForContext(dir: string, query: string, opts?: { max?: number; gate?: 'cover' | 'legacy' }): RecallContextItem[]
215
215
 
216
- export const internals: { WEIGHTS: Set<Weight>; FILE: string }
216
+ export const internals: {
217
+ WEIGHTS: Set<Weight>
218
+ FILE: string
219
+ /** 一行原样 → 归一化后的经历(旧格式补 id / formerId);给擦除复用同一套口径 */
220
+ normalize: (row: unknown) => Experience | null
221
+ /** 0.10 之前没有 id 的旧行,按内容推出稳定 id */
222
+ legacyId: (row: Record<string, unknown>) => string
223
+ }
@@ -1153,7 +1153,8 @@ export function renderTwoPart(entry, { now = new Date(), lang = 'zh' } = {}) {
1153
1153
  return lines.join('\n')
1154
1154
  }
1155
1155
 
1156
- export const internals = { WEIGHTS, FILE }
1156
+ // 给擦除(阶段 4)复用的内部口径:一行原样 → 她的一条经历(含旧格式的 id 推导)
1157
+ export const internals = { WEIGHTS, FILE, normalize, legacyId }
1157
1158
  // 兼容旧调用:只要一句摘要的地方仍可用
1158
1159
  // 宿主拿用户的原话直接来召回、再自动塞进提示词:默认走 strict 的新口径(cover)。
1159
1160
  // 旧口径(legacy)在同批用例上编造率 27.8%(见 docs/eval.md),自动递回不能默认用它;
@@ -301,3 +301,118 @@ export function readEvents(db, kind) {
301
301
  export function readRecords(db) {
302
302
  return parseColumn(db.prepare('SELECT json FROM records ORDER BY rowid').all().map((r) => r.json))
303
303
  }
304
+
305
+ // ---------------------------------------------------------------- 擦除(阶段 4)
306
+ //
307
+ // 撤回一条经历时,SQLite 副本里也得把它删掉——不然 JSONL 里没了、库里还留着,等于没删干净。
308
+ // 两件事必须分开:
309
+ // 1. eraseReadiness():动手之前先确认"库在不在、结构全不全、和 JSONL 对不对得上"。
310
+ // 拿不到 node:sqlite / 库缺表 → 直接抛(不许只删一半:一边删了、另一边删不了最糟)。
311
+ // "过期"不算错——照样能删,但**不能刷新 sources**,否则会把"库缺了最近的记录"伪装成"库是新的"。
312
+ // 2. eraseFromStore():一个事务里删 records + events(seal 留着),提交后按需刷新 sources。
313
+ // 墓碑写失败不回滚删除,这个取舍写在 docs/erase-audit-zh.md 里。
314
+ //
315
+ // 注意:SQLite 删除行之后,旧字节可能还留在文件页里(没有 VACUUM / secure_delete)。
316
+ // 这不是"没擦掉",是"磁盘上的碎片不追溯"——和备份里的历史副本一样,文档里写明不承诺。
317
+
318
+ // 库文件本身的存在性/形状:不存在 = null;是目录 / 0 字节 = 抛(不能当"没有库"糊弄过去)
319
+ function statDatabase(dir) {
320
+ const file = path.join(dir, DB_FILE)
321
+ let st
322
+ try {
323
+ st = fs.statSync(file)
324
+ } catch (error) {
325
+ if (error && error.code === 'ENOENT') return null
326
+ throw coded(DB_FILE + ' 读不出来:' + String(error && error.message ? error.message : error), 'STORAGE_UNREADABLE')
327
+ }
328
+ if (!st.isFile()) throw coded(DB_FILE + ' 不是普通文件(是目录?):不能当库用,先移走它。', 'STORAGE_UNREADABLE')
329
+ if (st.size === 0) throw coded(DB_FILE + ' 是 0 字节的空文件,不是完整的库(先移走它重新迁移)。', 'STORAGE_INCOMPLETE')
330
+ return st
331
+ }
332
+
333
+ /** 擦除前的体检:库不存在 = { present:false };存在但打不开/不全/0 字节 = 抛;过期 = fresh:false。 */
334
+ export function eraseReadiness(dir) {
335
+ // 没有库就不碰 node:sqlite:Node 20 上擦一个只用 file 后端的目录必须照常能跑
336
+ if (!statDatabase(dir)) return { present: false, fresh: false }
337
+ let db
338
+ try {
339
+ db = openDatabase(dir)
340
+ } catch (error) {
341
+ if (error && error.code === 'SQLITE_UNAVAILABLE') throw error
342
+ throw unreadable(error)
343
+ }
344
+ if (!db) return { present: false, fresh: false }
345
+ try {
346
+ let tables
347
+ try { tables = tablesOf(db) } catch (error) { throw unreadable(error) }
348
+ if (!tables.has('records') || !tables.has('events')) {
349
+ throw coded(DB_FILE + ' 缺表(' + ['records', 'events'].filter((t) => !tables.has(t)).join('、') + '):结构不全的库不能拿来擦,先移走它重新迁移。', 'STORAGE_INCOMPLETE')
350
+ }
351
+ // sources 是"库和 JSONL 对不对得上"的唯一依据;没有它就没法判断过期,宁可拒绝
352
+ if (!tables.has('sources')) {
353
+ throw coded(DB_FILE + ' 缺 sources 表(阶段 1 早期建的库):没法判断这个库是不是过期,先移走它重新迁移。', 'STORAGE_INCOMPLETE')
354
+ }
355
+ let fresh = true
356
+ try { checkFresh(db, dir, true) } catch (error) {
357
+ if (error && error.code === 'STORAGE_STALE') fresh = false
358
+ else throw unreadable(error)
359
+ }
360
+ return { present: true, fresh }
361
+ } finally {
362
+ try { db.close() } catch { }
363
+ }
364
+ }
365
+
366
+ // 过期库擦完之后必须继续过期:把 sources 全都写成 -1 这个不可能等于真实字节数的哨兵。
367
+ // 只靠"不刷新"不够——JSONL 删小之后可能恰好缩回迁移时记的字节数,checkFresh 就会误判成"对得上"。
368
+ const STALE_SIZE = -1
369
+ function invalidateSources(db) {
370
+ const st = db.prepare('INSERT OR REPLACE INTO sources (file, size, migrated_at) VALUES (?, ?, ?)')
371
+ const at = new Date().toISOString()
372
+ for (const name of SOURCE_FILES) st.run(name, STALE_SIZE, at)
373
+ }
374
+
375
+ /**
376
+ * 从 SQLite 副本里删掉这些 id 的经历与关联事件(seal 保留,章节不指向经历所以不动)。
377
+ * 删除与 sources 更新在**同一个事务**里:要么都成,要么都不成(不会出现"记录删了、source 还挂着旧尺寸")。
378
+ * @param {string} dir
379
+ * @param {string[]} ids 要删的经历 id
380
+ * @param {{ refreshSources?: boolean }} opts refreshSources:擦除前库和 JSONL 对得上时才为 true
381
+ * (这时删完把 sources 的字节数刷成现在 JSONL 的大小;否则写 -1 哨兵,让库继续保持过期、读路径 fail closed)
382
+ */
383
+ export function eraseFromStore(dir, ids, { refreshSources = false } = {}) {
384
+ if (!statDatabase(dir)) return { present: false, records: 0, events: 0 }
385
+ const wanted = [...new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))]
386
+ const db = openDatabase(dir)
387
+ if (!db) return { present: false, records: 0, events: 0 }
388
+ try {
389
+ let records = 0
390
+ let events = 0
391
+ db.exec('BEGIN IMMEDIATE')
392
+ try {
393
+ const delRecord = db.prepare('DELETE FROM records WHERE id = ?')
394
+ for (const id of wanted) records += Number(delRecord.run(id).changes || 0)
395
+ // 按 exp_id 删;seal 事件留着(封存状态不是正文)
396
+ const delEvent = db.prepare("DELETE FROM events WHERE exp_id = ? AND kind <> 'seal'")
397
+ for (const id of wanted) events += Number(delEvent.run(id).changes || 0)
398
+ // 联想:exp_id 只存 from,to 那一头要自己看
399
+ const delSeq = db.prepare('DELETE FROM events WHERE seq = ?')
400
+ for (const row of db.prepare("SELECT seq, json FROM events WHERE kind = 'link'").all()) {
401
+ let link
402
+ try { link = JSON.parse(row.json) } catch { continue }
403
+ if (wanted.includes(String(link.from)) || wanted.includes(String(link.to))) {
404
+ events += Number(delSeq.run(row.seq).changes || 0)
405
+ }
406
+ }
407
+ if (refreshSources) writeSources(db, sourceSizes(dir))
408
+ else invalidateSources(db)
409
+ db.exec('COMMIT')
410
+ } catch (error) {
411
+ try { db.exec('ROLLBACK') } catch { }
412
+ throw error
413
+ }
414
+ return { present: true, records, events }
415
+ } finally {
416
+ try { db.close() } catch { }
417
+ }
418
+ }
@@ -0,0 +1,26 @@
1
+ /** 墓碑:一条经历被整条撤回后留下的那一行(不含正文,不可用于恢复) */
2
+ export interface Tombstone {
3
+ v: 1
4
+ id: string
5
+ /** 撤回时间(ISO 8601) */
6
+ at: string
7
+ /** 为什么撤回(人写的短句) */
8
+ reason: string
9
+ /** 谁要求的(self / leo / host……) */
10
+ actor: string
11
+ /** 删除前那一行的 sha256(原样字节,不含行尾换行) */
12
+ hash: string
13
+ /** 可选(阶段 4 复审后加):这一条经历在库里用过的所有 id(当前 id + 旧 id) */
14
+ ids?: string[]
15
+ }
16
+
17
+ export const eventsFile: (memDir: string) => string
18
+ export function isValid(r: unknown): r is Tombstone
19
+ /** 读全部墓碑(文件不存在 = 还没撤回过任何一条) */
20
+ export function readAll(memDir: string): { rows: Tombstone[]; bad: number }
21
+ export function append(memDir: string, row: Tombstone): Tombstone
22
+ export function byId(memDir: string, id: string): Tombstone | null
23
+ /** 已撤回的全部 id */
24
+ export function ids(memDir: string): Set<string>
25
+ export function badLines(memDir: string): number
26
+ export const internals: { FILE: string }
@@ -0,0 +1,72 @@
1
+ // 墓碑(阶段 4):一条经历被**整条撤回**之后,只留这一行。
2
+ //
3
+ // 一行一个 { v: 1, id, at, reason, actor, hash, ids? }:
4
+ // · id 被撤回那条经历的 id(不透明,永不复用;墓碑里留着它,才能核"这条存在过、被撤回了")
5
+ // · at 撤回时间(ISO 8601)
6
+ // · reason 为什么撤(人写的,短句;这是唯一由人提供的字段)
7
+ // · actor 谁要求的(self / leo / host……,由宿主决定)
8
+ // · hash 删除前那一行的 sha256(那一行原样字节,不含行尾换行;CRLF 的 \r 也不算)
9
+ // · ids 可选(阶段 4 复审后加):这一条经历在库里用过的所有 id(当前 id + 0.10 之前的旧 id)。
10
+ // 按旧 id 撤回时墓碑的 id 是旧 id,封存事件却挂在当前 id 上;体检靠这个字段把两边的账对上。
11
+ // 只加不减:老墓碑没有这个字段照样读。
12
+ //
13
+ // 墓碑**不含正文**,也**不能用来恢复**:它只说"有过这一条、什么时候、为什么没的"。
14
+ // 只追加、不提供删除/清空的 API(库内 API 删不掉审计与墓碑;整目录导入是另一件事,
15
+ // archive.importArchive 会按导入包整体替换目录里的文件,见 docs/erase-audit-zh.md)。
16
+ //
17
+ // 为什么把墓碑单独放一个文件:撤回是破坏性操作,删除本身不可逆,唯一能事后核对的
18
+ // 就是这一行。它必须比记录文件更难被顺手清掉,也必须一眼看得出只有 id 和哈希。
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+ import { createLog } from './event-log.js'
22
+
23
+ const FILE = 'tombstones.jsonl'
24
+ const HASH = /^[0-9a-f]{64}$/
25
+
26
+ export const eventsFile = (memDir) => path.join(memDir, FILE)
27
+
28
+ // 一行算不算合格的墓碑。文件和将来的其它容器用同一条判据
29
+ export function isValid(r) {
30
+ return Boolean(
31
+ r &&
32
+ r.v === 1 &&
33
+ typeof r.id === 'string' && r.id.trim() &&
34
+ typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) &&
35
+ typeof r.reason === 'string' &&
36
+ typeof r.actor === 'string' && r.actor.trim() &&
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())))
39
+ )
40
+ }
41
+
42
+ const log = createLog(FILE, { valid: isValid })
43
+
44
+ // { rows, bad };文件不存在 = 还没有任何撤回(不是坏了);读不出来抛(不当成空)
45
+ export const readAll = log.readAll
46
+
47
+ // 追加一条墓碑:先校验,写不进去就抛(不许写半条)
48
+ export function append(memDir, row) {
49
+ if (!isValid(row)) throw new Error('墓碑不合格(需要 v:1 / id / at / reason / actor / 64 位十六进制 hash),拒绝写入。(tombstone is not valid)')
50
+ return log.decide(memDir, () => ({ ...row })).row
51
+ }
52
+
53
+ // 某个 id 的墓碑(id 或 ids 里任一个对上);没有返回 null
54
+ export function byId(memDir, id) {
55
+ const key = String(id || '')
56
+ return readAll(memDir).rows.find((r) => r.id === key || (Array.isArray(r.ids) && r.ids.includes(key))) || null
57
+ }
58
+
59
+ // 所有已撤回的 id(体检用来判断封存事件是不是指向一条"撤回过的"经历;id 与 ids 都算)
60
+ export function ids(memDir) {
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
67
+ }
68
+
69
+ // 坏行数(给 doctor / 诊断用):只给数字
70
+ export const badLines = (memDir) => readAll(memDir).bad
71
+
72
+ export const internals = { FILE }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.25.0",
3
+ "version": "0.26.1",
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",
@@ -141,6 +141,22 @@
141
141
  "types": "./lib/injection.d.ts",
142
142
  "default": "./lib/injection.js"
143
143
  },
144
+ "./erase": {
145
+ "types": "./lib/erase.d.ts",
146
+ "default": "./lib/erase.js"
147
+ },
148
+ "./audit": {
149
+ "types": "./lib/audit.d.ts",
150
+ "default": "./lib/audit.js"
151
+ },
152
+ "./tombstones": {
153
+ "types": "./lib/tombstones.d.ts",
154
+ "default": "./lib/tombstones.js"
155
+ },
156
+ "./export-memory": {
157
+ "types": "./lib/export-memory.d.ts",
158
+ "default": "./lib/export-memory.js"
159
+ },
144
160
  "./storage/backend": "./lib/storage/backend.js",
145
161
  "./storage/file-backend": "./lib/storage/file-backend.js",
146
162
  "./storage/sqlite-backend": "./lib/storage/sqlite-backend.js"