whale-memory-core 0.24.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/jsonl-stream.js +85 -0
- package/lib/metrics.d.ts +39 -0
- package/lib/metrics.js +116 -0
- package/lib/seal-events.js +1 -1
- package/lib/self-experience.d.ts +30 -1
- package/lib/self-experience.js +478 -100
- package/lib/sqlite-store.js +99 -0
- package/lib/storage/sqlite-backend.js +12 -6
- 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 }
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// 逐行读 JSONL:不把整个文件读成一个字符串。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有这个:旧写法是 readFileSync 整读 + split('\n'),十万条时同时占着
|
|
4
|
+
// 「文件字符串 + 切出来的行数组 + 解析后的对象」三份内存,峰值能到几百 MB。
|
|
5
|
+
// 这里按 64KB 块读、按字节找换行,每行单独解码、解析完就丢掉文本。
|
|
6
|
+
//
|
|
7
|
+
// 按字节找换行是安全的:0x0A 不可能出现在多字节 UTF-8 序列的内部(续字节都 ≥ 0x80),
|
|
8
|
+
// 所以「按 0x0A 切字节」和「先整体解码再按 '\n' 切字符串」得到的是同一组行。
|
|
9
|
+
// 唯一差别是文件末尾被截断在多字节字符中间时,最后一行解码成 U+FFFD——和 readFileSync 一样。
|
|
10
|
+
//
|
|
11
|
+
// 同步与异步两条读法共用 lineSplitter:切行口径只写一次。
|
|
12
|
+
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
|
|
15
|
+
export const READ_CHUNK = 64 * 1024
|
|
16
|
+
|
|
17
|
+
// 字节块 → 行。onLine(text, offset, bytes):
|
|
18
|
+
// text 这一行的原样文本(不含换行符;行尾的 \r 保留,和 split('\n') 一致)
|
|
19
|
+
// offset 这一行在文件里的起始字节位置
|
|
20
|
+
// bytes 这一行的字节长度(不含换行符)
|
|
21
|
+
// 注意:push 收到的 chunk 可能被复用,回调里不能把 chunk 存下来(存 text 没问题,它是新字符串)。
|
|
22
|
+
export function lineSplitter(onLine) {
|
|
23
|
+
let pending = Buffer.alloc(0)
|
|
24
|
+
let pendingAt = 0
|
|
25
|
+
return {
|
|
26
|
+
push(chunk, chunkAt) {
|
|
27
|
+
const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk
|
|
28
|
+
let start = 0
|
|
29
|
+
for (;;) {
|
|
30
|
+
const nl = buf.indexOf(10, start)
|
|
31
|
+
if (nl === -1) break
|
|
32
|
+
onLine(buf.toString('utf8', start, nl), pendingAt + start, nl - start)
|
|
33
|
+
start = nl + 1
|
|
34
|
+
}
|
|
35
|
+
// 剩下没换行的一段留到下一块;整块都以换行结尾时 pending 清空
|
|
36
|
+
pending = start >= buf.length ? Buffer.alloc(0) : Buffer.from(buf.subarray(start))
|
|
37
|
+
pendingAt += start
|
|
38
|
+
},
|
|
39
|
+
end() {
|
|
40
|
+
if (!pending.length) return
|
|
41
|
+
const text = pending.toString('utf8')
|
|
42
|
+
const at = pendingAt
|
|
43
|
+
const bytes = pending.length
|
|
44
|
+
pending = Buffer.alloc(0)
|
|
45
|
+
onLine(text, at, bytes)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 同步逐行:调用方自己 open / close(这样"文件不存在"在打开那一步就能报出来,
|
|
51
|
+
// 不会等第一次 next() 才冒出来)。一次只留 64KB 的读缓冲和一行文本。
|
|
52
|
+
export function* readLines(fd) {
|
|
53
|
+
const buf = Buffer.allocUnsafe(READ_CHUNK)
|
|
54
|
+
let lines = []
|
|
55
|
+
const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
|
|
56
|
+
let at = 0
|
|
57
|
+
for (;;) {
|
|
58
|
+
const n = fs.readSync(fd, buf, 0, READ_CHUNK, null)
|
|
59
|
+
if (!n) break
|
|
60
|
+
split.push(buf.subarray(0, n), at)
|
|
61
|
+
at += n
|
|
62
|
+
for (const line of lines) yield line
|
|
63
|
+
lines = []
|
|
64
|
+
}
|
|
65
|
+
split.end()
|
|
66
|
+
for (const line of lines) yield line
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 异步逐行:同上,块读走 fs/promises,不把事件循环卡住。
|
|
70
|
+
export async function* readLinesAsync(fh) {
|
|
71
|
+
const buf = Buffer.allocUnsafe(READ_CHUNK)
|
|
72
|
+
let lines = []
|
|
73
|
+
const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
|
|
74
|
+
let at = 0
|
|
75
|
+
for (;;) {
|
|
76
|
+
const { bytesRead } = await fh.read(buf, 0, READ_CHUNK, null)
|
|
77
|
+
if (!bytesRead) break
|
|
78
|
+
split.push(buf.subarray(0, bytesRead), at)
|
|
79
|
+
at += bytesRead
|
|
80
|
+
for (const line of lines) yield line
|
|
81
|
+
lines = []
|
|
82
|
+
}
|
|
83
|
+
split.end()
|
|
84
|
+
for (const line of lines) yield line
|
|
85
|
+
}
|