@kenz1117/dsh-engram 0.9.6 → 0.9.7

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.
@@ -1,63 +1,321 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * 嵌入回填:给已有但缺向量的记忆补算 embedding。
4
- * 场景:嵌入器曾降级(模型未就绪)时摄取/保存的记忆没有向量,
5
- * 语义检索上线后运行本脚本一次,让存量记忆参与向量道。
3
+ * 嵌入回填:给已有记忆补算向量,或在换了嵌入模型之后重建全部向量。
6
4
  *
7
- * 用法:node scripts/backfill-embeddings.mjs [dbDir]
8
- * 默认 dbDir = ~/.dsh/engram;只处理 active 且 embedding IS NULL 的条目。
5
+ * 场景 A(默认):嵌入器曾降级(模型未就绪)时写入的记忆没有向量——语义检索
6
+ * 上线后跑一次本脚本,让存量记忆参与向量道。
7
+ * 场景 B(--force):换了嵌入模型(`embedder.localModel` / `embedder.localPooling`)。
8
+ * 库中旧向量与新模型维度不同,store 会用 EMBEDDER_DIMENSION_MISMATCH 拒绝写入与
9
+ * 比较,所以换模型必须把向量整体重建,而不是逐条截断。
10
+ *
11
+ * 用法:
12
+ * node scripts/backfill-embeddings.mjs [dbDir] [--force] [--model <id>]
13
+ * [--pooling mean|cls] [--cache-dir <path>]
14
+ *
15
+ * 参数:
16
+ * dbDir 宫殿根目录;默认 ~/.dsh/engram。脚本扫描其中的
17
+ * user.db / shared.db / project-<hash>.db——全部分库,
18
+ * 而不只是默认库。
19
+ * --force 重建全部向量,而不只补 NULL:nodes 里所有已有向量或 active
20
+ * 的行,observations 里所有已有向量或未被否定的行。
21
+ * --model <id> 嵌入模型标识;默认 Xenova/paraphrase-multilingual-MiniLM-L12-v2
22
+ * (384 维,与插件默认一致)。
23
+ * --pooling <mode> 池化方式:mean(默认)| cls(bge-m3 等 XLM-R 同族模型)。
24
+ * --cache-dir <dir> 模型缓存目录;默认 <dbDir>/models。
25
+ * -h, --help 显示本说明。
26
+ *
27
+ * 维度是硬约束:不带 --force 时,若模型维度与库中已有向量不一致,脚本在写入前
28
+ * 就报错退出,绝不会写出混合维度的库;--force 写完后校验全库只剩一个维度。
29
+ *
30
+ * 远程嵌入器(`embedder.kind = remote`)不在本脚本覆盖范围:这里跑的是
31
+ * transformers.js 本地推理,复现不了远程端点的向量。请把 kind 切回 local 重建,
32
+ * 或按端点自己的重建手段处理。
9
33
  */
10
34
 
11
- import { DatabaseSync } from 'node:sqlite'
12
- import { join } from 'node:path'
35
+ import { existsSync, readdirSync } from 'node:fs'
13
36
  import { homedir } from 'node:os'
14
- import { pipeline, env } from '@huggingface/transformers'
37
+ import { basename, join } from 'node:path'
38
+ import { DatabaseSync } from 'node:sqlite'
15
39
 
16
- const dbDir = process.argv[2] ?? join(homedir(), '.dsh', 'engram')
17
- const modelCacheDir = join(dbDir, 'models')
18
- const MODEL_ID = 'Xenova/bge-small-zh-v1.5'
40
+ /** 插件默认模型;与 src/embedder/local.ts 的 ENGRAM_MODEL_ID 保持一致。 */
41
+ const DEFAULT_MODEL_ID = 'Xenova/paraphrase-multilingual-MiniLM-L12-v2'
19
42
 
20
- const dbs = ['user.db', 'project-db'].map(name => join(dbDir, name)).filter(p => {
21
- try { return new DatabaseSync(p, { readOnly: true }) && true } catch { return false }
22
- })
23
- if (dbs.length === 0) {
24
- console.log('[backfill] 未找到任何记忆分库,无需回填')
25
- process.exit(0)
43
+ /** 默认池化方式:多数句向量模型按 mean 训练。 */
44
+ const DEFAULT_POOLING = 'mean'
45
+
46
+ /** 单批推理的文本条数:太小拖慢,太大吃内存。 */
47
+ const CHUNK = 128
48
+
49
+ /** 浮点数在 BLOB 里的字节数:维度按浮点数个数算,不按字节。 */
50
+ const BYTES_PER_FLOAT = Float32Array.BYTES_PER_ELEMENT
51
+
52
+ /** 分库文件名:与插件 project/identity.ts、index.ts 的命名一致。 */
53
+ const DB_FILE_PATTERN = /^(?:user|shared|project-[0-9a-f]{24})\.db$/
54
+
55
+ const USAGE = `用法:node scripts/backfill-embeddings.mjs [dbDir] [--force] [--model <id>] [--pooling mean|cls] [--cache-dir <path>]
56
+
57
+ dbDir 宫殿根目录;默认 ~/.dsh/engram
58
+ --force 重建全部向量(换模型后用),而不只补 NULL
59
+ --model <id> 嵌入模型标识;默认 ${DEFAULT_MODEL_ID}
60
+ --pooling <mode> mean(默认)| cls
61
+ --cache-dir <dir> 模型缓存目录;默认 <dbDir>/models
62
+ -h, --help 显示本说明`
63
+
64
+ /**
65
+ * 报错退出:参数错误一律在动数据库之前失败。
66
+ * @param {string} text 给人看的错误文本。
67
+ */
68
+ function fail(text) {
69
+ console.error(`[backfill] ${text}`)
70
+ process.exit(1)
71
+ }
72
+
73
+ /**
74
+ * 解析命令行。
75
+ * @param {string[]} argv process.argv.slice(2)。
76
+ * @returns {{dbDir: string | undefined, force: boolean, model: string, pooling: 'mean' | 'cls', cacheDir: string | undefined, help: boolean}}
77
+ */
78
+ function parseArgs(argv) {
79
+ const options = {
80
+ dbDir: undefined,
81
+ force: false,
82
+ model: DEFAULT_MODEL_ID,
83
+ pooling: DEFAULT_POOLING,
84
+ cacheDir: undefined,
85
+ help: false,
86
+ }
87
+ for (let index = 0; index < argv.length; index += 1) {
88
+ const raw = argv[index]
89
+ if (raw === '--help' || raw === '-h') {
90
+ options.help = true
91
+ continue
92
+ }
93
+ if (raw === '--force') {
94
+ options.force = true
95
+ continue
96
+ }
97
+ if (raw.startsWith('--')) {
98
+ const split = raw.indexOf('=')
99
+ const name = split === -1 ? raw.slice(2) : raw.slice(2, split)
100
+ const inline = split === -1 ? undefined : raw.slice(split + 1)
101
+ if (name !== 'model' && name !== 'pooling' && name !== 'cache-dir') {
102
+ fail(`未知参数 --${name}(用 --help 查看用法)`)
103
+ }
104
+ const value = inline ?? argv[(index += 1)]
105
+ if (value === undefined) fail(`参数 --${name} 缺少取值`)
106
+ if (name === 'model') options.model = value
107
+ else if (name === 'pooling') options.pooling = value
108
+ else options.cacheDir = value
109
+ continue
110
+ }
111
+ if (options.dbDir !== undefined) fail(`多余的位置参数 ${raw}`)
112
+ options.dbDir = raw
113
+ }
114
+ if (options.pooling !== 'mean' && options.pooling !== 'cls') {
115
+ fail(`--pooling 只接受 mean 或 cls,收到 ${options.pooling}`)
116
+ }
117
+ if (options.model.trim() === '') fail('--model 不能为空')
118
+ return options
26
119
  }
27
120
 
28
- env.cacheDir = modelCacheDir
29
- // 下载端点可经 HF_ENDPOINT 覆盖(镜像);模型已在缓存时不会访问网络。
30
- if (process.env.HF_ENDPOINT) env.remoteHost = process.env.HF_ENDPOINT
31
- const extractor = await pipeline('feature-extraction', MODEL_ID, { dtype: 'q8' })
32
- const embed = async text => {
33
- const output = await extractor([text], { pooling: 'mean', normalize: true })
34
- return new Float32Array(output.tolist()[0])
121
+ /**
122
+ * 表是否存在:旧库可能还没有 observations 表。
123
+ * @param {DatabaseSync} db 已打开的库。
124
+ * @param {string} name 表名。
125
+ * @returns {boolean}
126
+ */
127
+ function hasTable(db, name) {
128
+ return db.prepare("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== undefined
35
129
  }
36
130
 
37
- let patched = 0
38
- for (const path of dbs) {
39
- const db = new DatabaseSync(path)
40
- const rows = db.prepare("SELECT id, content FROM nodes WHERE status = 'active' AND embedding IS NULL").all()
41
- if (rows.length === 0) {
42
- console.log(`[backfill] ${path}: 无缺向量条目`)
43
- db.close()
44
- continue
131
+ /**
132
+ * 库中已有向量的维度(浮点数个数)。
133
+ *
134
+ * 与 store 的读法一致:nodes 与 observations 一起看,任一边维度不对都会让语义
135
+ * 检索失真。库里还没有向量时返回 undefined。
136
+ * @param {DatabaseSync} db 已打开的库。
137
+ * @returns {number | undefined}
138
+ */
139
+ function readStoredDim(db) {
140
+ const queries = []
141
+ if (hasTable(db, 'nodes')) queries.push('SELECT LENGTH(embedding) AS bytes FROM nodes WHERE embedding IS NOT NULL')
142
+ if (hasTable(db, 'observations')) queries.push('SELECT LENGTH(embedding) AS bytes FROM observations WHERE embedding IS NOT NULL')
143
+ if (queries.length === 0) return undefined
144
+ const row = db.prepare(`${queries.join(' UNION ALL ')} LIMIT 1`).get()
145
+ return row === undefined ? undefined : row.bytes / BYTES_PER_FLOAT
146
+ }
147
+
148
+ /**
149
+ * 全库维度清单:写完后的校验依据。
150
+ * @param {DatabaseSync} db 已打开的库。
151
+ * @returns {number[]} 去重后的维度列表。
152
+ */
153
+ function storedDims(db) {
154
+ const dims = new Set()
155
+ for (const table of ['nodes', 'observations']) {
156
+ if (!hasTable(db, table)) continue
157
+ const rows = db.prepare(`SELECT DISTINCT LENGTH(embedding) AS bytes FROM ${table} WHERE embedding IS NOT NULL`).all()
158
+ for (const row of rows) dims.add(row.bytes / BYTES_PER_FLOAT)
159
+ }
160
+ return [...dims]
161
+ }
162
+
163
+ /**
164
+ * 列出要处理的分库。
165
+ *
166
+ * 插件把三个作用域写成三种文件名:user.db、shared.db、project-<hash>.db。
167
+ * 只按固定名字找会漏掉共享库与全部项目库,所以这里扫目录。
168
+ * @param {string} dbDir 宫殿根目录。
169
+ * @returns {string[]} 绝对路径列表(按文件名排序)。
170
+ */
171
+ function findDatabases(dbDir) {
172
+ if (!existsSync(dbDir)) return []
173
+ return readdirSync(dbDir)
174
+ .filter(name => DB_FILE_PATTERN.test(name))
175
+ .sort()
176
+ .map(name => join(dbDir, name))
177
+ }
178
+
179
+ /**
180
+ * 建本地嵌入器:transformers.js + q8 量化权重,与插件默认路径一致。
181
+ * @param {{model: string, pooling: 'mean' | 'cls', cacheDir: string}} options 嵌入参数。
182
+ * @returns {Promise<(texts: string[]) => Promise<Float32Array[]>>} 批量取向量。
183
+ */
184
+ async function createEmbedder(options) {
185
+ // 动态 import:--help 与参数错误不加载模型运行时。
186
+ const { env, pipeline } = await import('@huggingface/transformers')
187
+ env.cacheDir = options.cacheDir
188
+ // 下载端点可经 HF_ENDPOINT 覆盖(镜像);模型已在缓存时不会访问网络。
189
+ if (process.env.HF_ENDPOINT) env.remoteHost = process.env.HF_ENDPOINT
190
+ const extractor = await pipeline('feature-extraction', options.model, { dtype: 'q8' })
191
+ return async texts => {
192
+ const output = await extractor([...texts], { pooling: options.pooling, normalize: true })
193
+ return output.tolist().map(list => new Float32Array(list))
194
+ }
195
+ }
196
+
197
+ /**
198
+ * 把一个分库里的目标行全部算成向量,再在一个事务里写回。
199
+ *
200
+ * 先算后写:推理可能要跑很久(首次还要下载模型),不该把写事务开在那里。
201
+ * @param {DatabaseSync} db 已打开的库。
202
+ * @param {string} name 显示用的库名。
203
+ * @param {(texts: string[]) => Promise<Float32Array[]>} embed 批量取向量。
204
+ * @param {boolean} force 是否重建已有向量。
205
+ * @returns {Promise<{written: number, dim: number | undefined}>} 写入条数与最终维度。
206
+ */
207
+ async function processDatabase(db, name, embed, force) {
208
+ /** 一次处理的表:读哪列、挑哪些行、写回哪。 */
209
+ const targets = []
210
+ if (hasTable(db, 'nodes')) {
211
+ targets.push({
212
+ table: 'nodes',
213
+ text: 'content',
214
+ where: force ? "(status = 'active' OR embedding IS NOT NULL)" : "status = 'active' AND embedding IS NULL",
215
+ })
216
+ }
217
+ if (hasTable(db, 'observations')) {
218
+ targets.push({
219
+ table: 'observations',
220
+ text: 'belief',
221
+ where: force ? "(status != 'refuted' OR embedding IS NOT NULL)" : "status != 'refuted' AND embedding IS NULL",
222
+ })
223
+ }
224
+
225
+ // 先读出全部待办行:写事务之前就要知道有多少活。
226
+ const jobs = []
227
+ for (const target of targets) {
228
+ const rows = db.prepare(`SELECT id, ${target.text} AS text FROM ${target.table} WHERE ${target.where}`).all()
229
+ for (const row of rows) jobs.push({ table: target.table, id: row.id, text: row.text })
230
+ }
231
+ if (jobs.length === 0) {
232
+ console.log(`[backfill] ${name}: 无待处理条目`)
233
+ return { written: 0, dim: readStoredDim(db) }
234
+ }
235
+
236
+ const storedDim = readStoredDim(db)
237
+ console.log(`[backfill] ${name}: 待处理 ${jobs.length} 条${storedDim === undefined ? '' : `,库中向量 ${storedDim} 维`}`)
238
+
239
+ // 推理放在事务外:算完一批再写,事务不会挂很久。
240
+ const vectors = []
241
+ for (let start = 0; start < jobs.length; start += CHUNK) {
242
+ const slice = jobs.slice(start, start + CHUNK)
243
+ const computed = await embed(slice.map(job => job.text))
244
+ if (computed.length !== slice.length) {
245
+ throw new Error(`嵌入器返回 ${computed.length} 条向量,期望 ${slice.length} 条`)
246
+ }
247
+ vectors.push(...computed)
248
+ console.log(`[backfill] ${name}: ${Math.min(start + CHUNK, jobs.length)}/${jobs.length}`)
45
249
  }
250
+
251
+ const dim = vectors[0].length
252
+ if (!force && storedDim !== undefined && storedDim !== dim) {
253
+ throw new Error(
254
+ `模型给出 ${dim} 维向量,库中已有 ${storedDim} 维——不加 --force 会写出混合维度的库。`
255
+ + `换模型请用 --force 重建全部向量,或把模型改回与库一致。`,
256
+ )
257
+ }
258
+
46
259
  db.exec('BEGIN')
47
260
  try {
48
- for (const row of rows) {
49
- const vector = await embed(row.content)
50
- db.prepare('UPDATE nodes SET embedding = ? WHERE id = ?')
51
- .run(new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength), row.id)
52
- patched += 1
53
- console.log(`[backfill] ${path}: ${row.content.slice(0, 24)}… ✓`)
261
+ for (const table of ['nodes', 'observations']) {
262
+ if (!hasTable(db, table)) continue
263
+ const statement = db.prepare(`UPDATE ${table} SET embedding = ? WHERE id = ?`)
264
+ for (let index = 0; index < jobs.length; index += 1) {
265
+ const job = jobs[index]
266
+ if (job.table !== table) continue
267
+ const vector = vectors[index]
268
+ statement.run(new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength), job.id)
269
+ }
270
+ }
271
+ // 校验放在提交之前:维度一旦不一致就整体回滚,库保持原样。
272
+ const dims = storedDims(db)
273
+ if (dims.length > 1) {
274
+ throw new Error(`写完后仍有多个维度 ${dims.join(', ')}——已回滚`)
54
275
  }
55
276
  db.exec('COMMIT')
56
277
  } catch (error) {
57
278
  db.exec('ROLLBACK')
58
- db.close()
59
279
  throw error
60
280
  }
281
+ return { written: jobs.length, dim }
282
+ }
283
+
284
+ const options = parseArgs(process.argv.slice(2))
285
+ if (options.help) {
286
+ console.log(USAGE)
287
+ process.exit(0)
288
+ }
289
+
290
+ const dbDir = options.dbDir ?? join(homedir(), '.dsh', 'engram')
291
+ const cacheDir = options.cacheDir ?? join(dbDir, 'models')
292
+ const paths = findDatabases(dbDir)
293
+ if (paths.length === 0) {
294
+ console.log(`[backfill] ${dbDir} 下没有记忆分库,无需回填`)
295
+ process.exit(0)
296
+ }
297
+
298
+ console.log(
299
+ `[backfill] 模型 ${options.model}(pooling=${options.pooling}),`
300
+ + `${options.force ? '重建全部向量' : '只补缺失向量'},共 ${paths.length} 个分库`,
301
+ )
302
+
303
+ const embed = await createEmbedder({ model: options.model, pooling: options.pooling, cacheDir })
304
+
305
+ let total = 0
306
+ for (const path of paths) {
307
+ const name = basename(path)
308
+ const db = new DatabaseSync(path)
309
+ let written = 0
310
+ try {
311
+ const result = await processDatabase(db, name, embed, options.force)
312
+ written = result.written
313
+ } catch (error) {
314
+ // 单个分库失败就整体停下:半新半旧的向量比没有向量更难查。
315
+ db.close()
316
+ fail(`${name}: ${error instanceof Error ? error.message : String(error)}`)
317
+ }
61
318
  db.close()
319
+ total += written
62
320
  }
63
- console.log(`[backfill] 完成:共补算 ${patched} 条向量`)
321
+ console.log(`[backfill] 完成:共写入 ${total} 条向量`)