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/lib/sqlite-store.js
CHANGED
|
@@ -74,6 +74,20 @@ export function sqliteAvailable() {
|
|
|
74
74
|
// ---------------------------------------------------------------- 表结构
|
|
75
75
|
|
|
76
76
|
export function ensureSchema(db) {
|
|
77
|
+
// 建表必须一次成。DDL 逐条自动提交的话,第一次建库时进程被杀(或盘满)会留下"有 records、没 events"
|
|
78
|
+
// 的半截库,之后读路径会永远报缺表。SQLite 的 DDL 在事务里可以整组回滚,包一层就好。
|
|
79
|
+
db.exec('BEGIN IMMEDIATE')
|
|
80
|
+
try {
|
|
81
|
+
createTables(db)
|
|
82
|
+
db.exec('COMMIT')
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// 回滚本身也可能失败(连接已坏):不能盖掉真正的错误
|
|
85
|
+
try { db.exec('ROLLBACK') } catch { }
|
|
86
|
+
throw error
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function createTables(db) {
|
|
77
91
|
db.exec(`CREATE TABLE IF NOT EXISTS records (
|
|
78
92
|
id TEXT PRIMARY KEY,
|
|
79
93
|
day TEXT NOT NULL,
|
|
@@ -287,3 +301,88 @@ export function readEvents(db, kind) {
|
|
|
287
301
|
export function readRecords(db) {
|
|
288
302
|
return parseColumn(db.prepare('SELECT json FROM records ORDER BY rowid').all().map((r) => r.json))
|
|
289
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
|
+
}
|
|
@@ -18,6 +18,12 @@ import path from 'node:path'
|
|
|
18
18
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
19
19
|
import { DB_FILE, requireSqlite, openDatabase, insertRecord, insertEvent, recordExists, readEvents, readRecords, kindOf } from '../sqlite-store.js'
|
|
20
20
|
|
|
21
|
+
// 回滚本身失败时(盘满、连接已坏这类)不能把真正的错误盖掉:包一层,原错误优先。
|
|
22
|
+
// 这是 crash-drills 的复审发现:ROLLBACK 没包 try 时,SQLITE_FULL 之类的二次失败会顶掉原始错误。
|
|
23
|
+
function rollbackQuiet(db, sql = 'ROLLBACK') {
|
|
24
|
+
try { db.exec(sql) } catch { }
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export class SqliteBackend {
|
|
22
28
|
#als = new AsyncLocalStorage()
|
|
23
29
|
#tail = Promise.resolve()
|
|
@@ -73,8 +79,8 @@ export class SqliteBackend {
|
|
|
73
79
|
db.exec('RELEASE ' + sp)
|
|
74
80
|
return result
|
|
75
81
|
} catch (error) {
|
|
76
|
-
db
|
|
77
|
-
db
|
|
82
|
+
rollbackQuiet(db, 'ROLLBACK TO ' + sp)
|
|
83
|
+
rollbackQuiet(db, 'RELEASE ' + sp)
|
|
78
84
|
throw error
|
|
79
85
|
}
|
|
80
86
|
}
|
|
@@ -84,7 +90,7 @@ export class SqliteBackend {
|
|
|
84
90
|
db.exec('COMMIT')
|
|
85
91
|
return result
|
|
86
92
|
} catch (error) {
|
|
87
|
-
db
|
|
93
|
+
rollbackQuiet(db)
|
|
88
94
|
throw error
|
|
89
95
|
}
|
|
90
96
|
}
|
|
@@ -174,8 +180,8 @@ export class SqliteBackend {
|
|
|
174
180
|
db.exec('RELEASE ' + sp)
|
|
175
181
|
return result
|
|
176
182
|
} catch (error) {
|
|
177
|
-
db
|
|
178
|
-
db
|
|
183
|
+
rollbackQuiet(db, 'ROLLBACK TO ' + sp)
|
|
184
|
+
rollbackQuiet(db, 'RELEASE ' + sp)
|
|
179
185
|
throw error
|
|
180
186
|
}
|
|
181
187
|
}
|
|
@@ -187,7 +193,7 @@ export class SqliteBackend {
|
|
|
187
193
|
db.exec('COMMIT')
|
|
188
194
|
return result
|
|
189
195
|
} catch (error) {
|
|
190
|
-
db
|
|
196
|
+
rollbackQuiet(db)
|
|
191
197
|
throw error
|
|
192
198
|
}
|
|
193
199
|
})
|
|
@@ -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"
|