whale-memory-core 0.25.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.
- package/index.d.ts +5 -0
- package/index.js +5 -0
- package/lib/audit.d.ts +39 -0
- package/lib/audit.js +162 -0
- package/lib/erase.d.ts +38 -0
- package/lib/erase.js +224 -0
- package/lib/export-memory.d.ts +18 -0
- package/lib/export-memory.js +69 -0
- package/lib/seal-events.js +1 -1
- package/lib/self-experience.d.ts +8 -1
- package/lib/self-experience.js +2 -1
- package/lib/sqlite-store.js +85 -0
- package/lib/tombstones.d.ts +24 -0
- package/lib/tombstones.js +62 -0
- package/package.json +17 -1
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,39 @@
|
|
|
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
|
+
export function eventsFile(memDir: string): string
|
|
16
|
+
export function isValid(r: unknown): r is AuditRow
|
|
17
|
+
/** 查询的 sha256:审计只留这个指纹,不留原文 */
|
|
18
|
+
export function queryHash(query: unknown): string
|
|
19
|
+
export function record(memDir: string, row: { at?: string; actor: string; action: string; ids?: string[]; note?: string }): AuditRow
|
|
20
|
+
export function read(dir: string, opts?: { since?: string | Date | null; until?: string | Date | null; action?: string; actor?: string }): AuditRow[]
|
|
21
|
+
/** 坏行数(只数,不把整份读进内存) */
|
|
22
|
+
export function badLines(dir: string): number
|
|
23
|
+
/** 读一条并留 read 审计(找不到也留;返回 null) */
|
|
24
|
+
export function readRecord(dir: string, id: string, opts?: { actor: string; note?: string; backend?: StorageBackendName; asOf?: AsOf }): Experience | null
|
|
25
|
+
/** 召回一次并留 recall 审计(只留查询哈希 + 命中 id) */
|
|
26
|
+
export function recall(dir: string, query: string, opts?: {
|
|
27
|
+
actor: string
|
|
28
|
+
note?: string
|
|
29
|
+
limit?: number
|
|
30
|
+
backend?: StorageBackendName
|
|
31
|
+
includeSealed?: boolean
|
|
32
|
+
ranker?: 'literal' | 'hybrid' | null
|
|
33
|
+
gate?: 'cover' | 'legacy'
|
|
34
|
+
mode?: 'strict' | 'loose'
|
|
35
|
+
asOf?: AsOf
|
|
36
|
+
}): Experience[]
|
|
37
|
+
export function noteRead(dir: string, opts: { actor: string; ids?: string[]; note?: string }): AuditRow
|
|
38
|
+
export function noteRecall(dir: string, opts: { actor: string; ids?: string[]; query?: string; note?: string }): AuditRow
|
|
39
|
+
export const internals: { FILE: string }
|
package/lib/audit.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
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
|
+
|
|
20
|
+
// 动作:至少这三类。别的名字也收(新增动作算兼容),但必须是非空字符串
|
|
21
|
+
export const ACTIONS = Object.freeze(['read', 'recall', 'erase'])
|
|
22
|
+
|
|
23
|
+
export const eventsFile = (memDir) => path.join(memDir, FILE)
|
|
24
|
+
|
|
25
|
+
export function isValid(r) {
|
|
26
|
+
return Boolean(
|
|
27
|
+
r &&
|
|
28
|
+
typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) &&
|
|
29
|
+
typeof r.actor === 'string' && r.actor.trim() &&
|
|
30
|
+
typeof r.action === 'string' && r.action.trim() &&
|
|
31
|
+
Array.isArray(r.ids) && r.ids.every((id) => typeof id === 'string') &&
|
|
32
|
+
typeof r.note === 'string'
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 查询哈希:只留指纹,不留原文(查询里经常带着她写的原话)
|
|
37
|
+
export const queryHash = (query) => crypto.createHash('sha256').update(String(query ?? ''), 'utf8').digest('hex')
|
|
38
|
+
|
|
39
|
+
// 追加一条:先校验再写;锁内只 append,不重读整个文件(审计会越来越长)
|
|
40
|
+
export function record(memDir, { at = new Date().toISOString(), actor, action, ids = [], note = '' } = {}) {
|
|
41
|
+
const row = {
|
|
42
|
+
at: String(at),
|
|
43
|
+
actor: String(actor ?? '').trim(),
|
|
44
|
+
action: String(action ?? '').trim(),
|
|
45
|
+
ids: (Array.isArray(ids) ? ids : []).map(String),
|
|
46
|
+
note: String(note ?? '')
|
|
47
|
+
}
|
|
48
|
+
if (!isValid(row)) throw new Error('审计行不合格(需要 at / actor / action / ids / note),拒绝写入。(audit row is not valid)')
|
|
49
|
+
fs.mkdirSync(memDir, { recursive: true })
|
|
50
|
+
return withFileLock(eventsFile(memDir) + '.lock', () => {
|
|
51
|
+
const file = eventsFile(memDir)
|
|
52
|
+
let prefix = ''
|
|
53
|
+
try {
|
|
54
|
+
const st = fs.statSync(file)
|
|
55
|
+
if (st.size) {
|
|
56
|
+
const fd = fs.openSync(file, 'r')
|
|
57
|
+
const buf = Buffer.alloc(1)
|
|
58
|
+
fs.readSync(fd, buf, 0, 1, st.size - 1)
|
|
59
|
+
fs.closeSync(fd)
|
|
60
|
+
if (buf[0] !== 10) prefix = '\n'
|
|
61
|
+
}
|
|
62
|
+
} catch { }
|
|
63
|
+
fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
|
|
64
|
+
return row
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 读一次(宿主在"她要看这一条"的边界调它):返回记录(找不到返回 null),并留一条 read 审计
|
|
69
|
+
export function readRecord(dir, id, { actor, note = '', backend = 'file', asOf = null } = {}) {
|
|
70
|
+
const row = currentView(dir, String(id), { asOf, backend })
|
|
71
|
+
record(dir, { actor, action: 'read', ids: [String(id)], note })
|
|
72
|
+
return row
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 召回一次并留一条 recall 审计:只留查询哈希 + 命中 id,不留查询原文
|
|
76
|
+
export function recall(dir, query, { actor, note = '', ...opts } = {}) {
|
|
77
|
+
const hits = recallInner(dir, query, opts)
|
|
78
|
+
record(dir, { actor, action: 'recall', ids: hits.map((r) => r.id), note: note || 'qsha256:' + queryHash(query) })
|
|
79
|
+
return hits
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 坏行数(给 doctor / 诊断用):只数,不返回任何一行——审计可能很长,体检不该把整份读进内存
|
|
83
|
+
export function badLines(dir) {
|
|
84
|
+
let fd
|
|
85
|
+
try {
|
|
86
|
+
fd = fs.openSync(eventsFile(dir), 'r')
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error && error.code === 'ENOENT') return 0
|
|
89
|
+
const wrapped = new Error('审计文件读不出来(' + FILE + '):' + String(error && error.message ? error.message : error))
|
|
90
|
+
wrapped.code = 'AUDIT_UNREADABLE'
|
|
91
|
+
wrapped.cause = error
|
|
92
|
+
throw wrapped
|
|
93
|
+
}
|
|
94
|
+
let bad = 0
|
|
95
|
+
try {
|
|
96
|
+
for (const line of readLines(fd)) {
|
|
97
|
+
if (!line.text.trim()) continue
|
|
98
|
+
let row
|
|
99
|
+
try { row = JSON.parse(line.text) } catch { bad += 1; continue }
|
|
100
|
+
if (!isValid(row)) bad += 1
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
fs.closeSync(fd)
|
|
104
|
+
}
|
|
105
|
+
return bad
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 只读查询:按动作 / 按人 / 按时间(ISO 或 Date,左闭右开),按追加顺序返回
|
|
109
|
+
export function read(dir, { since = null, until = null, action = '', actor = '' } = {}) {
|
|
110
|
+
const from = since === null || since === undefined || since === '' ? null : ms(since, 'since')
|
|
111
|
+
const to = until === null || until === undefined || until === '' ? null : ms(until, 'until')
|
|
112
|
+
const wantAction = String(action || '')
|
|
113
|
+
const wantActor = String(actor || '')
|
|
114
|
+
const rows = []
|
|
115
|
+
let bad = 0
|
|
116
|
+
let fd
|
|
117
|
+
try {
|
|
118
|
+
fd = fs.openSync(eventsFile(dir), 'r')
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error && error.code === 'ENOENT') return []
|
|
121
|
+
const wrapped = new Error('审计文件读不出来(' + FILE + '):' + String(error && error.message ? error.message : error))
|
|
122
|
+
wrapped.code = 'AUDIT_UNREADABLE'
|
|
123
|
+
wrapped.cause = error
|
|
124
|
+
throw wrapped
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
for (const line of readLines(fd)) {
|
|
128
|
+
if (!line.text.trim()) continue
|
|
129
|
+
let row
|
|
130
|
+
try { row = JSON.parse(line.text) } catch { bad += 1; continue }
|
|
131
|
+
if (!isValid(row)) { bad += 1; continue }
|
|
132
|
+
const t = Date.parse(row.at)
|
|
133
|
+
if (from !== null && t < from) continue
|
|
134
|
+
if (to !== null && t >= to) continue
|
|
135
|
+
if (wantAction && row.action !== wantAction) continue
|
|
136
|
+
if (wantActor && row.actor !== wantActor) continue
|
|
137
|
+
rows.push(row)
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
fs.closeSync(fd)
|
|
141
|
+
}
|
|
142
|
+
// 坏行不静默:审计读不完整时宁可报错,也不给一份"看起来没问题"的审计
|
|
143
|
+
if (bad > 0) {
|
|
144
|
+
const error = new Error('审计文件有 ' + bad + ' 行无法解析或不合格:这份审计不完整,不能当真。(' + bad + ' unreadable audit line(s))')
|
|
145
|
+
error.code = 'AUDIT_CORRUPT'
|
|
146
|
+
error.bad = bad
|
|
147
|
+
throw error
|
|
148
|
+
}
|
|
149
|
+
return rows
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function ms(v, name) {
|
|
153
|
+
const t = v instanceof Date ? v.getTime() : Date.parse(String(v))
|
|
154
|
+
if (!Number.isFinite(t)) throw new Error(name + ' 不是合法时间(用 ISO 时间或 Date)。(invalid audit time filter)')
|
|
155
|
+
return t
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// 宿主边界用的顺手别名(名字直白一点,别让调用方去记 action 字符串)
|
|
159
|
+
export const noteRead = (dir, { actor, ids, note = '' } = {}) => record(dir, { actor, action: 'read', ids, note })
|
|
160
|
+
export const noteRecall = (dir, { actor, ids, query = '', note = '' } = {}) => record(dir, { actor, action: 'recall', ids, note: note || 'qsha256:' + queryHash(query) })
|
|
161
|
+
|
|
162
|
+
export const internals = { FILE }
|
package/lib/erase.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
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
|
+
actor?: string
|
|
26
|
+
reason?: string
|
|
27
|
+
removed: EraseRemoved
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 整条撤回:记录 + later / recall / unfinished / link 事件物理删除,seal 事件保留,
|
|
32
|
+
* 成功后在 tombstones.jsonl 留一块墓碑(id / 时间 / 原因 / 哈希,不含正文)。
|
|
33
|
+
*
|
|
34
|
+
* 幂等;坏行 / 读不出来 / SQLite 副本删不了都整次拒绝(不许只删一半)。
|
|
35
|
+
* 只由宿主在"她本人或 Leo 明确要求"时调用;库不自动擦除。
|
|
36
|
+
*/
|
|
37
|
+
export function eraseExperience(dir: string, opts: { id: string; reason: string; actor: string; now?: Date | string }): EraseResult
|
|
38
|
+
export const internals: { RECORDS: string; EVENT_FILES: string[] }
|
package/lib/erase.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// 整条撤回(阶段 4):把一条经历连同挂在它身上的事件从库里物理删掉,只留一块墓碑。
|
|
2
|
+
//
|
|
3
|
+
// 为什么允许删除、但不允许改:契约里"记录不可变"防的是**篡改历史**(把当时写的话换掉)。
|
|
4
|
+
// 整条撤回是另一件事:她(或 Leo)明确要求"这件事不要再留在库里",那就整条拿掉;
|
|
5
|
+
// 拿掉之后留一行墓碑(id / 时间 / 原因 / 哈希),让"这条存在过、被撤回了"仍然可核。
|
|
6
|
+
//
|
|
7
|
+
// 守住的几条:
|
|
8
|
+
// · 不改别的记录:没被撤回的行**一个字节都不动**(含它引用了被撤回那条的 then.refs——
|
|
9
|
+
// 那是她当时写下的原文,不许替她删改;读的时候那段引用会显示"找不到了")。
|
|
10
|
+
// · 先查后删:经历文件或要重写的事件文件里有坏行,**整次拒绝**——坏行说不清是不是那条,
|
|
11
|
+
// 不能假装删干净了。擦除不做"尽量"。
|
|
12
|
+
// · 文件原子:读全量 → 过滤 → 写 .tmp → rename(见 file-lock.writeFileAtomic),
|
|
13
|
+
// 永远不会出现"写了一半"的经历文件。
|
|
14
|
+
// · 幂等:第二次调用返回 { ok: true, alreadyGone: true },不再写第二条墓碑。
|
|
15
|
+
// · 只由宿主在"她本人或 Leo 明确要求"时调用;库不自动擦除,也没有定时清理。
|
|
16
|
+
//
|
|
17
|
+
// 做不到(文档里也写清):备份与快照里的历史副本不追溯;SQLite 删除后文件页里可能残留旧字节
|
|
18
|
+
// (安全删除 / VACUUM 不在承诺里);多写者不承诺(同一目录并发写按契约本来就是单写者假设)。
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import crypto from 'node:crypto'
|
|
22
|
+
import { withFileLock, writeFileAtomic } from './file-lock.js'
|
|
23
|
+
import { readLines } from './jsonl-stream.js'
|
|
24
|
+
import * as tombstones from './tombstones.js'
|
|
25
|
+
import * as audit from './audit.js'
|
|
26
|
+
import { internals as expInternals } from './self-experience.js'
|
|
27
|
+
import { eraseReadiness, eraseFromStore } from './sqlite-store.js'
|
|
28
|
+
|
|
29
|
+
const RECORDS = 'self-experience.jsonl'
|
|
30
|
+
// 挂在这条经历上的事件文件:撤回了就一起删。
|
|
31
|
+
// seal-events 不删:封存是"别再主动提起"的状态记录,不是正文;删了反而让"曾经封存过"这段历史断掉。
|
|
32
|
+
// chapter-events 不删:章节按日子命名一段时间,不指向某一条经历(见 link/chapter 的事件格式)。
|
|
33
|
+
const EVENT_FILES = ['later-events.jsonl', 'recall-events.jsonl', 'unfinished-events.jsonl', 'link-events.jsonl']
|
|
34
|
+
const LIMIT_REASON = 500
|
|
35
|
+
|
|
36
|
+
const coded = (message, code, extra = {}) => Object.assign(new Error(message), { code }, extra)
|
|
37
|
+
|
|
38
|
+
function readLinesOf(dir, name) {
|
|
39
|
+
const file = path.join(dir, name)
|
|
40
|
+
let fd
|
|
41
|
+
try {
|
|
42
|
+
fd = fs.openSync(file, 'r')
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error && error.code === 'ENOENT') return { exists: false, lines: [], bad: 0 }
|
|
45
|
+
throw coded('要擦除的文件读不出来(' + name + '):' + String(error && error.message ? error.message : error), 'ERASE_UNREADABLE', { cause: error })
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const lines = []
|
|
49
|
+
let bad = 0
|
|
50
|
+
for (const line of readLines(fd)) {
|
|
51
|
+
if (!line.text.trim()) continue
|
|
52
|
+
let row
|
|
53
|
+
try { row = JSON.parse(line.text) } catch { row = undefined; bad += 1 }
|
|
54
|
+
lines.push({ text: line.text, row })
|
|
55
|
+
}
|
|
56
|
+
return { exists: true, lines, bad }
|
|
57
|
+
} finally {
|
|
58
|
+
fs.closeSync(fd)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 一行算不算"她的一条经历"(口径与 self-experience.normalize 一致;这里用它的实现,不另抄一份)
|
|
63
|
+
function recordOf(row) {
|
|
64
|
+
if (!row || typeof row !== 'object') return null
|
|
65
|
+
const normalized = expInternals.normalize(row)
|
|
66
|
+
return normalized && normalized.then && normalized.then.text ? normalized : null
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 事件行指向了哪些经历 id:联想是 from/to,其余三类是 id
|
|
70
|
+
function eventIdsOf(row) {
|
|
71
|
+
if (!row || typeof row !== 'object') return []
|
|
72
|
+
const out = []
|
|
73
|
+
for (const key of ['id', 'from', 'to']) if (row[key] !== undefined && row[key] !== null) out.push(String(row[key]))
|
|
74
|
+
return out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const hashOfLine = (text) => crypto.createHash('sha256').update(String(text).replace(/\r$/, ''), 'utf8').digest('hex')
|
|
78
|
+
|
|
79
|
+
// 把经历文件解析成一行一条,并按 identifyRaw 同一套规则认领旧 id。
|
|
80
|
+
// 返回 { infos, target, ambiguous }:target 是要删掉的**当前 id** 集合(含通过旧 id 认领到的)
|
|
81
|
+
function analyse(records, id) {
|
|
82
|
+
const key = String(id)
|
|
83
|
+
const infos = records.lines.map((line) => {
|
|
84
|
+
const row = recordOf(line.row)
|
|
85
|
+
return { line, row, rawFormerId: row && row.formerId ? String(row.formerId) : '' }
|
|
86
|
+
})
|
|
87
|
+
const owners = new Map()
|
|
88
|
+
const explicit = new Set()
|
|
89
|
+
for (const info of infos) {
|
|
90
|
+
if (!info.row) continue
|
|
91
|
+
if (!info.row.formerId) explicit.add(info.row.id)
|
|
92
|
+
else {
|
|
93
|
+
const list = owners.get(info.row.formerId)
|
|
94
|
+
if (list) list.push(info.row.id)
|
|
95
|
+
else owners.set(info.row.formerId, [info.row.id])
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
// 同一个旧 id 被几条经历共用:不猜,报错让她用当前 id
|
|
99
|
+
if ((owners.get(key) || []).length > 1 && !explicit.has(key)) {
|
|
100
|
+
throw coded('这个旧 id 有好几条经历共用(' + key + '):先用 read 看一下当前 id 再撤回。(legacy id is ambiguous)', 'ERASE_AMBIGUOUS_ID')
|
|
101
|
+
}
|
|
102
|
+
for (const info of infos) {
|
|
103
|
+
if (info.row && info.row.formerId && (owners.get(info.row.formerId).length !== 1 || explicit.has(info.row.formerId))) info.row.formerId = ''
|
|
104
|
+
}
|
|
105
|
+
const target = new Set([key])
|
|
106
|
+
for (const info of infos) {
|
|
107
|
+
if (!info.row) continue
|
|
108
|
+
if (info.row.formerId === key) target.add(String(info.row.id))
|
|
109
|
+
}
|
|
110
|
+
return { infos, target }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function rewriteIfChanged(dir, name, lines, keep) {
|
|
114
|
+
const kept = []
|
|
115
|
+
let removed = 0
|
|
116
|
+
for (const line of lines) {
|
|
117
|
+
if (keep(line)) kept.push(line.text)
|
|
118
|
+
else removed += 1
|
|
119
|
+
}
|
|
120
|
+
if (!removed) return 0
|
|
121
|
+
writeFileAtomic(path.join(dir, name), kept.length ? kept.join('\n') + '\n' : '')
|
|
122
|
+
return removed
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 整条撤回一条经历。
|
|
127
|
+
*
|
|
128
|
+
* @param {string} dir 记忆目录
|
|
129
|
+
* @param {{ id: string, reason: string, actor: string, now?: Date|string }} opts
|
|
130
|
+
* id:要撤回的经历 id(也收 0.10 之前那个唯一对应的旧 id)
|
|
131
|
+
* reason:为什么撤回(人写的短句,写进墓碑;不写正文)
|
|
132
|
+
* actor:谁要求的(self / leo / host……,写进墓碑与审计)
|
|
133
|
+
* @returns {{ ok: true, id: string, alreadyGone: boolean, at: string, hash?: string, removed: object }}
|
|
134
|
+
*/
|
|
135
|
+
export function eraseExperience(dir, { id, reason = '', actor = '', now = new Date() } = {}) {
|
|
136
|
+
const key = String(id || '').trim()
|
|
137
|
+
if (!key) throw new Error('需要 id:说清要撤回哪一条经历。(missing id)')
|
|
138
|
+
if (!String(reason || '').trim()) throw new Error('需要 reason:撤回是破坏性操作,必须说清为什么(会写进墓碑)。(missing reason)')
|
|
139
|
+
if (String(reason).length > LIMIT_REASON) throw new Error('reason 太长(' + String(reason).length + '/' + LIMIT_REASON + ' 字)。(reason is too long)')
|
|
140
|
+
if (!String(actor || '').trim()) throw new Error('需要 actor:说清是谁要求的(self / leo / host……)。(missing actor)')
|
|
141
|
+
const actorText = String(actor).trim()
|
|
142
|
+
const at = (now instanceof Date ? now : new Date(now)).toISOString()
|
|
143
|
+
|
|
144
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
145
|
+
// 同一目录的撤回串行化;它跟事件文件各自的锁不是同一把,但擦除本身是单写者操作
|
|
146
|
+
return withFileLock(path.join(dir, 'erase.lock'), () => {
|
|
147
|
+
// 1) 账本先看一遍:墓碑文件坏了就不知道撤回没撤回,宁可不猜
|
|
148
|
+
const marks = tombstones.readAll(dir)
|
|
149
|
+
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() }
|
|
152
|
+
|
|
153
|
+
// 2) 读全量 + 预检:坏行 / 读不出来都整次拒绝,一个字节都不改
|
|
154
|
+
const records = readLinesOf(dir, RECORDS)
|
|
155
|
+
if (records.bad > 0) throw coded('经历文件有 ' + records.bad + ' 行无法解析:撤回没法保证删干净,先修好或先备份。(records are corrupt)', 'ERASE_RECORDS_CORRUPT', { bad: records.bad })
|
|
156
|
+
const events = EVENT_FILES.map((name) => ({ name, ...readLinesOf(dir, name) }))
|
|
157
|
+
const badEvent = events.find((e) => e.bad > 0)
|
|
158
|
+
if (badEvent) throw coded('事件文件 ' + badEvent.name + ' 有 ' + badEvent.bad + ' 行无法解析:撤回没法保证删干净,先修好再撤回。(events are corrupt)', 'ERASE_EVENTS_CORRUPT', { file: badEvent.name, bad: badEvent.bad })
|
|
159
|
+
|
|
160
|
+
// 3) 目录里有 SQLite 副本:先确认它打不开/不全(那就整次拒绝,不许只删一半),
|
|
161
|
+
// 顺便记下它跟 JSONL 对不对得上——决定删完要不要刷新 sources
|
|
162
|
+
const store = eraseReadiness(dir)
|
|
163
|
+
|
|
164
|
+
// 4) 认领要删的 id(含旧 id),并取出删除前那一行的哈希
|
|
165
|
+
const analysed = analyse(records, key)
|
|
166
|
+
const doomed = analysed.infos.filter((info) => info.row && analysed.target.has(String(info.row.id)))
|
|
167
|
+
const removed = emptyRemoved()
|
|
168
|
+
let hash = ''
|
|
169
|
+
if (doomed.length) {
|
|
170
|
+
hash = hashOfLine(doomed[0].line.text)
|
|
171
|
+
if (doomed.length > 1) removed.duplicates = doomed.length - 1
|
|
172
|
+
}
|
|
173
|
+
|
|
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
|
+
})
|
|
179
|
+
|
|
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
|
+
}
|
|
185
|
+
|
|
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)
|
|
190
|
+
|
|
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 }
|
|
195
|
+
}
|
|
196
|
+
// 记录已经不在了、事件/库里的残留清掉了:不写墓碑(我们从没看见过那条记录,写不出它的哈希)
|
|
197
|
+
return { ok: true, id: key, alreadyGone: true, at: '', removed }
|
|
198
|
+
}
|
|
199
|
+
|
|
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
|
+
}
|
|
206
|
+
|
|
207
|
+
// 10) 审计:只记 id 与动作,不记正文(reason 里有人的话,不往审计里抄)
|
|
208
|
+
try {
|
|
209
|
+
audit.record(dir, { actor: actorText, action: 'erase', ids: [key], note: 'tombstone' })
|
|
210
|
+
} catch (error) {
|
|
211
|
+
throw coded('记录与墓碑都在,但审计追加失败:' + String(error && error.message ? error.message : error) + '。(audit write failed after erase)', 'ERASE_AUDIT_FAILED', { cause: error, erased: true })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { ok: true, id: key, alreadyGone: false, at, hash, actor: actorText, reason: String(reason).trim(), removed }
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function emptyRemoved() {
|
|
219
|
+
return { records: 0, later: 0, recall: 0, unfinished: 0, link: 0, sqlite: false, sqliteRecords: 0, sqliteEvents: 0 }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const shortName = (file) => file.replace(/-events\.jsonl$/, '')
|
|
223
|
+
|
|
224
|
+
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 }
|
package/lib/seal-events.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 她选择的遗忘:封存 / 解封。一行一个 { id, at, day, action, note? },只追加
|
|
2
2
|
// 封存不是删除:原文、后记、选择都还在;只是不再被主动想起(召回、醒来、别的回想里的摘要都避开它)
|
|
3
|
-
//
|
|
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'
|
package/lib/self-experience.d.ts
CHANGED
|
@@ -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: {
|
|
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
|
+
}
|
package/lib/self-experience.js
CHANGED
|
@@ -1153,7 +1153,8 @@ export function renderTwoPart(entry, { now = new Date(), lang = 'zh' } = {}) {
|
|
|
1153
1153
|
return lines.join('\n')
|
|
1154
1154
|
}
|
|
1155
1155
|
|
|
1156
|
-
|
|
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),自动递回不能默认用它;
|
package/lib/sqlite-store.js
CHANGED
|
@@ -301,3 +301,88 @@ 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
|
+
/** 擦除前的体检:库不存在 = { present:false };存在但打不开/不全 = 抛;过期 = fresh:false。 */
|
|
319
|
+
export function eraseReadiness(dir) {
|
|
320
|
+
const file = path.join(dir, DB_FILE)
|
|
321
|
+
let exists = false
|
|
322
|
+
try { exists = fs.existsSync(file) } catch { exists = false }
|
|
323
|
+
// 没有库就不碰 node:sqlite:Node 20 上擦一个只用 file 后端的目录必须照常能跑
|
|
324
|
+
if (!exists) return { present: false, fresh: false }
|
|
325
|
+
const db = openDatabase(dir)
|
|
326
|
+
if (!db) return { present: false, fresh: false }
|
|
327
|
+
try {
|
|
328
|
+
let tables
|
|
329
|
+
try { tables = tablesOf(db) } catch (error) { throw unreadable(error) }
|
|
330
|
+
if (!tables.has('records') || !tables.has('events')) {
|
|
331
|
+
throw coded(DB_FILE + ' 缺表(' + ['records', 'events'].filter((t) => !tables.has(t)).join('、') + '):结构不全的库不能拿来擦,先移走它重新迁移。', 'STORAGE_INCOMPLETE')
|
|
332
|
+
}
|
|
333
|
+
let fresh = true
|
|
334
|
+
try { checkFresh(db, dir, tables.has('sources')) } catch (error) {
|
|
335
|
+
if (error && error.code === 'STORAGE_STALE') fresh = false
|
|
336
|
+
else throw unreadable(error)
|
|
337
|
+
}
|
|
338
|
+
return { present: true, fresh }
|
|
339
|
+
} finally {
|
|
340
|
+
try { db.close() } catch { }
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* 从 SQLite 副本里删掉这些 id 的经历与关联事件(seal 保留,章节不指向经历所以不动)。
|
|
346
|
+
* @param {string} dir
|
|
347
|
+
* @param {string[]} ids 要删的经历 id
|
|
348
|
+
* @param {{ refreshSources?: boolean }} opts refreshSources:删完把 sources 的字节数刷成现在 JSONL 的大小
|
|
349
|
+
* (只有擦除前库和 JSONL 对得上时才该这么做;否则会让一个缺记录的库看起来是新的)
|
|
350
|
+
*/
|
|
351
|
+
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 }
|
|
356
|
+
const wanted = [...new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))]
|
|
357
|
+
const db = openDatabase(dir)
|
|
358
|
+
if (!db) return { present: false, records: 0, events: 0 }
|
|
359
|
+
try {
|
|
360
|
+
let records = 0
|
|
361
|
+
let events = 0
|
|
362
|
+
db.exec('BEGIN IMMEDIATE')
|
|
363
|
+
try {
|
|
364
|
+
const delRecord = db.prepare('DELETE FROM records WHERE id = ?')
|
|
365
|
+
for (const id of wanted) records += Number(delRecord.run(id).changes || 0)
|
|
366
|
+
// 按 exp_id 删;seal 事件留着(封存状态不是正文)
|
|
367
|
+
const delEvent = db.prepare("DELETE FROM events WHERE exp_id = ? AND kind <> 'seal'")
|
|
368
|
+
for (const id of wanted) events += Number(delEvent.run(id).changes || 0)
|
|
369
|
+
// 联想:exp_id 只存 from,to 那一头要自己看
|
|
370
|
+
const delSeq = db.prepare('DELETE FROM events WHERE seq = ?')
|
|
371
|
+
for (const row of db.prepare("SELECT seq, json FROM events WHERE kind = 'link'").all()) {
|
|
372
|
+
let link
|
|
373
|
+
try { link = JSON.parse(row.json) } catch { continue }
|
|
374
|
+
if (wanted.includes(String(link.from)) || wanted.includes(String(link.to))) {
|
|
375
|
+
events += Number(delSeq.run(row.seq).changes || 0)
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
db.exec('COMMIT')
|
|
379
|
+
} catch (error) {
|
|
380
|
+
try { db.exec('ROLLBACK') } catch { }
|
|
381
|
+
throw error
|
|
382
|
+
}
|
|
383
|
+
if (refreshSources) writeSources(db, sourceSizes(dir))
|
|
384
|
+
return { present: true, records, events }
|
|
385
|
+
} finally {
|
|
386
|
+
try { db.close() } catch { }
|
|
387
|
+
}
|
|
388
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
}
|
|
14
|
+
|
|
15
|
+
export const eventsFile: (memDir: string) => string
|
|
16
|
+
export function isValid(r: unknown): r is Tombstone
|
|
17
|
+
/** 读全部墓碑(文件不存在 = 还没撤回过任何一条) */
|
|
18
|
+
export function readAll(memDir: string): { rows: Tombstone[]; bad: number }
|
|
19
|
+
export function append(memDir: string, row: Tombstone): Tombstone
|
|
20
|
+
export function byId(memDir: string, id: string): Tombstone | null
|
|
21
|
+
/** 已撤回的全部 id */
|
|
22
|
+
export function ids(memDir: string): Set<string>
|
|
23
|
+
export function badLines(memDir: string): number
|
|
24
|
+
export const internals: { FILE: string }
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// 墓碑(阶段 4):一条经历被**整条撤回**之后,只留这一行。
|
|
2
|
+
//
|
|
3
|
+
// 一行一个 { v: 1, id, at, reason, actor, hash }:
|
|
4
|
+
// · id 被撤回那条经历的 id(不透明,永不复用;墓碑里留着它,才能核"这条存在过、被撤回了")
|
|
5
|
+
// · at 撤回时间(ISO 8601)
|
|
6
|
+
// · reason 为什么撤(人写的,短句;这是唯一由人提供的字段)
|
|
7
|
+
// · actor 谁要求的(self / leo / host……,由宿主决定)
|
|
8
|
+
// · hash 删除前那一行的 sha256(那一行原样字节,不含行尾换行;CRLF 的 \r 也不算)
|
|
9
|
+
//
|
|
10
|
+
// 墓碑**不含正文**,也**不能用来恢复**:它只说"有过这一条、什么时候、为什么没的"。
|
|
11
|
+
// 只追加、不提供删除/清空的 API(库内 API 删不掉审计与墓碑;要动只能人拿编辑器来)。
|
|
12
|
+
//
|
|
13
|
+
// 为什么把墓碑单独放一个文件:撤回是破坏性操作,删除本身不可逆,唯一能事后核对的
|
|
14
|
+
// 就是这一行。它必须比记录文件更难被顺手清掉,也必须一眼看得出只有 id 和哈希。
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import path from 'node:path'
|
|
17
|
+
import { createLog } from './event-log.js'
|
|
18
|
+
|
|
19
|
+
const FILE = 'tombstones.jsonl'
|
|
20
|
+
const HASH = /^[0-9a-f]{64}$/
|
|
21
|
+
|
|
22
|
+
export const eventsFile = (memDir) => path.join(memDir, FILE)
|
|
23
|
+
|
|
24
|
+
// 一行算不算合格的墓碑。文件和将来的其它容器用同一条判据
|
|
25
|
+
export function isValid(r) {
|
|
26
|
+
return Boolean(
|
|
27
|
+
r &&
|
|
28
|
+
r.v === 1 &&
|
|
29
|
+
typeof r.id === 'string' && r.id.trim() &&
|
|
30
|
+
typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) &&
|
|
31
|
+
typeof r.reason === 'string' &&
|
|
32
|
+
typeof r.actor === 'string' && r.actor.trim() &&
|
|
33
|
+
typeof r.hash === 'string' && HASH.test(r.hash)
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const log = createLog(FILE, { valid: isValid })
|
|
38
|
+
|
|
39
|
+
// { rows, bad };文件不存在 = 还没有任何撤回(不是坏了);读不出来抛(不当成空)
|
|
40
|
+
export const readAll = log.readAll
|
|
41
|
+
|
|
42
|
+
// 追加一条墓碑:先校验,写不进去就抛(不许写半条)
|
|
43
|
+
export function append(memDir, row) {
|
|
44
|
+
if (!isValid(row)) throw new Error('墓碑不合格(需要 v:1 / id / at / reason / actor / 64 位十六进制 hash),拒绝写入。(tombstone is not valid)')
|
|
45
|
+
return log.decide(memDir, () => ({ ...row })).row
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 某个 id 的墓碑;没有返回 null
|
|
49
|
+
export function byId(memDir, id) {
|
|
50
|
+
const key = String(id || '')
|
|
51
|
+
return readAll(memDir).rows.find((r) => r.id === key) || null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 所有已撤回的 id(体检用来判断封存事件是不是指向一条"撤回过的"经历)
|
|
55
|
+
export function ids(memDir) {
|
|
56
|
+
return new Set(readAll(memDir).rows.map((r) => r.id))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// 坏行数(给 doctor / 诊断用):只给数字
|
|
60
|
+
export const badLines = (memDir) => readAll(memDir).bad
|
|
61
|
+
|
|
62
|
+
export const internals = { FILE }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whale-memory-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.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",
|
|
@@ -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"
|