whale-memory-core 0.22.0 → 0.24.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 +1 -0
- package/index.js +1 -0
- package/lib/chapter-events.d.ts +4 -0
- package/lib/chapter-events.js +9 -2
- package/lib/hybrid-recall.d.ts +35 -0
- package/lib/hybrid-recall.js +205 -0
- package/lib/later-events.d.ts +5 -0
- package/lib/later-events.js +11 -2
- package/lib/link-events.d.ts +4 -0
- package/lib/link-events.js +9 -2
- package/lib/recall-events.d.ts +5 -0
- package/lib/recall-events.js +13 -3
- package/lib/seal-events.d.ts +4 -0
- package/lib/seal-events.js +11 -2
- package/lib/self-experience.d.ts +13 -3
- package/lib/self-experience.js +91 -15
- package/lib/sqlite-store.js +289 -0
- package/lib/storage/backend.js +39 -0
- package/lib/storage/file-backend.js +119 -0
- package/lib/storage/sqlite-backend.js +206 -0
- package/lib/unfinished-events.d.ts +4 -0
- package/lib/unfinished-events.js +11 -2
- package/package.json +9 -2
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// SQLite 后端(阶段 1):用 Node 内置的 node:sqlite,不引入依赖。
|
|
2
|
+
//
|
|
3
|
+
// 要求 Node >= 22.5(node:sqlite 自 22.5 起可用)。拿不到 node:sqlite 时直接报错,
|
|
4
|
+
// 由调用方显式退回 file 后端——不装依赖、不静默降级。
|
|
5
|
+
//
|
|
6
|
+
// 两张数据表:records(id 主键 + day 索引 + 整行 json)和 events(seq 自增 + kind/exp_id 索引 + 整行 json)。
|
|
7
|
+
// 记录与事件都是不可变的,所以没有 UPDATE;换引擎不改变契约里的任何一条。
|
|
8
|
+
// 表结构、读写的同步内核在 ../sqlite-store.js(loadAll 是同步 API,要和这里共用同一份)。
|
|
9
|
+
//
|
|
10
|
+
// 事务的规矩(一个后端对象只有一条连接):
|
|
11
|
+
// · 同一时刻只有一个事务。别的调用方(不在这个事务的调用链里)的读写一律排队,等它结束——
|
|
12
|
+
// 不会悄悄并进别人的事务、跟着别人一起回滚,也读不到别人还没提交的东西;
|
|
13
|
+
// · 在事务自己的调用链里(transaction(fn) 的 fn 以及它 await 的一切):写入直接进这个事务;
|
|
14
|
+
// appendWithEvents / appendEvent / 嵌套的 transaction() 各自包一层 SAVEPOINT,
|
|
15
|
+
// 失败只撤掉自己这一组,外层可以接住错误继续;
|
|
16
|
+
// · 同一个事务里别并发跑两个嵌套分组(Promise.all 两个嵌套 transaction):SAVEPOINT 是栈,交错会乱。
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
19
|
+
import { DB_FILE, requireSqlite, openDatabase, insertRecord, insertEvent, recordExists, readEvents, readRecords, kindOf } from '../sqlite-store.js'
|
|
20
|
+
|
|
21
|
+
export class SqliteBackend {
|
|
22
|
+
#als = new AsyncLocalStorage()
|
|
23
|
+
#tail = Promise.resolve()
|
|
24
|
+
#savepoints = 0
|
|
25
|
+
|
|
26
|
+
/** @param {string} dir */
|
|
27
|
+
constructor(dir) {
|
|
28
|
+
// 在 openBackend 这一步就报错:文档里「try sqlite / catch 退回 file」的写法才真的接得住
|
|
29
|
+
requireSqlite()
|
|
30
|
+
this.dir = dir
|
|
31
|
+
this.kind = 'sqlite'
|
|
32
|
+
this.file = path.join(dir, DB_FILE)
|
|
33
|
+
this.db = null
|
|
34
|
+
this.capabilities = { transactions: true, wal: true, engine: 'sqlite' }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 当前调用是不是在本对象正在进行的事务的调用链里 */
|
|
38
|
+
get inTransaction() {
|
|
39
|
+
return this.#als.getStore() === this
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#open() {
|
|
43
|
+
if (!this.db) this.db = openDatabase(this.dir, { create: true })
|
|
44
|
+
return this.db
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 排队:同一时刻只跑一个(事务,或一次事务外的读写)
|
|
48
|
+
async #exclusive(task) {
|
|
49
|
+
const prev = this.#tail
|
|
50
|
+
let release
|
|
51
|
+
this.#tail = new Promise((resolve) => { release = resolve })
|
|
52
|
+
try {
|
|
53
|
+
await prev
|
|
54
|
+
return await task()
|
|
55
|
+
} finally {
|
|
56
|
+
release()
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 事务外:排队后自己开一个事务;事务里:直接跑
|
|
61
|
+
async #run(fn) {
|
|
62
|
+
if (this.inTransaction) return fn(this.#open())
|
|
63
|
+
return this.#exclusive(async () => fn(this.#open()))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 一组同步写入要么全成、要么全不成:事务里用 SAVEPOINT,事务外用 BEGIN IMMEDIATE
|
|
67
|
+
#group(db, fn) {
|
|
68
|
+
if (this.inTransaction) {
|
|
69
|
+
const sp = 'wm_sp_' + (++this.#savepoints)
|
|
70
|
+
db.exec('SAVEPOINT ' + sp)
|
|
71
|
+
try {
|
|
72
|
+
const result = fn()
|
|
73
|
+
db.exec('RELEASE ' + sp)
|
|
74
|
+
return result
|
|
75
|
+
} catch (error) {
|
|
76
|
+
db.exec('ROLLBACK TO ' + sp)
|
|
77
|
+
db.exec('RELEASE ' + sp)
|
|
78
|
+
throw error
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
db.exec('BEGIN IMMEDIATE')
|
|
82
|
+
try {
|
|
83
|
+
const result = fn()
|
|
84
|
+
db.exec('COMMIT')
|
|
85
|
+
return result
|
|
86
|
+
} catch (error) {
|
|
87
|
+
db.exec('ROLLBACK')
|
|
88
|
+
throw error
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {object} record */
|
|
93
|
+
async append(record) {
|
|
94
|
+
return this.#run((db) => insertRecord(db, record))
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 追加一条事件(原样存这一行的 JSON,不改形状)。
|
|
99
|
+
* mustExist:先确认这条事件指向的经历都在库里(联想两头都查;章节不指向经历,不查);查和写在同一个事务里。
|
|
100
|
+
* 这是低层追加:不做「重复封存算 noop」这类业务判断,那些在上层。
|
|
101
|
+
*/
|
|
102
|
+
async appendEvent(kind, row, { mustExist = false } = {}) {
|
|
103
|
+
const k = kindOf(kind)
|
|
104
|
+
return this.#run((db) => this.#group(db, () => {
|
|
105
|
+
if (mustExist && k.valid(row)) {
|
|
106
|
+
const missing = k.expIds(row).filter((id) => !recordExists(db, id))
|
|
107
|
+
if (missing.length) throw new Error('找不到这条经历:' + missing.join('、') + '(事件没有写入)')
|
|
108
|
+
}
|
|
109
|
+
return insertEvent(db, kind, row)
|
|
110
|
+
}))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 一条经历 + 它的若干事件,同一个事务写:任何一条失败(重复 id、事件不合格),整组都不落盘。
|
|
115
|
+
* 在 transaction() 里调用时同样成立(这一组包在 SAVEPOINT 里)。
|
|
116
|
+
* @param {object} record
|
|
117
|
+
* @param {{ kind: string, row: object }[]} events
|
|
118
|
+
*/
|
|
119
|
+
async appendWithEvents(record, events = []) {
|
|
120
|
+
return this.#run((db) => this.#group(db, () => {
|
|
121
|
+
insertRecord(db, record)
|
|
122
|
+
for (const e of events) insertEvent(db, e && e.kind, e && e.row)
|
|
123
|
+
return record
|
|
124
|
+
}))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async all() {
|
|
128
|
+
return this.#run((db) => {
|
|
129
|
+
const { rows, bad } = readRecords(db)
|
|
130
|
+
// 坏数据整体失败,不当空
|
|
131
|
+
if (bad) throw new Error('memory.sqlite 里有 ' + bad + ' 条记录解析不了(拒绝当作空)')
|
|
132
|
+
return rows
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 某一类事件,按追加顺序。坏行整体失败,不当空。 */
|
|
137
|
+
async events(kind) {
|
|
138
|
+
kindOf(kind)
|
|
139
|
+
return this.#run((db) => {
|
|
140
|
+
const { rows, bad } = readEvents(db, kind)
|
|
141
|
+
if (bad) throw new Error('memory.sqlite 里 ' + kind + ' 事件有 ' + bad + ' 条解析不了或不合格(拒绝当作空)')
|
|
142
|
+
return rows
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {string} id */
|
|
147
|
+
async byId(id) {
|
|
148
|
+
return this.#run((db) => {
|
|
149
|
+
const row = db.prepare('SELECT json FROM records WHERE id = ?').get(String(id))
|
|
150
|
+
return row ? JSON.parse(row.json) : null
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 按本地日取(契约里的 day 语义)。 */
|
|
155
|
+
async byDay(day) {
|
|
156
|
+
return this.#run((db) => db.prepare('SELECT json FROM records WHERE day = ? ORDER BY rowid').all(String(day)).map((r) => JSON.parse(r.json)))
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async count() {
|
|
160
|
+
return this.#run((db) => db.prepare('SELECT COUNT(*) AS c FROM records').get().c)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 事务里跑一段(记录与事件都在同一个事务里)。失败自动回滚。
|
|
165
|
+
* 嵌套调用(在 fn 里再 transaction)是一层 SAVEPOINT:内层失败只撤内层,错误照常抛给外层。
|
|
166
|
+
*/
|
|
167
|
+
async transaction(fn) {
|
|
168
|
+
if (this.inTransaction) {
|
|
169
|
+
const db = this.#open()
|
|
170
|
+
const sp = 'wm_sp_' + (++this.#savepoints)
|
|
171
|
+
db.exec('SAVEPOINT ' + sp)
|
|
172
|
+
try {
|
|
173
|
+
const result = await fn(this)
|
|
174
|
+
db.exec('RELEASE ' + sp)
|
|
175
|
+
return result
|
|
176
|
+
} catch (error) {
|
|
177
|
+
db.exec('ROLLBACK TO ' + sp)
|
|
178
|
+
db.exec('RELEASE ' + sp)
|
|
179
|
+
throw error
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return this.#exclusive(async () => {
|
|
183
|
+
const db = this.#open()
|
|
184
|
+
db.exec('BEGIN IMMEDIATE')
|
|
185
|
+
try {
|
|
186
|
+
const result = await this.#als.run(this, () => fn(this))
|
|
187
|
+
db.exec('COMMIT')
|
|
188
|
+
return result
|
|
189
|
+
} catch (error) {
|
|
190
|
+
db.exec('ROLLBACK')
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async close() {
|
|
197
|
+
// 事务里关连接会让外层事务永远等不到自己(排队等的正是它):直接拒绝
|
|
198
|
+
if (this.inTransaction) throw new Error('事务进行中不能 close()')
|
|
199
|
+
return this.#exclusive(async () => {
|
|
200
|
+
if (this.db) {
|
|
201
|
+
this.db.close()
|
|
202
|
+
this.db = null
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -26,4 +26,8 @@ export function decide(memDir: string, opts: { id: string; choice: UnfinishedCho
|
|
|
26
26
|
export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
|
|
27
27
|
/** until:按这一刻(毫秒时间戳)之前(含)的选择重放 */
|
|
28
28
|
export function latestByExp(memDir: string, opts?: { until?: number | null }): Map<string, UnfinishedLatest>
|
|
29
|
+
/** 同 latestByExp,但输入是已经读出的行(不碰文件) */
|
|
30
|
+
export function latestRows(rows: UnfinishedEvent[], opts?: { until?: number | null }): Map<string, UnfinishedLatest>
|
|
31
|
+
/** 一行算不算合格的「没弄完」事件(文件与 SQLite 同一条判据) */
|
|
32
|
+
export function isValid(row: unknown): boolean
|
|
29
33
|
export function countByExp(memDir: string): Map<string, number>
|
package/lib/unfinished-events.js
CHANGED
|
@@ -82,17 +82,26 @@ export function readAll(memDir) {
|
|
|
82
82
|
if (!line.trim()) continue
|
|
83
83
|
try {
|
|
84
84
|
const r = JSON.parse(line)
|
|
85
|
-
if (
|
|
85
|
+
if (isValid(r)) rows.push(r)
|
|
86
86
|
else bad += 1
|
|
87
87
|
} catch { bad += 1 }
|
|
88
88
|
}
|
|
89
89
|
return { rows, bad }
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
// 一行算不算合格的「没弄完」事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
|
|
93
|
+
export function isValid(r) {
|
|
94
|
+
return Boolean(r && r.id && CHOICES.has(r.choice))
|
|
95
|
+
}
|
|
96
|
+
|
|
92
97
|
// 每个经历 id 的最新状态,附带完整的选择历史(渲染"中间放下过"要用)
|
|
93
98
|
// until:按这一刻之前(含)的选择重放,「翻回那天的自己」用
|
|
94
99
|
export function latestByExp(memDir, { until = null } = {}) {
|
|
95
|
-
|
|
100
|
+
return latestRows(readAll(memDir).rows, { until })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
|
|
104
|
+
export function latestRows(rows, { until = null } = {}) {
|
|
96
105
|
const map = new Map()
|
|
97
106
|
for (const r of rows) {
|
|
98
107
|
if (!before(r, until)) continue
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whale-memory-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.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",
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
"types": "./lib/action-source.d.ts",
|
|
18
18
|
"default": "./lib/action-source.js"
|
|
19
19
|
},
|
|
20
|
+
"./hybrid-recall": {
|
|
21
|
+
"types": "./lib/hybrid-recall.d.ts",
|
|
22
|
+
"default": "./lib/hybrid-recall.js"
|
|
23
|
+
},
|
|
20
24
|
"./self-experience": {
|
|
21
25
|
"types": "./lib/self-experience.d.ts",
|
|
22
26
|
"default": "./lib/self-experience.js"
|
|
@@ -136,7 +140,10 @@
|
|
|
136
140
|
"./injection": {
|
|
137
141
|
"types": "./lib/injection.d.ts",
|
|
138
142
|
"default": "./lib/injection.js"
|
|
139
|
-
}
|
|
143
|
+
},
|
|
144
|
+
"./storage/backend": "./lib/storage/backend.js",
|
|
145
|
+
"./storage/file-backend": "./lib/storage/file-backend.js",
|
|
146
|
+
"./storage/sqlite-backend": "./lib/storage/sqlite-backend.js"
|
|
140
147
|
},
|
|
141
148
|
"files": [
|
|
142
149
|
"index.js",
|