@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.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/migrate.js ADDED
@@ -0,0 +1,1722 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 旧 JSON 记忆库 → TriviumDB 的迁移、双写开关、校验、回滚与报告(平台计划 todo 13)。
4
+ *
5
+ * 只做一件事:把 `store.js` 的每个 workspace JSON 文档读成信封(`envelope.js#fromLegacyEntry`
6
+ * 是唯一映射),嵌入(`embed.js`,e5 要求文档侧 `passage: ` 前缀),写进该 workspace 的
7
+ * TriviumDB,再换一个新的子进程把数据读回来校验。JSON 从始至终只读——迁移失败、校验失败、
8
+ * 回滚都不会删除或改写旧库(P5 的删除是 todo 43 的事)。
9
+ *
10
+ * 为什么是这个形状(todo 10/12 的实测,不是选择):
11
+ * 1. TriviumDB 是文件级独占租约:同一路径在同一个进程里开第二个门面会立刻 TDB_DATABASE_LOCKED。
12
+ * 所以本文件按「一个 scope 一个门面、用完就 close」串行使用;调用方(插件)应把已经打开的
13
+ * 那个门面通过 `options.trivium` 传进来,不要在这里再开一个。本模块自己不维护门面注册表,
14
+ * 共享一个门面是 todo 16 的事。
15
+ * 2. `store-trivium.js` 的 DEFAULT_DIM = 1536 只是占位,建索引必须显式传 EMBEDDING_DIM(384);
16
+ * 本文件在 open() 后断言 dim === 384,并用「错宽查询被拒」证明库里存的就是 384 维
17
+ * (以 384 建的库用别的维度打开会在 open 阶段抛 TDB_DIMENSION_MISMATCH,不会静默写错宽向量)。
18
+ * 3. 迁移必须幂等:以 legacy_id + 信封内容判断「已迁移且一致 → 复用」,不一致即失败,绝不覆盖
19
+ * (门面没有删除/更新原语,覆盖只能重建库,那是另一个决定)。
20
+ * 4. 双写窗口里 JSON 仍是权威读者(state.authoritative === 'json'):写入先落 JSON,再落库;
21
+ * 落库失败抛出带 jsonWritten: true 的错误,调用方必须知道两边已经分叉。
22
+ * 5. 校验的检索一致性用**确定性查询集**(首/中/尾,不抽样):主判定是「每个查询在两库 top-k 里
23
+ * 都能取回查询文本」,要求全部命中;Jaccard 重合率只作诊断字段写进报告(gating: false),
24
+ * 不参与 ok。抽样种子默认固定(DEFAULT_SEED),`--seed` 只影响报告列哪几条样本,不影响判定。
25
+ * 6. 信封的 `dynamic_relations` 必须落成**边**(任务 49):只写节点的话,迁移库上图臂恒为
26
+ * `degraded:'no_edges'`。目标按「本次迁移的 legacy_id」解析;`belongs_to_session` 的目标是
27
+ * 会话字符串而不是节点,所以为它建一个零向量的**会话锚点节点**(`kind:'kanabo-session'`),
28
+ * 并把这条成员关系**双向**写成边——TriviumDB 的边有向,而图臂只走出边,单向的话
29
+ * 「种子 → 会话锚点 → 同会话的下一条记忆」永远走不到第二跳。
30
+ * 7. 文本索引写 `topic + 正文`(payload 的 `text` 保持正文本身):旧实现的检索把 topic 算进命中,
31
+ * 只索引正文会让「只有 topic 沾边」的条目在新文本臂上凭空消失。
32
+ * 8. 旧条目自带的 `dynamic_relations`(契约形状)也一并落成边:`fromLegacyEntry` 只为每条记录
33
+ * 生成一个 `belongs_to_session`,若旧记录已经记了 `triggered_by` / `followed_by`,
34
+ * 迁移把它们合并进信封(同一 (label,target) 去重)再写边,而不是静默丢掉。
35
+ * 9. 旧记录可以是两种形状:`addEntry` 的扁平形状(走 `fromLegacyEntry`),或**已经是契约信封**
36
+ * (带 `source_type`,视觉/音频侧写入的形状,走 `validateEnvelope`)。后者是迁移库能同时
37
+ * 装 `VIDEO_CLIP` / `AUDIO_SEGMENT` 的前提——时间窗查询只对这两类有意义。
38
+ * 10. payload 写平铺镜像字段(`source_type` / `video_id|audio_id` / `t0` / `t1` / `ts` / `id`):
39
+ * TQL 不能过滤嵌套路径,时间窗查询(`query-window.js`)只认 payload 顶层字段。嵌套 `envelope`
40
+ * 照旧保留(recall 的 `envelopeOf` 依赖它),并在写入时建 `t0` 有序索引。
41
+ *
42
+ * 插件自己的召回注入块不会被迁移:`recall.js` 的注入是 HEADER + 若干行 + "(N entries)" 的整块
43
+ * 文本;若它被粘贴回对话、又被某条历史路径当成人类文本存进 JSON,本文件按「HEADER 独占一行 +
44
+ * 结尾 footer」两个条件同时命中才跳过(只命中 HEADER 的条目列进 suspects 但仍迁移——宁可少删,
45
+ * 不可误删记忆)。HEADER 字面量在 recall.js 未导出(那文件不在本任务改动范围),故复制一份,
46
+ * 探针会读 recall.js 核对它没有漂移。
47
+ *
48
+ * CLI:`node packages/dsh-kanabo-memory/migrate.js <command> [flags]`
49
+ * migrate --scope <workspace>... | --all-scopes 迁移 + 校验(JSON 只读)
50
+ * verify --scope <workspace>... | --all-scopes 只校验
51
+ * rollback 回到 JSON 权威 + 关闭双写(保留库文件)
52
+ * dual-write on|off 新写入是否同时落库
53
+ * authority json|trivium 读写权威(todo 16 的切换点)
54
+ * state 打印迁移状态
55
+ * 公共 flags:--store-dir、--trivium-dir、--report <base>、--sample N、--top-k K、
56
+ * --threshold R、--seed S、--json。
57
+ * 退出码:0 通过;1 未预期错误;2 预检/校验失败(JSON 未动);3 用法错误。
58
+ *
59
+ * 测试缝:KANABO_MIGRATE_EMBED=deterministic 注入 sha256 派生的 384 维假嵌入器(形状同
60
+ * embed.js,无语义)。只用于探针/离线实验,生产路径只会走 createEmbedder()。
61
+ */
62
+
63
+ import { createHash } from 'node:crypto'
64
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
65
+ import { basename, join, resolve } from 'node:path'
66
+ import { fileURLToPath } from 'node:url'
67
+
68
+ import { EMBEDDING_DIM } from './contract.js'
69
+ import { createEmbedder } from './embed.js'
70
+ import { fromLegacyEntry, validateEnvelope } from './envelope.js'
71
+ import {
72
+ DEFAULT_SCOPE,
73
+ addEntry,
74
+ clip,
75
+ searchEntries,
76
+ storeDir,
77
+ storeFile,
78
+ tokens,
79
+ writeAtomicFile,
80
+ } from './store.js'
81
+ import { createTriviumStore } from './store-trivium.js'
82
+
83
+ export const MIGRATION_STATE_VERSION = 1
84
+ export const MIGRATION_STATE_FILE = 'migration-state.json'
85
+ export const MIGRATION_KIND = 'kanabo-envelope'
86
+ export const RECALL_HEADER = "Recalled from this workspace's memory (shared across sessions):"
87
+ export const PASSAGE_PREFIX = 'passage: '
88
+ export const QUERY_PREFIX = 'query: '
89
+ export const DEFAULT_SAMPLE_SIZE = 20
90
+ export const DEFAULT_TOP_K = 5
91
+ /** 抽样种子的默认值:固定常量,默认跑可复现;只有显式 `--seed` 才引入方差。 */
92
+ export const DEFAULT_SEED = 'kanabo-migration-v1'
93
+ /** 检索重合率的诊断基线(Jaccard)。**不参与通过/失败判定**,只用于报告观察。 */
94
+ export const DEFAULT_OVERLAP_THRESHOLD = 0.4
95
+ export const MAX_INSERT_BATCH = 32
96
+ /** 一批写多少条边:一次 flush 约 130ms,逐条 flush 会把 2000 条边拖成几分钟。 */
97
+ export const MAX_EDGE_BATCH = 32
98
+ /** 会话锚点节点的 kind 与 legacy_id 前缀:与信封节点同一库里共存,但不会被 `kind:kanabo-envelope` 计数。 */
99
+ export const SESSION_NODE_KIND = 'kanabo-session'
100
+ export const SESSION_KEY_PREFIX = 'session:'
101
+ const ROW_LIMIT = 100_000
102
+ const NON_STORE_FILES = new Set([MIGRATION_STATE_FILE, 'cursors.json', 'sweep-state.json'])
103
+
104
+ function migrateError(code, message, extra = {}) {
105
+ const error = new Error(message, extra.cause === undefined ? undefined : { cause: extra.cause })
106
+ error.code = code
107
+ for (const key of ['field', 'entryId', 'reason', 'jsonWritten', 'details']) {
108
+ if (extra[key] !== undefined) error[key] = extra[key]
109
+ }
110
+ return error
111
+ }
112
+
113
+ function sha256(data) {
114
+ return createHash('sha256').update(data).digest('hex')
115
+ }
116
+
117
+ function iso(ms) {
118
+ return new Date(ms).toISOString()
119
+ }
120
+
121
+ export function migrationPaths(options = {}) {
122
+ const dir = resolve(options.storeDir ?? storeDir())
123
+ return {
124
+ dir,
125
+ stateFile: join(dir, MIGRATION_STATE_FILE),
126
+ reportDir: join(dir, 'migration'),
127
+ }
128
+ }
129
+
130
+ function emptyState() {
131
+ return {
132
+ version: MIGRATION_STATE_VERSION,
133
+ dualWrite: false,
134
+ authoritative: 'json',
135
+ migration: null,
136
+ updatedAt: 0,
137
+ }
138
+ }
139
+
140
+ function assertStateShape(state, file) {
141
+ const isObject = state !== null && typeof state === 'object' && !Array.isArray(state)
142
+ if (!isObject || state.version !== MIGRATION_STATE_VERSION
143
+ || typeof state.dualWrite !== 'boolean'
144
+ || (state.authoritative !== 'json' && state.authoritative !== 'trivium')) {
145
+ throw migrateError('KANABO_MIGRATE_STATE_CORRUPT',
146
+ `迁移状态文件形状不对(需要 version:${MIGRATION_STATE_VERSION}、dualWrite 布尔、authoritative json|trivium):${file}`)
147
+ }
148
+ return state
149
+ }
150
+
151
+ /** 文件不存在是正常状态:双写关、JSON 权威(即迁移前的行为)。 */
152
+ export function readMigrationState(options = {}) {
153
+ const { stateFile } = migrationPaths(options)
154
+ let raw
155
+ try {
156
+ raw = readFileSync(stateFile, 'utf8')
157
+ } catch (error) {
158
+ if (error?.code === 'ENOENT') return emptyState()
159
+ throw error
160
+ }
161
+ let parsed
162
+ try {
163
+ parsed = JSON.parse(raw)
164
+ } catch (error) {
165
+ throw migrateError('KANABO_MIGRATE_STATE_CORRUPT', `迁移状态文件不是合法 JSON:${stateFile}`, { cause: error })
166
+ }
167
+ return assertStateShape(parsed, stateFile)
168
+ }
169
+
170
+ export function writeMigrationState(patch, options = {}) {
171
+ const current = readMigrationState(options)
172
+ const next = {
173
+ ...emptyState(),
174
+ ...current,
175
+ ...patch,
176
+ version: MIGRATION_STATE_VERSION,
177
+ updatedAt: Date.now(),
178
+ }
179
+ assertStateShape(next, migrationPaths(options).stateFile)
180
+ writeAtomicFile(migrationPaths(options).stateFile, `${JSON.stringify(next, null, 2)}\n`)
181
+ return next
182
+ }
183
+
184
+ /** 双写开关:ON 时新写入同时落 JSON 与 TriviumDB;OFF 时只落 JSON(与迁移前完全一致)。 */
185
+ export function setDualWrite(enabled, options = {}) {
186
+ return writeMigrationState({ dualWrite: enabled === true, dualWriteAt: Date.now() }, options)
187
+ }
188
+
189
+ /** 读写权威的切换点;迁移本身从不改它,`rollback` 会把它拉回 json。 */
190
+ export function setAuthority(authority, options = {}) {
191
+ if (authority !== 'json' && authority !== 'trivium') {
192
+ throw migrateError('KANABO_MIGRATE_AUTHORITY', `authority 只能是 json 或 trivium(收到 ${String(authority)})`)
193
+ }
194
+ return writeMigrationState({ authoritative: authority, authorityAt: Date.now() }, options)
195
+ }
196
+
197
+ export function isDualWriteEnabled(options = {}) {
198
+ return readMigrationState(options).dualWrite === true
199
+ }
200
+
201
+ /**
202
+ * 识别插件自己的召回注入块:HEADER 独占一行 + 结尾 (N entries) 两个条件同时满足才算。
203
+ * 只命中 HEADER(用户引用了一半)返回 null,由调用方记为 suspect 并照常迁移。
204
+ */
205
+ export function detectOwnInjection(text) {
206
+ const source = String(text ?? '')
207
+ if (!source.includes(RECALL_HEADER)) return null
208
+ const trimmed = source.trimEnd()
209
+ if (!trimmed.split('\n').some((line) => line.trim() === RECALL_HEADER)) return null
210
+ if (!/\(\d+ entries?\)$/.test(trimmed)) return null
211
+ return { marker: 'recall-header+footer' }
212
+ }
213
+
214
+ function digestOfEntry(text) {
215
+ return sha256(String(text ?? ''))
216
+ }
217
+
218
+ /** JSON 文档位置:文件名只由 scope 派生,目录由 `options.storeDir`(优先)或 KANABO_MEMORY_DIR 决定。 */
219
+ function storeDocumentPath(options, scope) {
220
+ return join(resolve(options.storeDir ?? storeDir()), basename(storeFile(scope)))
221
+ }
222
+
223
+ /** 与 store.js 同一份形状契约(version:1 + entries 数组);损坏即抛 KANABO_STORE_CORRUPT。 */
224
+ function readDocument(options, scope, { missingOk = false } = {}) {
225
+ const file = storeDocumentPath(options, scope)
226
+ let raw
227
+ try {
228
+ raw = readFileSync(file)
229
+ } catch (error) {
230
+ if (error?.code !== 'ENOENT') throw error
231
+ if (!missingOk) {
232
+ throw migrateError('KANABO_MIGRATE_SCOPE_MISSING',
233
+ `workspace ${scope} 的 JSON 文档不存在:${file}`, { field: 'scope', details: { scope, file } })
234
+ }
235
+ return { file, exists: false, doc: { version: 1, scope, updatedAt: 0, entries: [] }, sha256: null }
236
+ }
237
+ let doc
238
+ try {
239
+ doc = JSON.parse(raw.toString('utf8'))
240
+ } catch (error) {
241
+ throw migrateError('KANABO_STORE_CORRUPT', `存储文件不是合法 JSON:${file}`, { cause: error })
242
+ }
243
+ if (doc?.version !== 1 || !Array.isArray(doc.entries)) {
244
+ throw migrateError('KANABO_STORE_CORRUPT', `存储文件形状不对(需要 version:1 与 entries 数组):${file}`)
245
+ }
246
+ return { file, exists: true, doc, sha256: sha256(raw) }
247
+ }
248
+
249
+ /** 旧条目自带的 `dynamic_relations`(契约形状):同一 (label,target) 去重后合进信封并重跑校验。 */
250
+ function mergedRelations(entry, envelope) {
251
+ const extra = Array.isArray(entry?.dynamic_relations) ? entry.dynamic_relations : []
252
+ const seen = new Set(envelope.dynamic_relations.map((relation) => `${relation.label}\u0000${relation.target}`))
253
+ const relations = [...envelope.dynamic_relations]
254
+ for (const relation of extra) {
255
+ const key = `${relation?.label}\u0000${relation?.target}`
256
+ if (seen.has(key)) continue
257
+ seen.add(key)
258
+ relations.push(relation)
259
+ }
260
+ // 校验整份信封:非法标签/权重/目标在这里就被拒绝(`KANABO_ENVELOPE_*`),不会写进库。
261
+ return relations.length === envelope.dynamic_relations.length
262
+ ? envelope
263
+ : validateEnvelope({ ...envelope, dynamic_relations: relations })
264
+ }
265
+
266
+ /**
267
+ * 信封的可读文本:CONVERSATION 用 `text`,其余类型(片段/音轨/工具轨迹)用它们自己的描述字段。
268
+ * 这个值用于嵌入与 BM25 索引,不写回 payload(payload 的正文仍是信封自己的字段)。
269
+ */
270
+ function envelopeTextOf(envelope) {
271
+ for (const field of ['text', 'scene_description', 'activity', 'tool_name']) {
272
+ const value = envelope?.[field]
273
+ if (typeof value === 'string' && value.trim() !== '') return value
274
+ }
275
+ const error = envelope?.error
276
+ if (typeof error === 'string' && error.trim() !== '') return error
277
+ return ''
278
+ }
279
+
280
+ /**
281
+ * 旧记录 → 信封,两种公认形状:
282
+ * 1. `store.js#addEntry` 的扁平形状 → `fromLegacyEntry`(唯一映射,不得另写);
283
+ * 2. 已经是契约信封的记录(带 `source_type`,视觉/音频侧写入的形状)→ `validateEnvelope`。
284
+ * 两者都再合并旧记录自带的 `dynamic_relations`(同一 (label,target) 去重)。
285
+ */
286
+ function envelopeForEntry(entry) {
287
+ const base = typeof entry?.source_type === 'string' ? validateEnvelope(entry) : fromLegacyEntry(entry)
288
+ return mergedRelations(entry, base)
289
+ }
290
+
291
+ function planScope(scope, options) {
292
+ const { file, doc, sha256: fileSha256 } = readDocument(options, scope)
293
+ const entries = Array.isArray(doc.entries) ? doc.entries : []
294
+ const plan = {
295
+ scope,
296
+ file,
297
+ fileSha256,
298
+ doc,
299
+ entriesCount: entries.length,
300
+ migratable: [],
301
+ skipped: [],
302
+ suspects: [],
303
+ problems: [],
304
+ }
305
+ const firstSeen = new Map()
306
+ entries.forEach((entry, index) => {
307
+ const id = typeof entry?.id === 'string' && entry.id.length > 0 ? entry.id : null
308
+ if (id !== null) {
309
+ if (firstSeen.has(id)) {
310
+ plan.problems.push({
311
+ index,
312
+ id,
313
+ code: 'KANABO_MIGRATE_DUPLICATE_ID',
314
+ message: `条目 id 重复:${id}(首次出现在 index ${firstSeen.get(id)});迁移无法为两条不同内容保留同一稳定身份。`,
315
+ })
316
+ } else {
317
+ firstSeen.set(id, index)
318
+ }
319
+ }
320
+ const rawText = typeof entry?.text === 'string' && entry.text.trim().length > 0
321
+ ? entry.text
322
+ : (typeof entry?.topic === 'string' ? entry.topic : '')
323
+ const injection = detectOwnInjection(rawText)
324
+ if (injection !== null) {
325
+ plan.skipped.push({ index, id, reason: 'own-injection', marker: injection.marker })
326
+ return
327
+ }
328
+ if (rawText.includes(RECALL_HEADER)) {
329
+ plan.suspects.push({ index, id, reason: 'recall-header-without-footer' })
330
+ }
331
+ try {
332
+ const envelope = envelopeForEntry(entry)
333
+ const body = envelopeTextOf(envelope)
334
+ plan.migratable.push({
335
+ index,
336
+ id: envelope.id,
337
+ entry,
338
+ envelope,
339
+ text: body,
340
+ indexText: indexTextFor(entry?.topic ?? envelope.topic ?? envelope.scene_description, body),
341
+ textSha256: digestOfEntry(body),
342
+ })
343
+ } catch (error) {
344
+ plan.problems.push({
345
+ index,
346
+ id,
347
+ code: typeof error?.code === 'string' ? error.code : 'KANABO_MIGRATE_LEGACY_ROW',
348
+ field: typeof error?.field === 'string' ? error.field : null,
349
+ message: error?.message ?? String(error),
350
+ })
351
+ }
352
+ })
353
+ return plan
354
+ }
355
+
356
+ /** 只认「version:1 + entries 数组 + scope 字符串」的文件;其它 JSON 不是静默跳过,而是问题。 */
357
+ function discoverScopes(options) {
358
+ const { dir } = migrationPaths(options)
359
+ const scopes = []
360
+ const problems = []
361
+ if (!existsSync(dir)) {
362
+ throw migrateError('KANABO_MIGRATE_STORE_DIR_MISSING', `存储目录不存在:${dir}`, { details: { dir } })
363
+ }
364
+ for (const name of readdirSync(dir).sort()) {
365
+ if (!name.endsWith('.json') || NON_STORE_FILES.has(name) || name.startsWith('.')) continue
366
+ const file = join(dir, name)
367
+ let doc
368
+ try {
369
+ doc = JSON.parse(readFileSync(file, 'utf8'))
370
+ } catch (error) {
371
+ problems.push({ file, code: 'KANABO_MIGRATE_NOT_JSON', message: `不是合法 JSON:${error?.message ?? String(error)}` })
372
+ continue
373
+ }
374
+ if (doc?.version === 1 && Array.isArray(doc?.entries) && typeof doc?.scope === 'string' && doc.scope.length > 0) {
375
+ scopes.push(doc.scope)
376
+ continue
377
+ }
378
+ problems.push({
379
+ file,
380
+ code: 'KANABO_MIGRATE_NOT_A_STORE',
381
+ message: '既不是记忆文档(需要 version:1、entries 数组、scope 字符串),也不在已知的非文档文件名单里;拒绝猜测。',
382
+ })
383
+ }
384
+ return { scopes, problems }
385
+ }
386
+
387
+ function resolveScopes(options) {
388
+ const explicit = Array.isArray(options.scopes) ? options.scopes.filter((scope) => typeof scope === 'string' && scope.length > 0) : []
389
+ if (explicit.length > 0) return { scopes: [...new Set(explicit)], problems: [] }
390
+ if (options.allScopes === true) return discoverScopes(options)
391
+ const error = migrateError('KANABO_MIGRATE_SCOPE_REQUIRED',
392
+ '需要至少一个 --scope <workspace>,或 --all-scopes(在 storeDir 顶层发现记忆文档)')
393
+ error.exitCode = 3
394
+ throw error
395
+ }
396
+
397
+ /** 注入的门面绑定某个 workspace:多 scope 或错配都拒绝,避免把两个工作区静默写进同一个库。 */
398
+ function assertFacadeScope(options, scopes) {
399
+ if (options.trivium === undefined || options.trivium === null) return
400
+ if (scopes.length !== 1) {
401
+ throw migrateError('KANABO_MIGRATE_FACADE_SCOPE',
402
+ `注入的门面一次只能服务一个 workspace(收到 ${scopes.length} 个 scope);多 scope 请让本模块自己按序开门面。`)
403
+ }
404
+ const bound = options.trivium.workspace
405
+ if (typeof bound === 'string' && bound !== scopes[0]) {
406
+ throw migrateError('KANABO_MIGRATE_FACADE_SCOPE',
407
+ `注入的门面绑定 workspace ${bound},但本次要迁移 ${scopes[0]};拒绝跨工作区误写。`)
408
+ }
409
+ }
410
+
411
+ /** 测试缝:sha256 派生 384 维单位向量,无语义;前缀被剥掉(passage/query 同向量)。 */
412
+ export function createDeterministicEmbedder(options = {}) {
413
+ const dim = Number.isInteger(options.dim) && options.dim > 0 ? options.dim : EMBEDDING_DIM
414
+ function vectorFor(input) {
415
+ const normalized = String(input ?? '').replace(/^(passage|query):\s*/, '')
416
+ const out = new Float32Array(dim)
417
+ let block = 0
418
+ let offset = 0
419
+ while (offset < dim) {
420
+ const digest = createHash('sha256').update(`${block}\u0000${normalized}`).digest()
421
+ for (let i = 0; i < digest.length && offset < dim; i += 1) {
422
+ out[offset] = (digest[i] - 127.5) / 127.5
423
+ offset += 1
424
+ }
425
+ block += 1
426
+ }
427
+ let norm = 0
428
+ for (const value of out) norm += value * value
429
+ norm = Math.sqrt(norm) || 1
430
+ for (let i = 0; i < dim; i += 1) out[i] /= norm
431
+ return out
432
+ }
433
+ const result = (vector) => ({ vector, degraded: false, reason: null, cached: false })
434
+ return {
435
+ dim,
436
+ providerId: 'deterministic:sha256 (test-only)',
437
+ async load() {
438
+ return { dim, modelId: null }
439
+ },
440
+ async embed(text, callOptions = {}) {
441
+ return result(vectorFor(`${callOptions.prefix ?? ''}${text}`))
442
+ },
443
+ async embedBatch(texts, callOptions = {}) {
444
+ return texts.map((text) => result(vectorFor(`${callOptions.prefix ?? ''}${text}`)))
445
+ },
446
+ close() {},
447
+ }
448
+ }
449
+
450
+ function resolveEmbedder(options) {
451
+ if (options.embedder !== undefined && options.embedder !== null) {
452
+ return { embedder: options.embedder, owned: false }
453
+ }
454
+ if (process.env.KANABO_MIGRATE_EMBED === 'deterministic') {
455
+ return { embedder: createDeterministicEmbedder(), owned: false }
456
+ }
457
+ return { embedder: createEmbedder({}), owned: true }
458
+ }
459
+
460
+ /**
461
+ * 一个 scope 一次门面生命周期。注入的门面(插件共享句柄)不关闭;自己开的用完必关,
462
+ * 因为同一路径在同一个进程里不能有两个活句柄。
463
+ */
464
+ async function withFacade(options, scope, run) {
465
+ if (options.trivium !== undefined && options.trivium !== null) {
466
+ return await run(options.trivium, { owned: false })
467
+ }
468
+ const facade = createTriviumStore({
469
+ workspace: scope,
470
+ dir: options.triviumDir,
471
+ dim: EMBEDDING_DIM,
472
+ idleMs: options.idleMs ?? 15_000,
473
+ requestTimeoutMs: options.requestTimeoutMs,
474
+ })
475
+ try {
476
+ return await run(facade, { owned: true })
477
+ } finally {
478
+ await facade.close()
479
+ }
480
+ }
481
+
482
+ function tqlString(value) {
483
+ return JSON.stringify(String(value))
484
+ }
485
+
486
+ function rowsOf(result) {
487
+ const rows = Array.isArray(result) ? result : (Array.isArray(result?.rows) ? result.rows : [])
488
+ return rows.map((row) => {
489
+ const node = row?._ ?? row
490
+ return { id: Number(node?.id ?? NaN), payload: node?.payload ?? null }
491
+ })
492
+ }
493
+
494
+ async function readWorkspaceRows(facade, scope) {
495
+ const query = `FIND {kind: ${tqlString(MIGRATION_KIND)}, workspace: ${tqlString(scope)}} RETURN * LIMIT ${ROW_LIMIT}`
496
+ return rowsOf(await facade.tql(query))
497
+ }
498
+
499
+ /**
500
+ * 平铺镜像的字段:TQL 不能过滤嵌套路径(`FIND {envelope.t0: …}` 直接 `TDB_QUERY_PARSE`),
501
+ * 而时间窗查询(`query-window.js`)只认 payload **顶层**字段。所以信封照旧整份存在
502
+ * `envelope` 里(recall 的 `envelopeOf` 依赖它),同时把时间窗要用的字段复制到顶层。
503
+ */
504
+ const MIRROR_TYPE_FIELDS = Object.freeze({
505
+ VIDEO_CLIP: Object.freeze(['video_id', 't0', 't1', 'frame_id', 'app', 'activity', 'scene_description', 'keyframe_path']),
506
+ AUDIO_SEGMENT: Object.freeze(['audio_id', 't0', 't1', 'text', 'speaker', 'stem']),
507
+ })
508
+
509
+ /** 向量只进索引,不在 payload 里重复 1.5KB;payload 存契约信封与检索/校验/时间窗要用的扁平键。 */
510
+ function payloadFor(workspace, item) {
511
+ const { envelope } = item
512
+ const payload = {
513
+ kind: MIGRATION_KIND,
514
+ workspace,
515
+ // 顶层镜像 `id`:`recall-trivium` 的显式种子(seedIds)用 `FIND {id: …}` 查 payload 顶层字段,
516
+ // 只靠 `legacy_id` / 嵌套 `envelope.id` 的话,迁移库上的 seedIds 会静默解析成零条。
517
+ id: envelope.id,
518
+ legacy_id: envelope.id,
519
+ source_type: envelope.source_type,
520
+ session_id: envelope.session.id,
521
+ turn: envelope.turn,
522
+ ts: envelope.ts,
523
+ // `evidence_trace` 也在顶层:时间窗的证据指针直接读 payload.evidence_trace。
524
+ evidence_trace: envelope.evidence_trace,
525
+ text_sha256: item.textSha256,
526
+ envelope,
527
+ }
528
+ for (const field of MIRROR_TYPE_FIELDS[envelope.source_type] ?? []) {
529
+ if (envelope[field] !== undefined) payload[field] = envelope[field]
530
+ }
531
+ return payload
532
+ }
533
+
534
+ /**
535
+ * 文本索引的内容:`topic` + 正文。payload 的 `text` 保持正文(预算与注入用正文),
536
+ * 只有 BM25 索引多吃一份 topic——旧实现 `searchEntries` 打分时就是「正文 + topic」。
537
+ * 正文里已经包含 topic 时不重复加(避免把同一个词计两次词频)。
538
+ */
539
+ function indexTextFor(topic, text) {
540
+ const body = String(text ?? '')
541
+ const head = typeof topic === 'string' ? topic.trim() : ''
542
+ if (head === '' || body.includes(head)) return body
543
+ return `${head} ${body}`
544
+ }
545
+
546
+ /**
547
+ * 边的纯规划(不碰库):信封的 `dynamic_relations` → `{ links, anchors, skipped }`。
548
+ *
549
+ * - 目标是本次写入的某个 legacy_id → 直接连到那个节点;
550
+ * - `belongs_to_session` 的目标是会话字符串,库里没有这个节点 → 建**会话锚点**,
551
+ * 并把成员关系双向写成边(有向边 + 只走出边的图臂,必须两个方向都建才走得到同会话的第二跳);
552
+ * - 其余标签(`triggered_by` / `followed_by`)目标不在库内时不编造节点,记入 `skipped`。
553
+ *
554
+ * 写与校验都调这一个函数,因此「应有多少条边、每个标签多少条」只有一个口径。
555
+ */
556
+ function planEdges(items, knownKeys) {
557
+ const keys = knownKeys instanceof Set ? knownKeys : new Set(items.map((item) => item.id))
558
+ const anchors = new Map()
559
+ const links = []
560
+ const skipped = []
561
+ for (const item of items) {
562
+ const relations = Array.isArray(item?.envelope?.dynamic_relations) ? item.envelope.dynamic_relations : []
563
+ for (const relation of relations) {
564
+ const label = relation?.label
565
+ const target = typeof relation?.target === 'string' ? relation.target : ''
566
+ if (target === '' || typeof label !== 'string') continue
567
+ const weight = Number.isFinite(relation?.weight) ? relation.weight : 1
568
+ const metadata = relation?.metadata ?? { legacy_target: target, evidence_trace: relation?.evidence_trace ?? null }
569
+ if (keys.has(target)) {
570
+ links.push({ fromKey: item.id, toKey: target, kind: 'node', label, weight, metadata, bidirectional: false })
571
+ continue
572
+ }
573
+ if (label === 'belongs_to_session') {
574
+ const key = `${SESSION_KEY_PREFIX}${target}`
575
+ if (!anchors.has(key)) anchors.set(key, { key, sessionId: target, ts: Number(item?.envelope?.ts) || 0 })
576
+ links.push({ fromKey: item.id, toKey: key, kind: 'anchor', label, weight, metadata, bidirectional: true })
577
+ continue
578
+ }
579
+ skipped.push({ id: item.id, label, target, reason: 'target-not-in-store' })
580
+ }
581
+ }
582
+ return { links, anchors: [...anchors.values()], skipped }
583
+ }
584
+
585
+ /** 计划里会落成多少条边、每个标签多少条(双向成员关系计两条)。 */
586
+ function tallyEdges(links) {
587
+ const labels = {}
588
+ let total = 0
589
+ for (const link of links) {
590
+ const size = link.bidirectional ? 2 : 1
591
+ labels[link.label] = (labels[link.label] ?? 0) + size
592
+ total += size
593
+ }
594
+ return { total, labels }
595
+ }
596
+
597
+ function anchorPayload(scope, anchor) {
598
+ return {
599
+ kind: SESSION_NODE_KIND,
600
+ // 图「胶水」标记:`recall-trivium` 的图臂会经过它扩散,但不把它当命中返回。
601
+ graph_role: 'anchor',
602
+ workspace: scope,
603
+ legacy_id: anchor.key,
604
+ session_id: anchor.sessionId,
605
+ ts: anchor.ts,
606
+ text: `session ${anchor.sessionId}`,
607
+ }
608
+ }
609
+
610
+ /** 会话锚点:先读已有(重跑复用),缺的才插。零向量——向量臂按 `score <= minVectorScore` 过滤,它永远不会成为向量命中。 */
611
+ async function ensureAnchors(facade, scope, anchors) {
612
+ const ids = new Map()
613
+ if (anchors.length === 0) return { ids, created: 0 }
614
+ const rows = rowsOf(await facade.tql(
615
+ `FIND {kind: ${tqlString(SESSION_NODE_KIND)}, workspace: ${tqlString(scope)}} RETURN *`))
616
+ for (const row of rows) {
617
+ const key = row.payload?.legacy_id
618
+ if (typeof key === 'string' && !ids.has(key)) ids.set(key, row.id)
619
+ }
620
+ const zero = new Array(EMBEDDING_DIM).fill(0)
621
+ let created = 0
622
+ for (const anchor of anchors) {
623
+ if (ids.has(anchor.key)) continue
624
+ const payload = anchorPayload(scope, anchor)
625
+ const inserted = await facade.insert({ vector: zero, payload, text: payload.text })
626
+ ids.set(anchor.key, inserted?.id)
627
+ created += 1
628
+ }
629
+ return { ids, created }
630
+ }
631
+
632
+ /**
633
+ * 把一组信封的 `dynamic_relations` 写成边。迁移与双写共用。
634
+ *
635
+ * `resolveExternal` 打开时,非会话目标若不在本批条目里,会去库里按 `legacy_id` 找已迁移的节点
636
+ * (双写单条信封时用);迁移本身只用本批解析,使「写入的边」与 `planEdges` 的规划完全一致。
637
+ */
638
+ async function writeEdgesForEntries(facade, scope, entries, options = {}) {
639
+ const nodeIdByKey = new Map(entries.map((entry) => [entry.id, entry.nodeId]))
640
+ if (options.resolveExternal === true) {
641
+ const external = new Set()
642
+ for (const entry of entries) {
643
+ for (const relation of entry.envelope?.dynamic_relations ?? []) {
644
+ if (typeof relation?.target === 'string' && !nodeIdByKey.has(relation.target)
645
+ && relation.label !== 'belongs_to_session') external.add(relation.target)
646
+ }
647
+ }
648
+ if (external.size > 0) {
649
+ const literals = [...external].map((key) => JSON.stringify(key)).join(', ')
650
+ const rows = rowsOf(await facade.tql(
651
+ `FIND {kind: ${tqlString(MIGRATION_KIND)}, workspace: ${tqlString(scope)}, legacy_id: {$in: [${literals}]}} RETURN *`))
652
+ for (const row of rows) {
653
+ const key = row.payload?.legacy_id
654
+ if (typeof key === 'string' && !nodeIdByKey.has(key)) nodeIdByKey.set(key, row.id)
655
+ }
656
+ }
657
+ }
658
+ const planned = planEdges(entries, new Set(nodeIdByKey.keys()))
659
+ const anchors = await ensureAnchors(facade, scope, planned.anchors)
660
+ for (const [key, id] of anchors.ids) if (!nodeIdByKey.has(key)) nodeIdByKey.set(key, id)
661
+ const edges = []
662
+ const skipped = [...planned.skipped]
663
+ for (const link of planned.links) {
664
+ const from = nodeIdByKey.get(link.fromKey)
665
+ const to = nodeIdByKey.get(link.toKey)
666
+ if (from === undefined || to === undefined) {
667
+ skipped.push({ id: link.fromKey, label: link.label, target: link.toKey, reason: 'node-id-unresolved' })
668
+ continue
669
+ }
670
+ const edge = { from, to, label: link.label, weight: link.weight, metadata: link.metadata }
671
+ edges.push(edge)
672
+ if (link.bidirectional) edges.push({ ...edge, from: to, to: from })
673
+ }
674
+ let created = 0
675
+ for (let start = 0; start < edges.length; start += MAX_EDGE_BATCH) {
676
+ const result = await facade.link(edges.slice(start, start + MAX_EDGE_BATCH))
677
+ created += Number(result?.created ?? 0)
678
+ }
679
+ if (edges.length > 0) await facade.commit()
680
+ return {
681
+ planned: tallyEdges(planned.links),
682
+ written: edges.length,
683
+ created,
684
+ anchors: anchors.created,
685
+ skipped,
686
+ }
687
+ }
688
+
689
+ function sameEnvelopeText(stored, expected) {
690
+ return stored !== null && typeof stored === 'object'
691
+ && stored.text === expected.text
692
+ && stored.turn === expected.turn
693
+ && stored?.session?.id === expected?.session?.id
694
+ }
695
+
696
+ function mulberry32(seed) {
697
+ let a = seed >>> 0
698
+ return function next() {
699
+ a = (a + 0x6d2b79f5) >>> 0
700
+ let t = a
701
+ t = Math.imul(t ^ (t >>> 15), t | 1)
702
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
703
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
704
+ }
705
+ }
706
+
707
+ function seedOf(options) {
708
+ const raw = options.seed === undefined || options.seed === null ? DEFAULT_SEED : String(options.seed)
709
+ let hash = 0
710
+ for (const char of raw) hash = (Math.imul(hash, 31) + char.codePointAt(0)) >>> 0
711
+ return { seedText: raw, seed: hash }
712
+ }
713
+
714
+ function pickSample(items, size, random) {
715
+ const pool = [...items]
716
+ const wanted = Math.min(Math.max(0, size), pool.length)
717
+ for (let i = pool.length - 1; i > 0; i -= 1) {
718
+ const j = Math.floor(random() * (i + 1))
719
+ const tmp = pool[i]
720
+ pool[i] = pool[j]
721
+ pool[j] = tmp
722
+ }
723
+ return pool.slice(0, wanted)
724
+ }
725
+
726
+ /**
727
+ * 检索一致性的查询集:**确定性**选取(首/中/尾),不来自随机抽样,因此通过/失败与 seed 无关。
728
+ * 只选有词元的文本(零信息查询在 JSON 侧按定义返回空);同文本去重,避免重复条目互相遮蔽。
729
+ */
730
+ function pickParityItems(items, limit = 3) {
731
+ const checkable = []
732
+ const seenText = new Set()
733
+ for (const item of items) {
734
+ if (tokens(item.text).length === 0) continue
735
+ if (seenText.has(item.text)) continue
736
+ seenText.add(item.text)
737
+ checkable.push(item)
738
+ }
739
+ if (checkable.length <= limit) return checkable
740
+ const indexes = [0, Math.floor((checkable.length - 1) / 2), checkable.length - 1]
741
+ return [...new Set(indexes)].slice(0, limit).map((index) => checkable[index])
742
+ }
743
+
744
+ /**
745
+ * 校验一个 workspace:条数/集合、全量文本往返、随机抽样、向量维度与错宽拒绝、向量自召回、
746
+ * 两库同一查询的 top-k 自取回(主判定)、JSON 字节未被改动。只读;返回的 ok 是全部检查的合取。
747
+ *
748
+ * 检索一致性的主判定是「每个确定性查询在 JSON 与 TriviumDB 的 top-k 里都能取回查询文本」;
749
+ * Jaccard 重合率只作诊断写进报告,不参与 ok。随机抽样只影响报告里列举哪几条,不影响判定。
750
+ */
751
+ async function verifyScope({ plan, facade, embedder, options, random }) {
752
+ const checks = []
753
+ const add = (name, ok, detail) => {
754
+ checks.push({ name, ok: ok === true, detail })
755
+ return ok === true
756
+ }
757
+ const expected = plan.migratable
758
+ const expectedIds = new Set(expected.map((item) => item.id))
759
+ const topK = Math.max(1, Number.isInteger(options.topK) && options.topK > 0 ? options.topK : DEFAULT_TOP_K)
760
+ const sampleSize = Math.max(0, Number.isInteger(options.sampleSize) && options.sampleSize >= 0 ? options.sampleSize : DEFAULT_SAMPLE_SIZE)
761
+ const threshold = Number.isFinite(options.overlapThreshold) ? options.overlapThreshold : DEFAULT_OVERLAP_THRESHOLD
762
+ const parityItems = pickParityItems(expected)
763
+
764
+ let openInfo = null
765
+ try {
766
+ openInfo = await facade.open()
767
+ } catch (error) {
768
+ return {
769
+ ok: false,
770
+ threshold,
771
+ open: null,
772
+ counts: { rows: 0, expected: expected.length, missing: expected.length, extra: 0 },
773
+ sample: { size: 0, results: [] },
774
+ parity: { topK, metric: 'jaccard', baseline: threshold, gating: false, ownHits: 0, required: 0, meanRatio: 0, rows: [] },
775
+ vectorProbe: { rejected: false, dbCode: null },
776
+ checks: [{ name: 'vector-dim', ok: false, detail: `open 失败:${error?.code ?? 'error'} ${error?.message ?? String(error)}` }],
777
+ }
778
+ }
779
+ add('vector-dim', openInfo?.dim === EMBEDDING_DIM,
780
+ `open().dim=${openInfo?.dim},期望 ${EMBEDDING_DIM}`)
781
+
782
+ const rows = await readWorkspaceRows(facade, plan.scope)
783
+ const byId = new Map()
784
+ for (const row of rows) {
785
+ const legacyId = row.payload?.legacy_id
786
+ if (typeof legacyId === 'string' && !byId.has(legacyId)) byId.set(legacyId, row)
787
+ }
788
+ const rowIds = new Set(byId.keys())
789
+ const missing = [...expectedIds].filter((id) => !rowIds.has(id))
790
+ const extra = [...rowIds].filter((id) => !expectedIds.has(id))
791
+ add('entry-count', rows.length === expected.length, `库内节点 ${rows.length} / 可迁移条目 ${expected.length}`)
792
+ add('entry-set', missing.length === 0 && extra.length === 0,
793
+ `缺失 ${missing.length} 条、多出 ${extra.length} 条${missing.length + extra.length === 0 ? '' : `(missing=${JSON.stringify(missing.slice(0, 5))}, extra=${JSON.stringify(extra.slice(0, 5))})`}`)
794
+
795
+ // 边:与写入同一份纯规划(planEdges)对比,重跑不会多边、少边。
796
+ const planned = planEdges(expected)
797
+ const tally = tallyEdges(planned.links)
798
+ const edgesRead = await facade.edges(null, { limit: 1 })
799
+ const graph = edgesRead?.graph ?? { edgeCount: 0, labels: {} }
800
+ const dbLabels = graph?.labels ?? {}
801
+ add('graph-edges', graph.edgeCount === tally.total && (tally.total === 0 || graph.edgeCount > 0),
802
+ `库内边 ${graph.edgeCount} / 规划 ${tally.total}(边>0:${graph.edgeCount > 0};会话锚点 ${planned.anchors.length})`)
803
+ const labelRows = Object.entries(tally.labels).map(([label, count]) => ({ label, expected: count, actual: dbLabels[label] ?? 0 }))
804
+ const labelBad = labelRows.filter((row) => row.actual !== row.expected)
805
+ add('graph-labels', tally.total === 0 ? true : labelBad.length === 0,
806
+ tally.total === 0 ? '没有可写的边' : `每个标签的边数 ${JSON.stringify(labelRows)}${labelBad.length === 0 ? '' : `;不一致 ${JSON.stringify(labelBad)}`}`)
807
+
808
+ // 显式种子:`recall-trivium` 用 `FIND {id: …}` 查 payload 顶层字段,迁移必须镜像一个 `id`。
809
+ const seedIds = expected.slice(0, 5).map((item) => item.id)
810
+ let seedRows = []
811
+ if (seedIds.length > 0) {
812
+ const literals = seedIds.map((id) => JSON.stringify(String(id))).join(', ')
813
+ const result = await facade.tql(`FIND {id: {$in: [${literals}]}} RETURN _.id AS nodeId`)
814
+ seedRows = Array.isArray(result?.rows) ? result.rows : []
815
+ }
816
+ const foundNodeIds = new Set(seedRows.map((row) => Number(row?.nodeId)).filter((id) => Number.isSafeInteger(id)))
817
+ const seedMissing = seedIds.filter((id) => {
818
+ const nodeId = byId.get(id)?.id
819
+ return nodeId === undefined || !foundNodeIds.has(nodeId)
820
+ })
821
+ add('payload-id-lookup', seedMissing.length === 0,
822
+ seedIds.length === 0
823
+ ? '无可查条目'
824
+ : `显式种子 ${seedIds.length - seedMissing.length}/${seedIds.length} 条用 FIND {id:…} 解析到正确节点${seedMissing.length === 0 ? '' : `(未命中 ${JSON.stringify(seedMissing)})`}`)
825
+
826
+ const fullMismatch = []
827
+ for (const item of expected) {
828
+ const stored = byId.get(item.id)?.payload?.envelope
829
+ if (stored === undefined) {
830
+ fullMismatch.push({ id: item.id, reason: 'missing-envelope' })
831
+ continue
832
+ }
833
+ try {
834
+ validateEnvelope(stored)
835
+ } catch (error) {
836
+ fullMismatch.push({ id: item.id, reason: `envelope:${error?.code ?? 'invalid'}` })
837
+ continue
838
+ }
839
+ if (stored.text !== item.envelope.text) fullMismatch.push({ id: item.id, reason: 'text' })
840
+ else if (stored.turn !== item.envelope.turn) fullMismatch.push({ id: item.id, reason: 'turn' })
841
+ else if (stored?.session?.id !== item.envelope.session.id) fullMismatch.push({ id: item.id, reason: 'session' })
842
+ }
843
+ add('text-roundtrip-full', fullMismatch.length === 0,
844
+ fullMismatch.length === 0 ? `${expected.length}/${expected.length} 条文本/turn/session 一致` : `不一致 ${fullMismatch.length} 条:${JSON.stringify(fullMismatch.slice(0, 5))}`)
845
+
846
+ const sample = pickSample(expected, sampleSize, random)
847
+ const sampleResults = sample.map((item) => {
848
+ const stored = byId.get(item.id)?.payload?.envelope
849
+ return {
850
+ id: item.id,
851
+ text: stored?.text === item.envelope.text,
852
+ turn: stored?.turn === item.envelope.turn,
853
+ session: stored?.session?.id === item.envelope.session.id,
854
+ }
855
+ })
856
+ const sampleOk = sampleResults.every((row) => row.text && row.turn && row.session)
857
+ add('sample-roundtrip', sampleOk,
858
+ `抽样 ${sample.length} 条${sampleOk ? '全部一致' : `,不一致:${JSON.stringify(sampleResults.filter((row) => !(row.text && row.turn && row.session)))}`}`)
859
+
860
+ let widthProbe = { rejected: false, dbCode: null }
861
+ try {
862
+ await facade.search({ vector: new Array(EMBEDDING_DIM + 1).fill(0), topK: 1 })
863
+ } catch (error) {
864
+ widthProbe = {
865
+ rejected: error?.dbCode === 'KANABO_TRIVIUM_VECTOR' || String(error?.message ?? '').includes('KANABO_TRIVIUM_VECTOR'),
866
+ dbCode: error?.dbCode ?? null,
867
+ message: error?.message ?? String(error),
868
+ }
869
+ }
870
+ add('vector-width-probe', widthProbe.rejected,
871
+ widthProbe.rejected
872
+ ? `维度 ${EMBEDDING_DIM + 1} 的查询被拒(${widthProbe.dbCode ?? 'KANABO_TRIVIUM_VECTOR'})`
873
+ : `维度 ${EMBEDDING_DIM + 1} 的查询没有被拒:${widthProbe.message ?? '无错误'}`)
874
+
875
+ const vectorResults = []
876
+ if (parityItems.length > 0) {
877
+ const embedded = await embedder.embedBatch(parityItems.map((item) => item.text), { prefix: QUERY_PREFIX })
878
+ for (let i = 0; i < parityItems.length; i += 1) {
879
+ const item = parityItems[i]
880
+ const result = embedded[i]
881
+ if (result === undefined || result.vector === null || result.degraded === true) {
882
+ vectorResults.push({ id: item.id, ok: false, reason: result?.reason ?? 'no-vector' })
883
+ continue
884
+ }
885
+ const hits = (await facade.search({
886
+ vector: Array.from(result.vector),
887
+ topK,
888
+ payloadFilter: { kind: MIGRATION_KIND, workspace: plan.scope },
889
+ }))?.hits ?? []
890
+ // 按**节点 id** 比对,而不是文本相等:非 CONVERSATION 信封(片段/音轨)根本没有 `text` 字段。
891
+ const nodeId = byId.get(item.id)?.id
892
+ const rank = hits.findIndex((hit) => Number(hit?.id) === nodeId)
893
+ vectorResults.push({ id: item.id, ok: rank >= 0, rank, hits: hits.length })
894
+ }
895
+ }
896
+ add('vector-recall', vectorResults.every((row) => row.ok === true),
897
+ vectorResults.length === 0 ? '无可查条目' : JSON.stringify(vectorResults))
898
+
899
+ const searchable = expected.map((item) => ({ id: item.id, text: item.text, topic: item.entry?.topic ?? '', ts: item.entry?.ts ?? 0 }))
900
+ const parityRows = []
901
+ for (const item of parityItems) {
902
+ const query = clip(String(item.text).replace(/\s+/gu, ' ').trim(), 512)
903
+ const jsonIds = searchEntries(searchable, query, topK).map((entry) => entry.id)
904
+ const textRows = rowsOf(await facade.tql(`TEXT BM25 ${tqlString(query)} TOP ${topK} RETURN * LIMIT ${topK}`))
905
+ const dbIds = textRows
906
+ .map((row) => row.payload?.legacy_id)
907
+ .filter((id) => typeof id === 'string' && expectedIds.has(id))
908
+ .slice(0, topK)
909
+ const jsonRank = jsonIds.indexOf(item.id)
910
+ const dbRank = dbIds.indexOf(item.id)
911
+ const overlap = jsonIds.filter((id) => dbIds.includes(id)).length
912
+ const union = new Set([...jsonIds, ...dbIds]).size
913
+ parityRows.push({
914
+ id: item.id,
915
+ query: clip(query, 80),
916
+ jsonTop: jsonIds,
917
+ dbTop: dbIds,
918
+ ownInJson: jsonRank >= 0,
919
+ ownInDb: dbRank >= 0,
920
+ rankJson: jsonRank,
921
+ rankDb: dbRank,
922
+ overlapTopK: overlap,
923
+ jaccard: union === 0 ? 1 : overlap / union,
924
+ })
925
+ }
926
+ const ownHits = parityRows.filter((row) => row.ownInJson && row.ownInDb).length
927
+ const meanJaccard = parityRows.length === 0
928
+ ? 1
929
+ : parityRows.reduce((sum, row) => sum + row.jaccard, 0) / parityRows.length
930
+ const parityOk = parityRows.every((row) => row.ownInJson && row.ownInDb)
931
+ add('retrieval-parity-text', parityOk,
932
+ parityRows.length === 0
933
+ ? '没有带词元的查询(检索一致性无信号)'
934
+ : `own-text 命中 ${ownHits}/${parityRows.length}(要求全部:两库 top-${topK} 都要能取回查询文本);`
935
+ + `诊断:Jaccard 均值 ${meanJaccard.toFixed(2)}(基线 ${threshold},**不参与判定**)。明细 ${JSON.stringify(parityRows)}`)
936
+
937
+ let afterSha = plan.fileSha256
938
+ try {
939
+ afterSha = sha256(readFileSync(plan.file))
940
+ } catch (error) {
941
+ afterSha = `unreadable:${error?.code ?? 'error'}`
942
+ }
943
+ add('json-untouched', afterSha === plan.fileSha256,
944
+ afterSha === plan.fileSha256 ? `sha256 未变(${plan.fileSha256.slice(0, 12)}…)` : `sha256 变化:${plan.fileSha256.slice(0, 12)}… → ${String(afterSha).slice(0, 12)}…`)
945
+
946
+ return {
947
+ ok: checks.every((check) => check.ok),
948
+ threshold,
949
+ open: { dim: openInfo?.dim ?? null, path: openInfo?.path ?? null, nodeCount: openInfo?.nodeCount ?? null, loadTextIndex: openInfo?.loadTextIndex ?? null },
950
+ counts: { rows: rows.length, expected: expected.length, missing: missing.length, extra: extra.length },
951
+ sample: { size: sample.length, results: sampleResults },
952
+ parity: {
953
+ topK,
954
+ metric: 'jaccard',
955
+ baseline: threshold,
956
+ gating: false,
957
+ ownHits,
958
+ required: parityRows.length,
959
+ meanRatio: meanJaccard,
960
+ rows: parityRows,
961
+ },
962
+ vectorProbe: widthProbe,
963
+ checks,
964
+ }
965
+ }
966
+
967
+ function renderMarkdown(report) {
968
+ const lines = []
969
+ lines.push(`# 记忆迁移报告:${report.command}`)
970
+ lines.push('')
971
+ lines.push(`- 状态:**${report.status}**`)
972
+ lines.push(`- 开始:${report.startedAt};用时:${report.elapsedMs}ms`)
973
+ lines.push(`- storeDir:\`${report.options.storeDir}\``)
974
+ lines.push(`- triviumDir:\`${report.options.triviumDir}\``)
975
+ lines.push(`- 双写:${report.state?.dualWrite === true ? 'ON' : 'OFF'};权威读者:${report.state?.authoritative ?? 'json'}`)
976
+ lines.push('')
977
+ lines.push('## 前后对比')
978
+ lines.push('')
979
+ lines.push('| 指标 | 值 |')
980
+ lines.push('| --- | --- |')
981
+ lines.push(`| 迁移前条目(全部) | ${report.before.totalEntries} |`)
982
+ lines.push(`| 其中可迁移 | ${report.before.migratable} |`)
983
+ lines.push(`| 跳过(自家注入) | ${report.before.skippedInjection} |`)
984
+ lines.push(`| 迁移后本工作区节点 | ${report.after.rows} |`)
985
+ lines.push(`| 新增写入 | ${report.after.inserted} |`)
986
+ lines.push(`| 复用(已一致) | ${report.after.reused} |`)
987
+ lines.push(`| 向量维度 | ${report.vector.expectedDim}(open().dim=${report.vector.openedDim}) |`)
988
+ lines.push('')
989
+ lines.push('## 逐工作区')
990
+ for (const ws of report.workspaces) {
991
+ lines.push('')
992
+ lines.push(`### \`${ws.scope}\``)
993
+ lines.push('')
994
+ lines.push(`- 文件:\`${ws.file}\`(sha256 ${String(ws.fileSha256).slice(0, 12)}…)`)
995
+ lines.push(`- 条目:${ws.entries}(可迁移 ${ws.migratable},跳过 ${ws.skipped.length})`)
996
+ lines.push(`- 库:\`${ws.db.path}\`(存在=${ws.db.exists}${ws.db.exists ? `,${ws.db.sizeBytes} 字节` : ''})`)
997
+ if (ws.inserted !== undefined) lines.push(`- 新增 ${ws.inserted},复用 ${ws.reused}${ws.conflicts?.length ? `,冲突 ${ws.conflicts.length}` : ''}`)
998
+ if (ws.edges !== undefined) {
999
+ lines.push(`- 边:写入 ${ws.edges.written}(新建 ${ws.edges.created},会话锚点 ${ws.edges.anchors},跳过 ${ws.edges.skipped.length})`)
1000
+ }
1001
+ if (ws.windowIndex !== undefined && ws.windowIndex !== null) {
1002
+ lines.push(`- 时间窗索引:\`${ws.windowIndex}\`(ordered)`)
1003
+ }
1004
+ if (ws.verification !== undefined) {
1005
+ lines.push('')
1006
+ lines.push('| 校验项 | 结果 | 明细 |')
1007
+ lines.push('| --- | --- | --- |')
1008
+ for (const check of ws.verification.checks) {
1009
+ lines.push(`| ${check.name} | ${check.ok ? 'PASS' : 'FAIL'} | ${String(check.detail).replace(/\|/g, '\\|')} |`)
1010
+ }
1011
+ }
1012
+ if (ws.problems.length > 0) {
1013
+ lines.push('')
1014
+ lines.push('问题:')
1015
+ for (const problem of ws.problems) lines.push(`- \`${problem.id ?? `#${problem.index}`}\` ${problem.code}: ${problem.message}`)
1016
+ }
1017
+ }
1018
+ if (report.skipped.length > 0) {
1019
+ lines.push('')
1020
+ lines.push('## 跳过的自家注入')
1021
+ lines.push('')
1022
+ lines.push('检测规则:文本里有独占一行的 `Recalled from this workspace\'s memory (shared across sessions):`'
1023
+ + ' 且结尾为 `(N entries)` 才判为插件召回块(`recall.js` 的 HEADER 与 footer);只命中 HEADER 的条目不跳过,记为 suspect。')
1024
+ lines.push('')
1025
+ lines.push('| workspace | 条目 id | 原因 | 标记 |')
1026
+ lines.push('| --- | --- | --- | --- |')
1027
+ for (const row of report.skipped) lines.push(`| ${row.scope} | ${row.id ?? '(无 id)'} | ${row.reason} | ${row.marker ?? ''} |`)
1028
+ }
1029
+ if (report.problems.length > 0) {
1030
+ lines.push('')
1031
+ lines.push('## 问题(迁移被拒)')
1032
+ lines.push('')
1033
+ for (const problem of report.problems) {
1034
+ lines.push(`- [${problem.code}] ${problem.scope ? `${problem.scope}: ` : ''}${problem.id ?? problem.file ?? `#${problem.index}`} — ${problem.message}`)
1035
+ }
1036
+ }
1037
+ lines.push('')
1038
+ lines.push('## 回滚')
1039
+ lines.push('')
1040
+ lines.push('```sh')
1041
+ lines.push('node packages/dsh-kanabo-memory/migrate.js rollback --store-dir <storeDir>')
1042
+ lines.push('```')
1043
+ lines.push('回滚只把状态改成 `dualWrite=false`、`authoritative=json`,并保留 TriviumDB 文件供检查。')
1044
+ lines.push('')
1045
+ return `${lines.join('\n')}\n`
1046
+ }
1047
+
1048
+ function renderSummary(report) {
1049
+ const lines = []
1050
+ lines.push(`${report.command}: ${report.status} (${report.elapsedMs}ms)`)
1051
+ lines.push(` before: entries=${report.before.totalEntries} migratable=${report.before.migratable} skipped=${report.before.skippedInjection}`)
1052
+ lines.push(` after: rows=${report.after.rows} inserted=${report.after.inserted} reused=${report.after.reused}`)
1053
+ const edges = report.after.edges ?? null
1054
+ if (edges !== null) lines.push(` edges: written=${edges.written} created=${edges.created} anchors=${edges.anchors} skipped=${edges.skipped}`)
1055
+ lines.push(` vector: expected=${report.vector.expectedDim} opened=${report.vector.openedDim}`)
1056
+ for (const ws of report.workspaces) {
1057
+ if (ws.verification !== undefined) {
1058
+ lines.push(` verify[${ws.scope}]: ${ws.verification.ok ? 'PASS' : 'FAIL'} (${ws.verification.checks.filter((c) => c.ok).length}/${ws.verification.checks.length})`)
1059
+ for (const check of ws.verification.checks) {
1060
+ if (!check.ok) lines.push(` FAIL ${check.name}: ${check.detail}`)
1061
+ }
1062
+ }
1063
+ }
1064
+ for (const problem of report.problems) {
1065
+ lines.push(` problem[${problem.code}] ${problem.scope ? `${problem.scope}: ` : ''}${problem.id ?? problem.file ?? `#${problem.index}`} — ${problem.message}`)
1066
+ }
1067
+ lines.push(` state: dualWrite=${report.state.dualWrite} authoritative=${report.state.authoritative}`)
1068
+ lines.push(` report: ${report.report.jsonPath}`)
1069
+ return `${lines.join('\n')}\n`
1070
+ }
1071
+
1072
+ function reportPaths(options, command) {
1073
+ const base = resolve(options.reportBase ?? join(migrationPaths(options).reportDir, command))
1074
+ return { jsonPath: `${base}.json`, mdPath: `${base}.md` }
1075
+ }
1076
+
1077
+ function writeReports(report, options) {
1078
+ if (report.report === null) report.report = reportPaths(options, report.command)
1079
+ writeAtomicFile(report.report.jsonPath, `${JSON.stringify(report, null, 2)}\n`)
1080
+ writeAtomicFile(report.report.mdPath, renderMarkdown(report))
1081
+ return report.report
1082
+ }
1083
+
1084
+ function scopeReportBase(plan) {
1085
+ return {
1086
+ scope: plan.scope,
1087
+ file: plan.file,
1088
+ fileSha256: plan.fileSha256,
1089
+ entries: plan.entriesCount,
1090
+ migratable: plan.migratable.length,
1091
+ skipped: plan.skipped,
1092
+ suspects: plan.suspects,
1093
+ problems: plan.problems,
1094
+ }
1095
+ }
1096
+
1097
+ /** 只算路径、不 open:文件级租约不允许顺手开一个「看看有没有」的句柄。 */
1098
+ function dbInfo(options, scope) {
1099
+ const path = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM, idleMs: 1 }).path
1100
+ const exists = existsSync(path)
1101
+ return { path, exists, sizeBytes: exists ? statSync(path).size : 0 }
1102
+ }
1103
+
1104
+ function readMigrationStateSafe(options) {
1105
+ try {
1106
+ return readMigrationState(options)
1107
+ } catch (error) {
1108
+ return { version: MIGRATION_STATE_VERSION, dualWrite: false, authoritative: 'json', migration: null, updatedAt: 0, readError: error?.code ?? 'error' }
1109
+ }
1110
+ }
1111
+
1112
+ function baseReport(command, options, startedAt) {
1113
+ return {
1114
+ task: 'dsh-kanabo-memory/migrate',
1115
+ migrationVersion: MIGRATION_STATE_VERSION,
1116
+ command,
1117
+ status: 'FAIL',
1118
+ startedAt: iso(startedAt),
1119
+ elapsedMs: 0,
1120
+ options: {
1121
+ storeDir: migrationPaths(options).dir,
1122
+ triviumDir: resolve(options.triviumDir ?? process.env.KANABO_TRIVIUM_DIR ?? join(storeDir(), 'trivium')),
1123
+ sampleSize: options.sampleSize ?? DEFAULT_SAMPLE_SIZE,
1124
+ topK: options.topK ?? DEFAULT_TOP_K,
1125
+ overlapThreshold: options.overlapThreshold ?? DEFAULT_OVERLAP_THRESHOLD,
1126
+ scopes: options.scopes ?? null,
1127
+ allScopes: options.allScopes === true,
1128
+ seed: null,
1129
+ },
1130
+ before: { totalEntries: 0, migratable: 0, skippedInjection: 0, suspects: 0 },
1131
+ after: { totalNodes: 0, rows: 0, inserted: 0, reused: 0, edges: { written: 0, created: 0, anchors: 0, skipped: 0 } },
1132
+ workspaces: [],
1133
+ skipped: [],
1134
+ problems: [],
1135
+ vector: { expectedDim: EMBEDDING_DIM, openedDim: null, providerId: null, wrongWidthRejected: null },
1136
+ verification: { ok: false, checks: [] },
1137
+ state: readMigrationStateSafe(options),
1138
+ report: null,
1139
+ }
1140
+ }
1141
+
1142
+ function collectPreflightProblems(scopes, discoveryProblems, options) {
1143
+ const plans = []
1144
+ const problems = [...discoveryProblems]
1145
+ for (const scope of scopes) {
1146
+ try {
1147
+ plans.push(planScope(scope, options))
1148
+ } catch (error) {
1149
+ problems.push({
1150
+ scope,
1151
+ code: typeof error?.code === 'string' ? error.code : 'KANABO_MIGRATE_PLAN',
1152
+ message: error?.message ?? String(error),
1153
+ })
1154
+ }
1155
+ }
1156
+ for (const plan of plans) {
1157
+ for (const problem of plan.problems) problems.push({ scope: plan.scope, ...problem })
1158
+ }
1159
+ return { plans, problems }
1160
+ }
1161
+
1162
+ function describePlans(report, plans, problems) {
1163
+ report.workspaces = plans.map((plan) => ({ ...scopeReportBase(plan), db: dbInfo(report.options, plan.scope) }))
1164
+ report.problems = problems
1165
+ report.skipped = plans.flatMap((plan) => plan.skipped.map((row) => ({ scope: plan.scope, ...row })))
1166
+ report.before = {
1167
+ totalEntries: plans.reduce((sum, plan) => sum + plan.entriesCount, 0),
1168
+ migratable: plans.reduce((sum, plan) => sum + plan.migratable.length, 0),
1169
+ skippedInjection: report.skipped.length,
1170
+ suspects: plans.reduce((sum, plan) => sum + plan.suspects.length, 0),
1171
+ }
1172
+ }
1173
+
1174
+ async function embedPassages(embedder, plans) {
1175
+ const items = plans.flatMap((plan) => plan.migratable.map((item) => ({ scope: plan.scope, item })))
1176
+ if (items.length === 0) return { vectors: new Map(), degraded: [] }
1177
+ const results = await embedder.embedBatch(items.map(({ item }) => item.text), { prefix: PASSAGE_PREFIX })
1178
+ const vectors = new Map()
1179
+ const degraded = []
1180
+ results.forEach((result, index) => {
1181
+ const { scope, item } = items[index]
1182
+ if (result === undefined || result.vector === null || result.degraded === true) {
1183
+ degraded.push({ scope, id: item.id, reason: result?.reason ?? 'provider_error' })
1184
+ return
1185
+ }
1186
+ vectors.set(`${scope}\u0000${item.id}`, result.vector)
1187
+ })
1188
+ return { vectors, degraded }
1189
+ }
1190
+
1191
+ async function writeScope({ plan, facade, vectors }) {
1192
+ const openInfo = await facade.open()
1193
+ if (openInfo?.dim !== EMBEDDING_DIM) {
1194
+ throw migrateError('KANABO_MIGRATE_DIM',
1195
+ `库以 ${openInfo?.dim} 维打开,契约维度是 ${EMBEDDING_DIM};拒绝写入错宽的向量。`,
1196
+ { details: { scope: plan.scope, openedDim: openInfo?.dim } })
1197
+ }
1198
+ const rows = await readWorkspaceRows(facade, plan.scope)
1199
+ // 时间窗的 `t0` 区间条件靠有序索引;建索引是写入路径的事,且幂等(重跑安全)。
1200
+ const windowIndex = await facade.createOrderedIndex('t0')
1201
+ const byId = new Map(rows.map((row) => [row.payload?.legacy_id, row]))
1202
+ const inserts = []
1203
+ const reused = []
1204
+ const conflicts = []
1205
+ for (const item of plan.migratable) {
1206
+ const row = byId.get(item.id)
1207
+ if (row === undefined) {
1208
+ inserts.push(item)
1209
+ continue
1210
+ }
1211
+ if (sameEnvelopeText(row.payload?.envelope, item.envelope)) {
1212
+ reused.push(item.id)
1213
+ } else {
1214
+ conflicts.push({
1215
+ id: item.id,
1216
+ reason: 'TriviumDB 里已有同 legacy_id 但内容不同的节点;门面没有删除/更新原语,拒绝覆盖。',
1217
+ })
1218
+ }
1219
+ }
1220
+ let inserted = 0
1221
+ const nodeIdByKey = new Map()
1222
+ for (const [legacyId, row] of byId) nodeIdByKey.set(legacyId, row.id)
1223
+ for (let start = 0; start < inserts.length; start += MAX_INSERT_BATCH) {
1224
+ const chunk = inserts.slice(start, start + MAX_INSERT_BATCH)
1225
+ const result = await facade.batch(chunk.map((item) => ({
1226
+ vector: Array.from(vectors.get(`${plan.scope}\u0000${item.id}`)),
1227
+ payload: payloadFor(plan.scope, item),
1228
+ // 索引写 topic + 正文;payload.text 仍是正文(预算与注入用正文)。
1229
+ text: item.indexText ?? item.text,
1230
+ })))
1231
+ inserted += Number(result?.count ?? chunk.length)
1232
+ const ids = Array.isArray(result?.ids) ? result.ids : []
1233
+ chunk.forEach((item, offset) => {
1234
+ if (ids[offset] !== undefined) nodeIdByKey.set(item.id, Number(ids[offset]))
1235
+ })
1236
+ }
1237
+ const edges = await writeEdgesForEntries(
1238
+ facade,
1239
+ plan.scope,
1240
+ plan.migratable.map((item) => ({ id: item.id, nodeId: nodeIdByKey.get(item.id), envelope: item.envelope })),
1241
+ )
1242
+ return {
1243
+ openedDim: openInfo.dim,
1244
+ inserted,
1245
+ reused: reused.length,
1246
+ conflicts,
1247
+ rowsBefore: rows.length,
1248
+ windowIndex: windowIndex?.field ?? null,
1249
+ edges,
1250
+ }
1251
+ }
1252
+
1253
+ async function verifyPlans({ plans, options, embedder, random }) {
1254
+ const results = []
1255
+ for (const plan of plans) {
1256
+ const verification = await withFacade(options, plan.scope, async (facade) =>
1257
+ await verifyScope({ plan, facade, embedder, options, random }))
1258
+ results.push({ scope: plan.scope, verification })
1259
+ }
1260
+ return results
1261
+ }
1262
+
1263
+ function mergeVerification(report, verifications) {
1264
+ report.verification = { ok: true, checks: [] }
1265
+ for (const { scope, verification } of verifications) {
1266
+ const entry = report.workspaces.find((ws) => ws.scope === scope)
1267
+ if (entry !== undefined) entry.verification = verification
1268
+ report.verification.checks.push(...verification.checks.map((check) => ({ ...check, name: `${scope}:${check.name}` })))
1269
+ report.verification.ok = report.verification.ok && verification.ok
1270
+ report.after.rows += verification.counts.rows
1271
+ report.after.totalNodes = Math.max(report.after.totalNodes, verification.open?.nodeCount ?? 0)
1272
+ report.vector.openedDim = verification.open?.dim ?? null
1273
+ report.vector.wrongWidthRejected = verification.vectorProbe?.rejected ?? null
1274
+ }
1275
+ }
1276
+
1277
+ function migrationRecord(ok, plans, options, report) {
1278
+ return {
1279
+ status: ok ? 'verified' : 'failed',
1280
+ at: Date.now(),
1281
+ dim: EMBEDDING_DIM,
1282
+ triviumDir: report.options.triviumDir,
1283
+ scopes: plans.map((plan) => ({
1284
+ scope: plan.scope,
1285
+ file: plan.file,
1286
+ fileSha256: plan.fileSha256,
1287
+ entries: plan.entriesCount,
1288
+ migratable: plan.migratable.length,
1289
+ skipped: plan.skipped.length,
1290
+ db: dbInfo(report.options, plan.scope).path,
1291
+ })),
1292
+ sampleSize: report.options.sampleSize,
1293
+ topK: report.options.topK,
1294
+ threshold: report.options.overlapThreshold,
1295
+ parityGating: 'own-text-in-both-topk (all queries; jaccard diagnostic only)',
1296
+ report: report.report,
1297
+ }
1298
+ }
1299
+
1300
+ function saveState(record, report, options) {
1301
+ try {
1302
+ report.state = writeMigrationState({ migration: record }, options)
1303
+ } catch (error) {
1304
+ report.stateWriteError = error?.code ?? 'error'
1305
+ }
1306
+ }
1307
+
1308
+ /** 迁移入口;无论成败都写 JSON + Markdown 报告。本函数不写 JSON 记忆文档(双写是 writeDualEntry 的事)。 */
1309
+ export async function migrate(options = {}) {
1310
+ const startedAt = Date.now()
1311
+ const report = baseReport('migrate', options, startedAt)
1312
+ const { seedText, seed } = seedOf(options)
1313
+ report.options.seed = seedText
1314
+ const random = mulberry32(seed)
1315
+ const { embedder, owned: ownsEmbedder } = resolveEmbedder(options)
1316
+
1317
+ try {
1318
+ const { scopes, problems: discoveryProblems } = resolveScopes(options)
1319
+ assertFacadeScope(options, scopes)
1320
+ report.options.scopes = scopes
1321
+ if (scopes.length === 0) discoveryProblems.push({ code: 'KANABO_MIGRATE_NO_SCOPES', message: '没有发现任何记忆文档。' })
1322
+ const { plans, problems } = collectPreflightProblems(scopes, discoveryProblems, options)
1323
+ describePlans(report, plans, problems)
1324
+
1325
+ if (problems.length > 0) {
1326
+ report.elapsedMs = Date.now() - startedAt
1327
+ report.verification = { ok: false, checks: [{ name: 'preflight', ok: false, detail: `${problems.length} 个预检问题;未写入数据库,JSON 未改动。` }] }
1328
+ report.report = reportPaths(options, report.command)
1329
+ saveState(migrationRecord(false, plans, options, report), report, options)
1330
+ writeReports(report, options)
1331
+ return { ok: false, exitCode: 2, report }
1332
+ }
1333
+
1334
+ const embedded = await embedPassages(embedder, plans)
1335
+ if (embedded.degraded.length > 0) {
1336
+ report.problems = embedded.degraded.map((row) => ({
1337
+ scope: row.scope,
1338
+ id: row.id,
1339
+ code: 'KANABO_MIGRATE_EMBED_UNAVAILABLE',
1340
+ message: `嵌入不可用(${row.reason});迁移要求每条都有向量,否则向量召回会静默残缺。JSON 未改动。`,
1341
+ }))
1342
+ report.elapsedMs = Date.now() - startedAt
1343
+ report.verification = { ok: false, checks: [{ name: 'embed', ok: false, detail: `${report.problems.length} 条未能嵌入(${[...new Set(embedded.degraded.map((row) => row.reason))].join(', ')})。` }] }
1344
+ report.report = reportPaths(options, report.command)
1345
+ saveState(migrationRecord(false, plans, options, report), report, options)
1346
+ writeReports(report, options)
1347
+ return { ok: false, exitCode: 2, report }
1348
+ }
1349
+ report.vector.providerId = typeof embedder.providerId === 'string' ? embedder.providerId : null
1350
+
1351
+ for (const plan of plans) {
1352
+ const writeResult = await withFacade(options, plan.scope, async (facade) =>
1353
+ await writeScope({ plan, facade, vectors: embedded.vectors }))
1354
+ const entry = report.workspaces.find((ws) => ws.scope === plan.scope)
1355
+ if (entry !== undefined) {
1356
+ entry.inserted = writeResult.inserted
1357
+ entry.reused = writeResult.reused
1358
+ entry.conflicts = writeResult.conflicts
1359
+ entry.edges = writeResult.edges
1360
+ entry.windowIndex = writeResult.windowIndex
1361
+ entry.db = { ...entry.db, openDim: writeResult.openedDim, ...dbInfo(report.options, plan.scope) }
1362
+ }
1363
+ report.after.inserted += writeResult.inserted
1364
+ report.after.reused += writeResult.reused
1365
+ report.after.edges.written += writeResult.edges.written
1366
+ report.after.edges.created += writeResult.edges.created
1367
+ report.after.edges.anchors += writeResult.edges.anchors
1368
+ report.after.edges.skipped += writeResult.edges.skipped.length
1369
+ for (const conflict of writeResult.conflicts) {
1370
+ report.problems.push({ scope: plan.scope, id: conflict.id, code: 'KANABO_MIGRATE_DB_CONFLICT', message: conflict.reason })
1371
+ }
1372
+ }
1373
+
1374
+ const verifications = await verifyPlans({ plans, options, embedder, random })
1375
+ mergeVerification(report, verifications)
1376
+
1377
+ const ok = report.verification.ok && report.problems.length === 0
1378
+ report.status = ok ? 'PASS' : 'FAIL'
1379
+ report.elapsedMs = Date.now() - startedAt
1380
+ report.report = reportPaths(options, report.command)
1381
+ saveState(migrationRecord(ok, plans, options, report), report, options)
1382
+ writeReports(report, options)
1383
+ return { ok, exitCode: ok ? 0 : 2, report }
1384
+ } finally {
1385
+ if (ownsEmbedder) embedder.close?.()
1386
+ }
1387
+ }
1388
+
1389
+ export async function verifyMigration(options = {}) {
1390
+ const startedAt = Date.now()
1391
+ const report = baseReport('verify', options, startedAt)
1392
+ const { seedText, seed } = seedOf(options)
1393
+ report.options.seed = seedText
1394
+ const random = mulberry32(seed)
1395
+ const { embedder, owned: ownsEmbedder } = resolveEmbedder(options)
1396
+ try {
1397
+ const { scopes, problems: discoveryProblems } = resolveScopes(options)
1398
+ assertFacadeScope(options, scopes)
1399
+ report.options.scopes = scopes
1400
+ if (scopes.length === 0) discoveryProblems.push({ code: 'KANABO_MIGRATE_NO_SCOPES', message: '没有发现任何记忆文档。' })
1401
+ const { plans, problems } = collectPreflightProblems(scopes, discoveryProblems, options)
1402
+ describePlans(report, plans, problems)
1403
+ report.vector.providerId = typeof embedder.providerId === 'string' ? embedder.providerId : null
1404
+ report.report = reportPaths(options, report.command)
1405
+ if (problems.length > 0) {
1406
+ report.verification = { ok: false, checks: [{ name: 'preflight', ok: false, detail: `${problems.length} 个预检问题;未校验数据库。` }] }
1407
+ report.status = 'FAIL'
1408
+ report.elapsedMs = Date.now() - startedAt
1409
+ writeReports(report, options)
1410
+ return { ok: false, exitCode: 2, report }
1411
+ }
1412
+ const verifications = await verifyPlans({ plans, options, embedder, random })
1413
+ mergeVerification(report, verifications)
1414
+ const ok = report.verification.ok
1415
+ report.status = ok ? 'PASS' : 'FAIL'
1416
+ report.elapsedMs = Date.now() - startedAt
1417
+ writeReports(report, options)
1418
+ return { ok, exitCode: ok ? 0 : 2, report }
1419
+ } finally {
1420
+ if (ownsEmbedder) embedder.close?.()
1421
+ }
1422
+ }
1423
+
1424
+ /**
1425
+ * 回滚到「JSON 是权威读者 + 双写关闭」的原行为,并保留 TriviumDB 文件供检查。
1426
+ * 只改状态文件;JSON 与库都不动。
1427
+ */
1428
+ export async function rollback(options = {}) {
1429
+ const startedAt = Date.now()
1430
+ const report = baseReport('rollback', options, startedAt)
1431
+ const before = readMigrationStateSafe(options)
1432
+ const after = writeMigrationState({
1433
+ dualWrite: false,
1434
+ authoritative: 'json',
1435
+ rollbackAt: Date.now(),
1436
+ dualWriteBefore: before.dualWrite,
1437
+ authorityBefore: before.authoritative,
1438
+ }, options)
1439
+ report.state = after
1440
+ const scopes = Array.isArray(before.migration?.scopes)
1441
+ ? before.migration.scopes.map((row) => row.scope).filter((scope) => typeof scope === 'string')
1442
+ : (Array.isArray(options.scopes) ? options.scopes : [])
1443
+ for (const scope of [...new Set(scopes)]) {
1444
+ let entries = null
1445
+ let file = storeDocumentPath(options, scope)
1446
+ try {
1447
+ const read = readDocument(options, scope, { missingOk: true })
1448
+ entries = read.doc.entries.length
1449
+ file = read.file
1450
+ } catch {
1451
+ entries = null
1452
+ }
1453
+ report.workspaces.push({
1454
+ scope,
1455
+ file,
1456
+ entries,
1457
+ db: dbInfo(report.options, scope),
1458
+ skipped: [],
1459
+ suspects: [],
1460
+ problems: [],
1461
+ })
1462
+ }
1463
+ report.status = 'PASS'
1464
+ report.verification = {
1465
+ ok: true,
1466
+ checks: [{
1467
+ name: 'rollback-state',
1468
+ ok: after.dualWrite === false && after.authoritative === 'json',
1469
+ detail: `dualWrite ${before.dualWrite} → ${after.dualWrite};authoritative ${before.authoritative} → ${after.authoritative};TriviumDB 文件保留。`,
1470
+ }],
1471
+ }
1472
+ report.elapsedMs = Date.now() - startedAt
1473
+ report.report = reportPaths(options, report.command)
1474
+ writeReports(report, options)
1475
+ return { ok: true, exitCode: 0, report }
1476
+ }
1477
+
1478
+ /**
1479
+ * 双写入口(todo 16 接线):新写入先落 JSON(切换前 JSON 是权威读者),状态为 ON 时再落 TriviumDB。
1480
+ * 插件必须传共享的 `options.trivium`(已打开的门面)与 `options.embedder`,否则每次写入都会自己
1481
+ * 拉起子进程/加载模型。OFF 时只写 JSON(与迁移前行为一致)。ON 时落库失败会抛带
1482
+ * `jsonWritten: true` 的错误:JSON 已经成功,两边分叉,调用方不得当成「什么都没写」。
1483
+ */
1484
+ export async function writeDualEntry(entry, options = {}) {
1485
+ const state = readMigrationState(options)
1486
+ const scope = typeof entry?.scope === 'string' && entry.scope.length > 0
1487
+ ? entry.scope
1488
+ : (typeof options.scope === 'string' && options.scope.length > 0 ? options.scope : DEFAULT_SCOPE)
1489
+ const { doc, file } = readDocument(options, scope, { missingOk: true })
1490
+ const next = addEntry(doc, { ...entry, scope })
1491
+ const written = next.entries.at(-1)
1492
+ writeAtomicFile(file, JSON.stringify(next))
1493
+ const result = {
1494
+ id: written?.id ?? null,
1495
+ scope,
1496
+ json: 'written',
1497
+ dualWrite: state.dualWrite === true,
1498
+ trivium: state.dualWrite === true ? 'pending' : 'skipped-off',
1499
+ }
1500
+ if (state.dualWrite !== true) return result
1501
+
1502
+ const { embedder, owned: ownsEmbedder } = resolveEmbedder(options)
1503
+ let ownedFacade = null
1504
+ try {
1505
+ let facade = options.trivium ?? null
1506
+ if (facade === null) {
1507
+ facade = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM })
1508
+ ownedFacade = facade
1509
+ }
1510
+ const envelope = fromLegacyEntry(written)
1511
+ const embedded = await embedder.embed(envelope.text, { prefix: PASSAGE_PREFIX })
1512
+ if (embedded === undefined || embedded.vector === null || embedded.degraded === true) {
1513
+ throw migrateError('KANABO_MIGRATE_EMBED_UNAVAILABLE',
1514
+ `双写落库需要向量,但嵌入不可用(${embedded?.reason ?? 'no-vector'})。`,
1515
+ { reason: embedded?.reason ?? 'no-vector', jsonWritten: true, entryId: written?.id ?? null })
1516
+ }
1517
+ const inserted = await facade.insert({
1518
+ vector: Array.from(embedded.vector),
1519
+ payload: payloadFor(scope, { envelope, textSha256: digestOfEntry(envelopeTextOf(envelope)) }),
1520
+ text: indexTextFor(written?.topic ?? envelope.topic ?? envelope.scene_description, envelopeTextOf(envelope)),
1521
+ })
1522
+ // 双写也建边:只写节点的话,新记忆在图上永远是孤岛,图臂依旧 "no_edges"。
1523
+ const edges = await writeEdgesForEntries(
1524
+ facade,
1525
+ scope,
1526
+ [{ id: envelope.id, nodeId: Number(inserted?.id), envelope }],
1527
+ { resolveExternal: true },
1528
+ )
1529
+ result.trivium = 'written'
1530
+ result.triviumId = inserted?.id ?? null
1531
+ result.edges = { written: edges.written, created: edges.created, anchors: edges.anchors, skipped: edges.skipped.length }
1532
+ return result
1533
+ } catch (error) {
1534
+ if (error?.jsonWritten !== true) error.jsonWritten = true
1535
+ if (error?.entryId === undefined) error.entryId = written?.id ?? null
1536
+ throw error
1537
+ } finally {
1538
+ if (ownedFacade !== null) await ownedFacade.close()
1539
+ if (ownsEmbedder) embedder.close?.()
1540
+ }
1541
+ }
1542
+
1543
+ const USAGE = `用法:node packages/dsh-kanabo-memory/migrate.js <command> [flags]
1544
+
1545
+ 命令:
1546
+ migrate --scope <workspace>... | --all-scopes 迁移 + 校验(JSON 只读)
1547
+ verify --scope <workspace>... | --all-scopes 只校验
1548
+ rollback 回到 JSON 权威 + 关闭双写(保留库文件)
1549
+ dual-write on|off 新写入是否同时落库
1550
+ authority json|trivium 读写权威(todo 16 的切换点)
1551
+ state 打印迁移状态
1552
+
1553
+ flags:
1554
+ --store-dir <dir> JSON 文档目录(默认 KANABO_MEMORY_DIR 或 <tmp>/dsh-kanabo-memory)
1555
+ --trivium-dir <dir> TriviumDB 目录(默认 KANABO_TRIVIUM_DIR 或 <store-dir>/trivium)
1556
+ --report <base> 报告基名(默认 <store-dir>/migration/<command>)
1557
+ --sample <N> 抽样条数(默认 ${DEFAULT_SAMPLE_SIZE})
1558
+ --top-k <K> 检索重合的 top-k(默认 ${DEFAULT_TOP_K})
1559
+ --threshold <R> Jaccard 诊断基线(默认 ${DEFAULT_OVERLAP_THRESHOLD};**不参与判定**)
1560
+ --seed <S> 抽样种子(默认固定 ${DEFAULT_SEED};只影响样本列举,不影响判定)
1561
+ --json 把报告 JSON 打到 stdout
1562
+ `
1563
+
1564
+ function usageError(message) {
1565
+ const error = migrateError('KANABO_MIGRATE_USAGE', message)
1566
+ error.exitCode = 3
1567
+ return error
1568
+ }
1569
+
1570
+ function parseArgs(argv) {
1571
+ const parsed = { command: argv[0] ?? 'help', scopes: [], allScopes: false, json: false }
1572
+ const rest = argv.slice(1)
1573
+ for (let index = 0; index < rest.length; index += 1) {
1574
+ const arg = rest[index]
1575
+ if (!arg.startsWith('--')) {
1576
+ if (parsed.value === undefined) {
1577
+ parsed.value = arg
1578
+ continue
1579
+ }
1580
+ throw usageError(`多余的参数:${arg}`)
1581
+ }
1582
+ const take = () => {
1583
+ const value = rest[++index]
1584
+ if (value === undefined || value.startsWith('--')) throw usageError(`${arg} 缺少值`)
1585
+ return value
1586
+ }
1587
+ switch (arg) {
1588
+ case '--scope':
1589
+ parsed.scopes.push(take())
1590
+ break
1591
+ case '--all-scopes':
1592
+ parsed.allScopes = true
1593
+ break
1594
+ case '--store-dir':
1595
+ parsed.storeDir = take()
1596
+ break
1597
+ case '--trivium-dir':
1598
+ parsed.triviumDir = take()
1599
+ break
1600
+ case '--report':
1601
+ parsed.reportBase = take()
1602
+ break
1603
+ case '--sample': {
1604
+ const value = Number(take())
1605
+ if (!Number.isInteger(value) || value < 0) throw usageError('--sample 需要 ≥0 的整数')
1606
+ parsed.sampleSize = value
1607
+ break
1608
+ }
1609
+ case '--top-k': {
1610
+ const value = Number(take())
1611
+ if (!Number.isInteger(value) || value <= 0) throw usageError('--top-k 需要 >0 的整数')
1612
+ parsed.topK = value
1613
+ break
1614
+ }
1615
+ case '--threshold': {
1616
+ const value = Number(take())
1617
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw usageError('--threshold 需要 0..1 的小数')
1618
+ parsed.overlapThreshold = value
1619
+ break
1620
+ }
1621
+ case '--seed':
1622
+ parsed.seed = take()
1623
+ break
1624
+ case '--json':
1625
+ parsed.json = true
1626
+ break
1627
+ case '--help':
1628
+ parsed.help = true
1629
+ break
1630
+ default:
1631
+ throw usageError(`未知参数:${arg}`)
1632
+ }
1633
+ }
1634
+ return parsed
1635
+ }
1636
+
1637
+ function isEntryPoint() {
1638
+ const script = process.argv[1]
1639
+ if (typeof script !== 'string' || script.length === 0) return false
1640
+ try {
1641
+ return realpathSync(script) === realpathSync(fileURLToPath(import.meta.url))
1642
+ } catch {
1643
+ return false
1644
+ }
1645
+ }
1646
+
1647
+ async function main(argv) {
1648
+ let parsed
1649
+ try {
1650
+ parsed = parseArgs(argv)
1651
+ } catch (error) {
1652
+ process.stderr.write(`${error.message}\n\n${USAGE}`)
1653
+ return error.exitCode ?? 3
1654
+ }
1655
+ if (parsed.help || parsed.command === 'help') {
1656
+ process.stdout.write(USAGE)
1657
+ return 0
1658
+ }
1659
+ const options = {
1660
+ scopes: parsed.scopes,
1661
+ allScopes: parsed.allScopes,
1662
+ storeDir: parsed.storeDir,
1663
+ triviumDir: parsed.triviumDir,
1664
+ reportBase: parsed.reportBase,
1665
+ sampleSize: parsed.sampleSize,
1666
+ topK: parsed.topK,
1667
+ overlapThreshold: parsed.overlapThreshold,
1668
+ seed: parsed.seed,
1669
+ }
1670
+ try {
1671
+ if (parsed.command === 'migrate') {
1672
+ const outcome = await migrate(options)
1673
+ process.stdout.write(renderSummary(outcome.report))
1674
+ if (parsed.json) process.stdout.write(`${JSON.stringify(outcome.report, null, 2)}\n`)
1675
+ return outcome.exitCode
1676
+ }
1677
+ if (parsed.command === 'verify') {
1678
+ const outcome = await verifyMigration(options)
1679
+ process.stdout.write(renderSummary(outcome.report))
1680
+ if (parsed.json) process.stdout.write(`${JSON.stringify(outcome.report, null, 2)}\n`)
1681
+ return outcome.exitCode
1682
+ }
1683
+ if (parsed.command === 'rollback') {
1684
+ const outcome = await rollback(options)
1685
+ process.stdout.write(renderSummary(outcome.report))
1686
+ if (parsed.json) process.stdout.write(`${JSON.stringify(outcome.report, null, 2)}\n`)
1687
+ return outcome.exitCode
1688
+ }
1689
+ if (parsed.command === 'dual-write') {
1690
+ if (parsed.value !== 'on' && parsed.value !== 'off') throw usageError('dual-write 需要 on 或 off')
1691
+ const next = setDualWrite(parsed.value === 'on', options)
1692
+ process.stdout.write(`${JSON.stringify({ command: 'dual-write', dualWrite: next.dualWrite, authoritative: next.authoritative, stateFile: migrationPaths(options).stateFile }, null, 2)}\n`)
1693
+ return 0
1694
+ }
1695
+ if (parsed.command === 'authority') {
1696
+ const next = setAuthority(parsed.value, options)
1697
+ process.stdout.write(`${JSON.stringify({ command: 'authority', dualWrite: next.dualWrite, authoritative: next.authoritative }, null, 2)}\n`)
1698
+ return 0
1699
+ }
1700
+ if (parsed.command === 'state') {
1701
+ process.stdout.write(`${JSON.stringify(readMigrationState(options), null, 2)}\n`)
1702
+ return 0
1703
+ }
1704
+ throw usageError(`未知命令:${parsed.command}`)
1705
+ } catch (error) {
1706
+ if (error?.code === 'KANABO_MIGRATE_USAGE' || error?.exitCode === 3) {
1707
+ process.stderr.write(`${error.message}\n\n${USAGE}`)
1708
+ return 3
1709
+ }
1710
+ process.stderr.write(`migrate: ${error?.code ?? 'ERROR'}: ${error?.message ?? String(error)}\n`)
1711
+ return 1
1712
+ }
1713
+ }
1714
+
1715
+ if (isEntryPoint()) {
1716
+ main(process.argv.slice(2)).then((code) => {
1717
+ process.exitCode = code
1718
+ }, (error) => {
1719
+ process.stderr.write(`migrate: ${error?.stack ?? String(error)}\n`)
1720
+ process.exitCode = 1
1721
+ })
1722
+ }