dsh-config-sync-plugin 0.3.68 → 0.3.70
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/README.en.md +17 -180
- package/README.md +19 -171
- package/client.js +58 -31
- package/index.js +9 -9
- package/package.json +1 -1
- package/runtime/apply.ps1 +37 -6
- package/runtime/capture.ps1 +20 -1
- package/runtime/dsh-sync-common.ps1 +153 -1
- package/runtime/post-exit.ps1 +2 -0
- package/runtime/tools/bili-state.mjs +501 -0
- package/tools/bili-state.mjs +501 -0
- package/tools/selftest.mjs +67 -0
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// billion-context 压缩状态跨机同步工具。
|
|
3
|
+
//
|
|
4
|
+
// 背景:billion-context(下称 bili)把每个会话的压缩状态(blocks/refs/摘要)存在自己的
|
|
5
|
+
// SQLite 库 index.db 里,DSH 的会话日志里没有。跨机同步只搬 sessions 日志时,接收端
|
|
6
|
+
// bili 会认为这是一份没有任何压缩记录的新会话 —— 它算不出可压区间(max compressible
|
|
7
|
+
// 不足阈值),于是整段 surface 直发 provider,报 CONTEXT_WINDOW_EXCEEDED。
|
|
8
|
+
//
|
|
9
|
+
// 这个工具按会话导出/导入「压缩状态」,不含消息正文(正文由 bili 自己从 DSH 会话日志
|
|
10
|
+
// 重新 ingest,没必要搬)。导出格式与 bili 自带 `sessions archive` 的 archive.jsonl
|
|
11
|
+
// 行结构兼容,便于互相迁移。
|
|
12
|
+
//
|
|
13
|
+
// 用法:
|
|
14
|
+
// node bili-state.mjs probe
|
|
15
|
+
// node bili-state.mjs export <sessionId> <outFile> [--all-blocks]
|
|
16
|
+
// node bili-state.mjs import <inFile> [--dry-run]
|
|
17
|
+
// node bili-state.mjs info <inFile>
|
|
18
|
+
//
|
|
19
|
+
// 退出码:0 成功;1 失败;2 用法/IO。
|
|
20
|
+
|
|
21
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
|
23
|
+
import path from 'node:path'
|
|
24
|
+
import os from 'node:os'
|
|
25
|
+
|
|
26
|
+
const FORMAT = 1
|
|
27
|
+
|
|
28
|
+
function biliSessionsDir() {
|
|
29
|
+
const cfg = process.env.BILI_CONFIG_FILE
|
|
30
|
+
if (cfg) {
|
|
31
|
+
const dir = path.dirname(path.resolve(cfg))
|
|
32
|
+
const cand = path.join(dir, 'sessions')
|
|
33
|
+
if (existsSync(path.join(cand, 'index.db'))) return cand
|
|
34
|
+
}
|
|
35
|
+
const explicit = process.env.BILI_DATA_DIR || process.env.BILLION_CONTEXT_DATA_DIR
|
|
36
|
+
if (explicit) {
|
|
37
|
+
// 显式指定即视为权威:允许指到数据根(…\billion-context)或直接指到 sessions 目录。
|
|
38
|
+
// 找不到 index.db 就返回 null(= 这台机器没有 bili 数据),不再回头去猜用户主目录——
|
|
39
|
+
// 隔离测试/无插件机器都靠这条语义,否则会误抓真实库。
|
|
40
|
+
const direct = path.resolve(explicit)
|
|
41
|
+
if (existsSync(path.join(direct, 'index.db'))) return direct
|
|
42
|
+
const cand = path.join(direct, 'sessions')
|
|
43
|
+
if (existsSync(path.join(cand, 'index.db'))) return cand
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
const home = process.env.USERPROFILE || process.env.HOME || os.homedir()
|
|
47
|
+
const candidates = [
|
|
48
|
+
path.join(home, '.local', 'share', 'billion-context', 'sessions'),
|
|
49
|
+
path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'billion-context', 'sessions'),
|
|
50
|
+
path.join(process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'billion-context', 'sessions'),
|
|
51
|
+
]
|
|
52
|
+
for (const c of candidates) if (existsSync(path.join(c, 'index.db'))) return c
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function openDb(dir, readOnly) {
|
|
57
|
+
const file = path.join(dir, 'index.db')
|
|
58
|
+
if (!existsSync(file)) throw new Error(`index.db 不存在:${file}`)
|
|
59
|
+
return new DatabaseSync(file, { readOnly: !!readOnly })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function tableColumns(db, table) {
|
|
63
|
+
return db.prepare(`PRAGMA table_info(${table})`).all()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 按目标表的实际列生成插入/更新用的列清单:丢掉导出文件里不存在的列,
|
|
67
|
+
// 也丢掉「值为 null 但目标列 NOT NULL」的列(否则会直接约束失败;
|
|
68
|
+
// 丢掉后该列落 DEFAULT)。bili 的表大量使用 NOT NULL DEFAULT '{}',
|
|
69
|
+
// 少一列就会炸,这是必须的保底处理。
|
|
70
|
+
function pickColumns(info, row, only) {
|
|
71
|
+
const notNull = new Set(info.filter((c) => c.notnull === 1).map((c) => c.name))
|
|
72
|
+
const allowed = only ? new Set(only) : null
|
|
73
|
+
return info
|
|
74
|
+
.map((c) => c.name)
|
|
75
|
+
.filter((n) => row[n] !== undefined && !(row[n] === null && notNull.has(n)))
|
|
76
|
+
.filter((n) => !allowed || allowed.has(n))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function insertRow(db, table, info, row) {
|
|
80
|
+
const use = pickColumns(info, row)
|
|
81
|
+
if (!use.length) return false
|
|
82
|
+
db.prepare(`INSERT INTO ${table} (${use.join(', ')}) VALUES (${use.map(() => '?').join(', ')})`)
|
|
83
|
+
.run(...use.map((c) => row[c]))
|
|
84
|
+
return true
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function log(msg) {
|
|
88
|
+
process.stdout.write(msg + '\n')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function cmdProbe() {
|
|
92
|
+
const dir = biliSessionsDir()
|
|
93
|
+
if (!dir) {
|
|
94
|
+
log('没有找到 billion-context 的 sessions 目录(本机没装 bili,或换了数据目录)')
|
|
95
|
+
return 1
|
|
96
|
+
}
|
|
97
|
+
const db = openDb(dir, true)
|
|
98
|
+
const cols = tableColumns(db, 'sessions')
|
|
99
|
+
const n = db.prepare('SELECT COUNT(*) AS c FROM sessions').get().c
|
|
100
|
+
log(`bili sessions dir: ${dir}`)
|
|
101
|
+
log(`sessions 行数: ${n};schema 列数: ${cols.length}`)
|
|
102
|
+
const sample = db.prepare('SELECT session_id, status, last_ingested_seq, next_block_id FROM sessions LIMIT 3').all()
|
|
103
|
+
for (const s of sample) log(` ${s.session_id} status=${s.status} ingested=${s.last_ingested_seq} nextBlock=${s.next_block_id}`)
|
|
104
|
+
db.close()
|
|
105
|
+
return 0
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function cmdExport(sessionId, outFile, allBlocks, full) {
|
|
109
|
+
const dir = biliSessionsDir()
|
|
110
|
+
if (!dir) {
|
|
111
|
+
log('没有找到 billion-context 的 sessions 目录')
|
|
112
|
+
return 1
|
|
113
|
+
}
|
|
114
|
+
const db = openDb(dir, true)
|
|
115
|
+
try {
|
|
116
|
+
const sessCols = tableColumns(db, 'sessions').map((c) => c.name)
|
|
117
|
+
const row = db.prepare('SELECT * FROM sessions WHERE session_id = ?').get(sessionId)
|
|
118
|
+
if (!row) {
|
|
119
|
+
log(`bili 库里没有会话 ${sessionId}(这台机器没在这个会话上跑过 bili 压缩)`)
|
|
120
|
+
return 1
|
|
121
|
+
}
|
|
122
|
+
// metadata_json 是 bili 自己的查询缓存(cacheLedger / publicSnapshot / foldCoverage 等),
|
|
123
|
+
// 接收端会自己重建;它占 2.4 MB 左右,默认不发,--full 才带上。
|
|
124
|
+
// 注意必须 delete 键而不是置 null:这一列是 NOT NULL DEFAULT '{}',写 null 会直接约束失败,
|
|
125
|
+
// 而删掉键就能落到 DEFAULT 上。
|
|
126
|
+
if (!full && row.metadata_json !== undefined) {
|
|
127
|
+
delete row.metadata_json
|
|
128
|
+
}
|
|
129
|
+
const blocks = allBlocks
|
|
130
|
+
? db.prepare('SELECT * FROM blocks WHERE session_id = ? ORDER BY ord').all(sessionId)
|
|
131
|
+
: db.prepare('SELECT * FROM blocks WHERE session_id = ? AND active = 1 ORDER BY ord').all(sessionId)
|
|
132
|
+
const refs = db.prepare('SELECT * FROM refs WHERE session_id = ? ORDER BY ord').all(sessionId)
|
|
133
|
+
const deadRefs = db.prepare('SELECT * FROM dead_refs WHERE session_id = ? ORDER BY ord').all(sessionId)
|
|
134
|
+
const ccr = db.prepare('SELECT * FROM ccr_entries WHERE session_id = ? ORDER BY ord').all(sessionId)
|
|
135
|
+
const ext = db.prepare('SELECT * FROM session_ext WHERE session_id = ?').all(sessionId)
|
|
136
|
+
const checkpoints = db.prepare('SELECT * FROM checkpoints WHERE session_id = ?').all(sessionId)
|
|
137
|
+
|
|
138
|
+
// 只搬「压缩状态」需要的内容:block 的摘要(summary_hash / one_hash)。
|
|
139
|
+
// 消息正文(messages 的 content_hash)不搬 —— 接收端 bili 会从 DSH 会话日志重新 ingest。
|
|
140
|
+
// checkpoint 的 state_hash 是「fork 基线快照」,单个就能到 20 MB 以上,而且压缩判定用不到它,
|
|
141
|
+
// 所以默认不发(只发 checkpoint 行本身,import 时会因为缺 content 而跳过该行);
|
|
142
|
+
// --full 才把 checkpoint 快照一起带上(用于跨机接续 fork)。
|
|
143
|
+
const wanted = new Set()
|
|
144
|
+
for (const b of blocks) {
|
|
145
|
+
if (b.summary_hash) wanted.add(b.summary_hash)
|
|
146
|
+
if (b.one_hash) wanted.add(b.one_hash)
|
|
147
|
+
}
|
|
148
|
+
if (full) {
|
|
149
|
+
for (const c of checkpoints) if (c.state_hash) wanted.add(c.state_hash)
|
|
150
|
+
}
|
|
151
|
+
for (const e of ccr) if (e.content_hash) wanted.add(e.content_hash)
|
|
152
|
+
|
|
153
|
+
const content = {}
|
|
154
|
+
let contentBytes = 0
|
|
155
|
+
const getContent = db.prepare('SELECT bytes, byte_len FROM content WHERE hash = ?')
|
|
156
|
+
for (const hash of wanted) {
|
|
157
|
+
const c = getContent.get(hash)
|
|
158
|
+
if (!c) continue
|
|
159
|
+
const text = Buffer.from(c.bytes).toString('utf8')
|
|
160
|
+
content[hash] = text
|
|
161
|
+
contentBytes += Buffer.byteLength(text, 'utf8')
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const dump = {
|
|
165
|
+
format: FORMAT,
|
|
166
|
+
kind: 'billion-context-compaction-state',
|
|
167
|
+
sessionId,
|
|
168
|
+
exportedAt: Date.now(),
|
|
169
|
+
schemaUserVersion: db.prepare('PRAGMA user_version').get().user_version,
|
|
170
|
+
sessionColumns: sessCols,
|
|
171
|
+
session: row,
|
|
172
|
+
blocks,
|
|
173
|
+
refs,
|
|
174
|
+
deadRefs,
|
|
175
|
+
ccrEntries: ccr,
|
|
176
|
+
sessionExt: ext,
|
|
177
|
+
checkpoints,
|
|
178
|
+
content,
|
|
179
|
+
// 显式声明:没有 messages / mediaMaps,接收端不要指望能从这里恢复消息正文
|
|
180
|
+
omitted: ['messages', 'message_media'],
|
|
181
|
+
}
|
|
182
|
+
const text = JSON.stringify(dump)
|
|
183
|
+
mkdirSync(path.dirname(path.resolve(outFile)), { recursive: true })
|
|
184
|
+
writeFileSync(outFile, text, 'utf8')
|
|
185
|
+
const bytes = Buffer.byteLength(text, 'utf8')
|
|
186
|
+
log(`导出 ${sessionId}`)
|
|
187
|
+
log(` blocks: ${blocks.length}${allBlocks ? '(全部,含已被取代的)' : '(仅 active)'}`)
|
|
188
|
+
log(` refs: ${refs.length} checkpoints: ${checkpoints.length} content 条: ${Object.keys(content).length}(${(contentBytes / 1048576).toFixed(2)} MB)`)
|
|
189
|
+
log(` 落盘: ${outFile} 共 ${(bytes / 1048576).toFixed(2)} MB`)
|
|
190
|
+
return 0
|
|
191
|
+
} finally {
|
|
192
|
+
db.close()
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function cmdInfo(inFile) {
|
|
197
|
+
const dump = JSON.parse(readFileSync(inFile, 'utf8'))
|
|
198
|
+
log(`文件: ${inFile}(${(statSync(inFile).size / 1048576).toFixed(2)} MB)`)
|
|
199
|
+
log(` 会话: ${dump.sessionId}`)
|
|
200
|
+
log(` schema: format=${dump.format} userVersion=${dump.schemaUserVersion}`)
|
|
201
|
+
log(` blocks=${(dump.blocks || []).length} refs=${(dump.refs || []).length} checkpoints=${(dump.checkpoints || []).length} content=${Object.keys(dump.content || {}).length}`)
|
|
202
|
+
const s = dump.session || {}
|
|
203
|
+
log(` status=${s.status} last_ingested_seq=${s.last_ingested_seq} next_block_id=${s.next_block_id}`)
|
|
204
|
+
log(` omitted=${(dump.omitted || []).join(',') || '(无)'}`)
|
|
205
|
+
return 0
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function cmdImport(inFile, dryRun) {
|
|
209
|
+
const dump = JSON.parse(readFileSync(inFile, 'utf8'))
|
|
210
|
+
if (dump.format !== FORMAT || dump.kind !== 'billion-context-compaction-state') {
|
|
211
|
+
log(`不认识的文件格式(format=${dump.format} kind=${dump.kind})`)
|
|
212
|
+
return 2
|
|
213
|
+
}
|
|
214
|
+
const sessionId = dump.sessionId
|
|
215
|
+
const dir = biliSessionsDir()
|
|
216
|
+
if (!dir) {
|
|
217
|
+
log('没有找到 billion-context 的 sessions 目录(本机没装 bili),无法导入压缩状态')
|
|
218
|
+
return 1
|
|
219
|
+
}
|
|
220
|
+
const db = openDb(dir, false)
|
|
221
|
+
let insSession = 0
|
|
222
|
+
let insBlock = 0
|
|
223
|
+
let skipBlock = 0
|
|
224
|
+
let insRef = 0
|
|
225
|
+
let skipRef = 0
|
|
226
|
+
let insContent = 0
|
|
227
|
+
let skipContent = 0
|
|
228
|
+
let insCp = 0
|
|
229
|
+
try {
|
|
230
|
+
const localVersion = db.prepare('PRAGMA user_version').get().user_version
|
|
231
|
+
if (dump.schemaUserVersion && localVersion !== dump.schemaUserVersion) {
|
|
232
|
+
log(`提示:导出端 schema user_version=${dump.schemaUserVersion},本机=${localVersion};按列名逐列写入,缺列会跳过。`)
|
|
233
|
+
}
|
|
234
|
+
db.exec('BEGIN')
|
|
235
|
+
try {
|
|
236
|
+
// 1) content:只补缺的
|
|
237
|
+
const hasContent = db.prepare('SELECT 1 AS x FROM content WHERE hash = ?')
|
|
238
|
+
const insC = db.prepare("INSERT INTO content (hash, byte_len, refcount, algo, bytes) VALUES (?, ?, 1, 'sha256', ?)")
|
|
239
|
+
for (const [hash, text] of Object.entries(dump.content || {})) {
|
|
240
|
+
if (hasContent.get(hash)) { skipContent++; continue }
|
|
241
|
+
const buf = Buffer.from(text, 'utf8')
|
|
242
|
+
insC.run(hash, buf.length, buf)
|
|
243
|
+
insContent++
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// 2) sessions 行:存在就只补压缩相关列,不存在就整行插入
|
|
247
|
+
const sess = dump.session || {}
|
|
248
|
+
const sinfo = tableColumns(db, 'sessions')
|
|
249
|
+
const cols = sinfo.map((c) => c.name)
|
|
250
|
+
const exists = db.prepare('SELECT 1 AS x FROM sessions WHERE session_id = ?').get(sessionId)
|
|
251
|
+
const carry = ['status', 'last_ingested_seq', 'next_block_id', 'next_run_id', 'kstate_json', 'tail_json', 'ccr_json', 'stats_json', 'meta_json', 'metadata_json', 'orphans_json', 'protocol', 'label', 'title', 'host_title', 'origin', 'updated_at']
|
|
252
|
+
if (exists) {
|
|
253
|
+
const use = pickColumns(sinfo, sess, carry.filter((c) => cols.includes(c)))
|
|
254
|
+
if (use.length) {
|
|
255
|
+
db.prepare(`UPDATE sessions SET ${use.map((c) => `${c} = ?`).join(', ')} WHERE session_id = ?`)
|
|
256
|
+
.run(...use.map((c) => sess[c]), sessionId)
|
|
257
|
+
insSession = 1
|
|
258
|
+
}
|
|
259
|
+
} else {
|
|
260
|
+
const use = pickColumns(sinfo, sess)
|
|
261
|
+
db.prepare(`INSERT INTO sessions (${use.join(', ')}) VALUES (${use.map(() => '?').join(', ')})`)
|
|
262
|
+
.run(...use.map((c) => sess[c]))
|
|
263
|
+
insSession = 1
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// 3) blocks:同 block_id 已存在就不动(本机可能已经自己压过更靠后的版本)
|
|
267
|
+
const hasBlock = db.prepare('SELECT 1 AS x FROM blocks WHERE session_id = ? AND block_id = ?')
|
|
268
|
+
const binfo = tableColumns(db, 'blocks')
|
|
269
|
+
for (const b of dump.blocks || []) {
|
|
270
|
+
if (hasBlock.get(sessionId, b.block_id)) { skipBlock++; continue }
|
|
271
|
+
if (insertRow(db, 'blocks', binfo, b)) insBlock++
|
|
272
|
+
else skipBlock++
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 4) refs:raw_id 与 ord 都可能是唯一键,冲突就跳
|
|
276
|
+
const hasRefOrd = db.prepare('SELECT 1 AS x FROM refs WHERE session_id = ? AND ord = ?')
|
|
277
|
+
const hasRefRaw = db.prepare('SELECT 1 AS x FROM refs WHERE session_id = ? AND raw_id = ?')
|
|
278
|
+
const rinfo = tableColumns(db, 'refs')
|
|
279
|
+
for (const r of dump.refs || []) {
|
|
280
|
+
if (hasRefOrd.get(sessionId, r.ord) || hasRefRaw.get(sessionId, r.raw_id)) { skipRef++; continue }
|
|
281
|
+
if (insertRow(db, 'refs', rinfo, r)) insRef++
|
|
282
|
+
else skipRef++
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// 5) checkpoints / dead_refs / ccr_entries / session_ext:都是小表,冲突就跳
|
|
286
|
+
let skipCpNoState = 0
|
|
287
|
+
const cinfo = tableColumns(db, 'checkpoints')
|
|
288
|
+
for (const cp of dump.checkpoints || []) {
|
|
289
|
+
if (db.prepare('SELECT 1 AS x FROM checkpoints WHERE cp_id = ?').get(cp.cp_id)) continue
|
|
290
|
+
// 默认导出不带 checkpoint 的 state_hash 快照(单个可达 20 MB+),缺 content 就跳过这行,
|
|
291
|
+
// 不然会插出一条指向不存在 state 的 checkpoint。
|
|
292
|
+
if (cp.state_hash && !db.prepare('SELECT 1 AS x FROM content WHERE hash = ?').get(cp.state_hash)) {
|
|
293
|
+
skipCpNoState++
|
|
294
|
+
continue
|
|
295
|
+
}
|
|
296
|
+
if (insertRow(db, 'checkpoints', cinfo, cp)) insCp++
|
|
297
|
+
}
|
|
298
|
+
if (skipCpNoState) log(` checkpoints 跳过 ${skipCpNoState} 个(导出时没带 state 快照,用 --full 重导可带上)`)
|
|
299
|
+
for (const [table, list] of [
|
|
300
|
+
['dead_refs', dump.deadRefs || []],
|
|
301
|
+
['ccr_entries', dump.ccrEntries || []],
|
|
302
|
+
['session_ext', dump.sessionExt || []],
|
|
303
|
+
]) {
|
|
304
|
+
if (!list.length) continue
|
|
305
|
+
const info = tableColumns(db, table)
|
|
306
|
+
for (const r of list) {
|
|
307
|
+
try { insertRow(db, table, info, r) } catch { /* 主键冲突或外键缺失:跳过 */ }
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (dryRun) db.exec('ROLLBACK')
|
|
312
|
+
else db.exec('COMMIT')
|
|
313
|
+
} catch (err) {
|
|
314
|
+
try { db.exec('ROLLBACK') } catch {}
|
|
315
|
+
throw err
|
|
316
|
+
}
|
|
317
|
+
log(`${dryRun ? '(演练,未提交)' : ''}导入 ${sessionId}`)
|
|
318
|
+
log(` sessions 行: ${insSession ? '已更新/插入' : '无变化'}`)
|
|
319
|
+
log(` blocks: 新增 ${insBlock},跳过 ${skipBlock}`)
|
|
320
|
+
log(` refs: 新增 ${insRef},跳过 ${skipRef}`)
|
|
321
|
+
log(` content: 新增 ${insContent},已存在 ${skipContent}`)
|
|
322
|
+
log(` checkpoints: 新增 ${insCp}`)
|
|
323
|
+
return 0
|
|
324
|
+
} finally {
|
|
325
|
+
db.close()
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function parseArgs(argv) {
|
|
330
|
+
const args = argv.slice(2)
|
|
331
|
+
const flags = new Set(args.filter((a) => a.startsWith('--')))
|
|
332
|
+
const pos = args.filter((a) => !a.startsWith('--'))
|
|
333
|
+
return { pos, flags }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// 批量模式:给 PowerShell 侧调用。参数全走 JSON 文件,避免 PS5.1 把中文/引号拆坏。
|
|
337
|
+
// spec = { mode:"export"|"import", repoDir, biliDir?, sessions?:[..] }
|
|
338
|
+
// export:把本机 bili 库里指定会话的压缩状态写到 repoDir/<sessionId>.json
|
|
339
|
+
// import:把 repoDir 下所有 *.json 导入本机 bili 库
|
|
340
|
+
// 结果写到 outJson,PS 侧读文件(Electron 是 GUI 子系统,抓不到 stdout)。
|
|
341
|
+
function cmdSync(specFile, outFile) {
|
|
342
|
+
const spec = JSON.parse(readFileSync(specFile, 'utf8'))
|
|
343
|
+
const mode = spec.mode
|
|
344
|
+
const result = { ok: true, mode, exported: [], imported: [], missing: [], skipped: [], failed: [], biliDir: null }
|
|
345
|
+
if (spec.biliDir) process.env.BILI_DATA_DIR = spec.biliDir
|
|
346
|
+
const dir = biliSessionsDir()
|
|
347
|
+
result.biliDir = dir
|
|
348
|
+
if (!dir) {
|
|
349
|
+
// 本机没装 bili / 没有 bili 数据:导出侧当成「这台机器没压缩记录」,导入侧当成「跳过」。
|
|
350
|
+
result.ok = true
|
|
351
|
+
result.noBili = true
|
|
352
|
+
if (mode === 'import') result.skipped.push('本机没有 billion-context 数据目录,压缩状态无处可写')
|
|
353
|
+
writeFileSync(outFile, JSON.stringify(result, null, 2), 'utf8')
|
|
354
|
+
return 0
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const repoDir = spec.repoDir
|
|
358
|
+
mkdirSync(repoDir, { recursive: true })
|
|
359
|
+
|
|
360
|
+
if (mode === 'export') {
|
|
361
|
+
const db = openDb(dir, true)
|
|
362
|
+
try {
|
|
363
|
+
const hasSess = db.prepare('SELECT 1 AS x FROM sessions WHERE session_id = ?')
|
|
364
|
+
const sessInfo = db.prepare('PRAGMA table_info(sessions)').all()
|
|
365
|
+
const blocksInfo = db.prepare('PRAGMA table_info(blocks)').all()
|
|
366
|
+
for (const sid of spec.sessions || []) {
|
|
367
|
+
if (!hasSess.get(sid)) { result.missing.push(sid); continue }
|
|
368
|
+
try {
|
|
369
|
+
const row = db.prepare('SELECT * FROM sessions WHERE session_id = ?').get(sid)
|
|
370
|
+
delete row.metadata_json
|
|
371
|
+
const blocks = db.prepare('SELECT * FROM blocks WHERE session_id = ? AND active = 1 ORDER BY ord').all(sid)
|
|
372
|
+
const refs = db.prepare('SELECT * FROM refs WHERE session_id = ? ORDER BY ord').all(sid)
|
|
373
|
+
const deadRefs = db.prepare('SELECT * FROM dead_refs WHERE session_id = ? ORDER BY ord').all(sid)
|
|
374
|
+
const ccr = db.prepare('SELECT * FROM ccr_entries WHERE session_id = ? ORDER BY ord').all(sid)
|
|
375
|
+
const ext = db.prepare('SELECT * FROM session_ext WHERE session_id = ?').all(sid)
|
|
376
|
+
const checkpoints = db.prepare('SELECT * FROM checkpoints WHERE session_id = ?').all(sid)
|
|
377
|
+
const wanted = new Set()
|
|
378
|
+
for (const b of blocks) { if (b.summary_hash) wanted.add(b.summary_hash); if (b.one_hash) wanted.add(b.one_hash) }
|
|
379
|
+
for (const e of ccr) if (e.content_hash) wanted.add(e.content_hash)
|
|
380
|
+
const content = {}
|
|
381
|
+
const getC = db.prepare('SELECT bytes FROM content WHERE hash = ?')
|
|
382
|
+
for (const h of wanted) { const c = getC.get(h); if (c) content[h] = Buffer.from(c.bytes).toString('utf8') }
|
|
383
|
+
const dump = {
|
|
384
|
+
format: FORMAT, kind: 'billion-context-compaction-state', sessionId: sid, exportedAt: Date.now(),
|
|
385
|
+
schemaUserVersion: db.prepare('PRAGMA user_version').get().user_version,
|
|
386
|
+
sessionColumns: sessInfo.map((c) => c.name), blockColumns: blocksInfo.map((c) => c.name),
|
|
387
|
+
session: row, blocks, refs, deadRefs, ccrEntries: ccr, sessionExt: ext, checkpoints, content,
|
|
388
|
+
omitted: ['messages', 'message_media', 'checkpoint.state_hash'],
|
|
389
|
+
}
|
|
390
|
+
const out = path.join(repoDir, sid + '.json')
|
|
391
|
+
writeFileSync(out, JSON.stringify(dump), 'utf8')
|
|
392
|
+
result.exported.push({ sessionId: sid, blocks: blocks.length, refs: refs.length, content: Object.keys(content).length, bytes: statSync(out).size })
|
|
393
|
+
} catch (err) {
|
|
394
|
+
result.failed.push({ sessionId: sid, error: String(err && err.message ? err.message : err) })
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
} finally { db.close() }
|
|
398
|
+
} else if (mode === 'import') {
|
|
399
|
+
const db = openDb(dir, false)
|
|
400
|
+
try {
|
|
401
|
+
const localVersion = db.prepare('PRAGMA user_version').get().user_version
|
|
402
|
+
const sinfo = db.prepare('PRAGMA table_info(sessions)').all()
|
|
403
|
+
const binfo = db.prepare('PRAGMA table_info(blocks)').all()
|
|
404
|
+
const rinfo = db.prepare('PRAGMA table_info(refs)').all()
|
|
405
|
+
const cinfo = db.prepare('PRAGMA table_info(checkpoints)').all()
|
|
406
|
+
const files = existsSync(repoDir)
|
|
407
|
+
? readdirSync(repoDir).filter((f) => f.toLowerCase().endsWith('.json'))
|
|
408
|
+
: []
|
|
409
|
+
for (const f of files) {
|
|
410
|
+
const full = path.join(repoDir, f)
|
|
411
|
+
let dump
|
|
412
|
+
try { dump = JSON.parse(readFileSync(full, 'utf8')) } catch (err) { result.failed.push({ file: f, error: 'JSON 解析失败' }); continue }
|
|
413
|
+
if (dump.format !== FORMAT || dump.kind !== 'billion-context-compaction-state') { result.skipped.push({ file: f, reason: '不是压缩状态文件' }); continue }
|
|
414
|
+
if (localVersion && dump.schemaUserVersion && localVersion !== dump.schemaUserVersion) {
|
|
415
|
+
result.schemaWarnings = result.schemaWarnings || []
|
|
416
|
+
result.schemaWarnings.push(`${f}: 导出端 user_version=${dump.schemaUserVersion},本机=${localVersion}(按列名逐列写入,缺列落 DEFAULT)`)
|
|
417
|
+
}
|
|
418
|
+
const sid = dump.sessionId
|
|
419
|
+
try {
|
|
420
|
+
db.exec('BEGIN')
|
|
421
|
+
let nc = 0
|
|
422
|
+
const hasContent = db.prepare('SELECT 1 AS x FROM content WHERE hash = ?')
|
|
423
|
+
const insC = db.prepare("INSERT INTO content (hash, byte_len, refcount, algo, bytes) VALUES (?, ?, 1, 'sha256', ?)")
|
|
424
|
+
for (const [hash, text] of Object.entries(dump.content || {})) {
|
|
425
|
+
if (hasContent.get(hash)) continue
|
|
426
|
+
const buf = Buffer.from(text, 'utf8')
|
|
427
|
+
insC.run(hash, buf.length, buf); nc++
|
|
428
|
+
}
|
|
429
|
+
const sess = dump.session || {}
|
|
430
|
+
const exists = db.prepare('SELECT 1 AS x FROM sessions WHERE session_id = ?').get(sid)
|
|
431
|
+
if (exists) {
|
|
432
|
+
const carry = ['status', 'last_ingested_seq', 'next_block_id', 'next_run_id', 'kstate_json', 'tail_json', 'ccr_json', 'stats_json', 'meta_json', 'metadata_json', 'orphans_json', 'protocol', 'label', 'title', 'host_title', 'origin', 'updated_at']
|
|
433
|
+
const use = pickColumns(sinfo, sess, carry)
|
|
434
|
+
if (use.length) db.prepare(`UPDATE sessions SET ${use.map((c) => `${c} = ?`).join(', ')} WHERE session_id = ?`).run(...use.map((c) => sess[c]), sid)
|
|
435
|
+
} else {
|
|
436
|
+
const use = pickColumns(sinfo, sess)
|
|
437
|
+
db.prepare(`INSERT INTO sessions (${use.join(', ')}) VALUES (${use.map(() => '?').join(', ')})`).run(...use.map((c) => sess[c]))
|
|
438
|
+
}
|
|
439
|
+
let nb = 0, sb = 0
|
|
440
|
+
const hasB = db.prepare('SELECT 1 AS x FROM blocks WHERE session_id = ? AND block_id = ?')
|
|
441
|
+
for (const b of dump.blocks || []) {
|
|
442
|
+
if (hasB.get(sid, b.block_id)) { sb++; continue }
|
|
443
|
+
if (insertRow(db, 'blocks', binfo, b)) nb++; else sb++
|
|
444
|
+
}
|
|
445
|
+
let nr = 0, sr = 0
|
|
446
|
+
const hasRO = db.prepare('SELECT 1 AS x FROM refs WHERE session_id = ? AND ord = ?')
|
|
447
|
+
const hasRR = db.prepare('SELECT 1 AS x FROM refs WHERE session_id = ? AND raw_id = ?')
|
|
448
|
+
for (const r of dump.refs || []) {
|
|
449
|
+
if (hasRO.get(sid, r.ord) || hasRR.get(sid, r.raw_id)) { sr++; continue }
|
|
450
|
+
if (insertRow(db, 'refs', rinfo, r)) nr++; else sr++
|
|
451
|
+
}
|
|
452
|
+
let ncp = 0
|
|
453
|
+
for (const cp of dump.checkpoints || []) {
|
|
454
|
+
if (db.prepare('SELECT 1 AS x FROM checkpoints WHERE cp_id = ?').get(cp.cp_id)) continue
|
|
455
|
+
if (cp.state_hash && !db.prepare('SELECT 1 AS x FROM content WHERE hash = ?').get(cp.state_hash)) continue
|
|
456
|
+
if (insertRow(db, 'checkpoints', cinfo, cp)) ncp++
|
|
457
|
+
}
|
|
458
|
+
for (const [table, list] of [['dead_refs', dump.deadRefs || []], ['ccr_entries', dump.ccrEntries || []], ['session_ext', dump.sessionExt || []]]) {
|
|
459
|
+
if (!list.length) continue
|
|
460
|
+
const info = tableColumns(db, table)
|
|
461
|
+
for (const r of list) { try { insertRow(db, table, info, r) } catch {} }
|
|
462
|
+
}
|
|
463
|
+
db.exec('COMMIT')
|
|
464
|
+
result.imported.push({ sessionId: sid, content: nc, blocks: nb, blocksSkipped: sb, refs: nr, refsSkipped: sr, checkpoints: ncp })
|
|
465
|
+
} catch (err) {
|
|
466
|
+
try { db.exec('ROLLBACK') } catch {}
|
|
467
|
+
result.failed.push({ file: f, sessionId: sid, error: String(err && err.message ? err.message : err) })
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
} finally { db.close() }
|
|
471
|
+
}
|
|
472
|
+
result.ok = result.failed.length === 0
|
|
473
|
+
writeFileSync(outFile, JSON.stringify(result, null, 2), 'utf8')
|
|
474
|
+
return result.ok ? 0 : 1
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const { pos, flags } = parseArgs(process.argv)
|
|
478
|
+
const cmd = pos[0]
|
|
479
|
+
let code = 2
|
|
480
|
+
try {
|
|
481
|
+
if (cmd === 'probe') code = cmdProbe()
|
|
482
|
+
else if (cmd === 'export') {
|
|
483
|
+
if (!pos[1] || !pos[2]) { log('用法: node bili-state.mjs export <sessionId> <outFile> [--all-blocks] [--full]'); code = 2 }
|
|
484
|
+
else code = cmdExport(pos[1], pos[2], flags.has('--all-blocks'), flags.has('--full'))
|
|
485
|
+
} else if (cmd === 'import') {
|
|
486
|
+
if (!pos[1]) { log('用法: node bili-state.mjs import <inFile> [--dry-run]'); code = 2 }
|
|
487
|
+
else code = cmdImport(pos[1], flags.has('--dry-run'))
|
|
488
|
+
} else if (cmd === 'info') {
|
|
489
|
+
if (!pos[1]) { log('用法: node bili-state.mjs info <inFile>'); code = 2 }
|
|
490
|
+
else code = cmdInfo(pos[1])
|
|
491
|
+
} else if (cmd === 'sync') {
|
|
492
|
+
if (!pos[1] || !pos[2]) { log('用法: node bili-state.mjs sync <specJson> <outJson>'); code = 2 }
|
|
493
|
+
else code = cmdSync(pos[1], pos[2])
|
|
494
|
+
} else {
|
|
495
|
+
log('用法: node bili-state.mjs probe | export <sessionId> <outFile> [--all-blocks] | import <inFile> [--dry-run] | info <inFile>')
|
|
496
|
+
}
|
|
497
|
+
} catch (err) {
|
|
498
|
+
log(`错误: ${err && err.message ? err.message : String(err)}`)
|
|
499
|
+
code = 1
|
|
500
|
+
}
|
|
501
|
+
process.exit(code)
|
package/tools/selftest.mjs
CHANGED
|
@@ -998,6 +998,13 @@ if (!existsSync(repoArg) || !existsSync(pluginRuntime) || !repoReady) {
|
|
|
998
998
|
const toolSame = existsSync(mirrorTool) && existsSync(sourceTool) && readFileSync(mirrorTool).equals(readFileSync(sourceTool))
|
|
999
999
|
check('执行体副本与插件 runtime 逐字节一致:tools/fix-session-cwd.mjs', toolSame,
|
|
1000
1000
|
existsSync(mirrorTool) ? '内容已漂移,跑 tools/sync-plugin-mirror.ps1 重新同步' : '配置仓库没有 tools/fix-session-cwd.mjs')
|
|
1001
|
+
for (const tname of ['session-log-guard.mjs', 'session-log-lib.mjs', 'bili-state.mjs']) {
|
|
1002
|
+
const m = join(repoArg, 'tools', tname)
|
|
1003
|
+
const s = join(pluginRuntime, 'tools', tname)
|
|
1004
|
+
const ok = existsSync(m) && existsSync(s) && readFileSync(m).equals(readFileSync(s))
|
|
1005
|
+
check(`执行体副本与插件 runtime 逐字节一致:tools/${tname}`, ok,
|
|
1006
|
+
!existsSync(m) ? `配置仓库没有 tools/${tname}` : (existsSync(s) ? '内容已漂移,跑 tools/sync-plugin-mirror.ps1 重新同步' : `插件 runtime 没有 tools/${tname}`))
|
|
1007
|
+
}
|
|
1001
1008
|
}
|
|
1002
1009
|
|
|
1003
1010
|
// 内置运行时链接修复(0.3.24):客户端升级会清空 resources\runtime,
|
|
@@ -1523,5 +1530,65 @@ console.log('== 0.3.68:会话投影缓存守卫(agent-busy 自动清缓存
|
|
|
1523
1530
|
gClear.statusCode === 400 && gClearBody.ok === false, gClear.body.slice(0, 160))
|
|
1524
1531
|
}
|
|
1525
1532
|
|
|
1533
|
+
console.log('')
|
|
1534
|
+
console.log('== billion-context 压缩状态跨机搬运 ==')
|
|
1535
|
+
{
|
|
1536
|
+
// DSH 原生 compaction 被 bili 接管后,真正的压缩记录在 bili 自己的 SQLite 里;
|
|
1537
|
+
// 只带会话日志会让另一台机器把未压缩的全量 surface 发出去并报 CONTEXT_WINDOW_EXCEEDED。
|
|
1538
|
+
const toolPath = join(pluginRootSelf, 'tools', 'bili-state.mjs')
|
|
1539
|
+
const toolRuntime = join(pluginRuntime, 'tools', 'bili-state.mjs')
|
|
1540
|
+
check('提供 tools/bili-state.mjs', existsSync(toolPath), toolPath)
|
|
1541
|
+
check('runtime/tools 下也有同一份(tgz 只打 runtime 时也在包里)',
|
|
1542
|
+
existsSync(toolRuntime) && existsSync(toolPath) && readFileSync(toolRuntime).equals(readFileSync(toolPath)))
|
|
1543
|
+
const biliSrc = existsSync(toolPath) ? readFileSync(toolPath, 'utf8') : ''
|
|
1544
|
+
check('支持 export / import / sync / probe 四个子命令',
|
|
1545
|
+
["'export'", "'import'", "'sync'", "'probe'"].every((k) => biliSrc.includes(`cmd === ${k}`)))
|
|
1546
|
+
check('导出默认不带 messages 正文(体积可控)',
|
|
1547
|
+
biliSrc.includes("omitted: ['messages'") || biliSrc.includes('omitted: [\'messages\''), 'export 的 omitted 字段')
|
|
1548
|
+
check('导出不写 metadata_json(2.4MB 级缓存,且 NOT NULL 会炸)',
|
|
1549
|
+
biliSrc.includes('delete row.metadata_json'))
|
|
1550
|
+
check('本机没有 bili 时静默跳过(noBili 而不是报错)',
|
|
1551
|
+
biliSrc.includes('noBili'))
|
|
1552
|
+
check('BILI_DATA_DIR 指到哪就用哪,不回头猜用户主目录',
|
|
1553
|
+
biliSrc.includes('显式指定即视为权威') || biliSrc.includes('return null\r\n }'))
|
|
1554
|
+
|
|
1555
|
+
const commonText2 = existsSync(join(pluginRuntime, 'dsh-sync-common.ps1')) ? readFileSync(join(pluginRuntime, 'dsh-sync-common.ps1'), 'utf8') : ''
|
|
1556
|
+
const captureText2 = existsSync(join(pluginRuntime, 'capture.ps1')) ? readFileSync(join(pluginRuntime, 'capture.ps1'), 'utf8') : ''
|
|
1557
|
+
const applyText2 = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
|
|
1558
|
+
check('common 提供 Invoke-BiliStateSync / Write-BiliStateSyncReport',
|
|
1559
|
+
/function\s+Invoke-BiliStateSync\s*\{/.test(commonText2) && /function\s+Write-BiliStateSyncReport\s*\(/.test(commonText2))
|
|
1560
|
+
check('capture 推送时导出压缩状态(否则 B 机拿不到)',
|
|
1561
|
+
/Invoke-BiliStateSync\s+-Mode\s+'export'/.test(captureText2))
|
|
1562
|
+
check('apply 拉取时导入压缩状态',
|
|
1563
|
+
/Invoke-BiliStateSync\s+-Mode\s+'import'/.test(applyText2))
|
|
1564
|
+
check('apply 只在仓库里有该目录时才导入(首次导出前为空属正常)',
|
|
1565
|
+
/Test-Path\s+-LiteralPath\s+\$biliRepo/.test(applyText2))
|
|
1566
|
+
check('压缩状态按会话导出,不是整库拷贝',
|
|
1567
|
+
captureText2.includes('$touchedSids') && captureText2.includes(`'billion_context'`))
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
console.log('')
|
|
1571
|
+
console.log('== 同步清单的两类新提示 ==')
|
|
1572
|
+
{
|
|
1573
|
+
const commonText3 = existsSync(join(pluginRuntime, 'dsh-sync-common.ps1')) ? readFileSync(join(pluginRuntime, 'dsh-sync-common.ps1'), 'utf8') : ''
|
|
1574
|
+
const applyText3 = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
|
|
1575
|
+
const postText3 = existsSync(join(pluginRuntime, 'post-exit.ps1')) ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
|
|
1576
|
+
const indexText3 = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
|
|
1577
|
+
const clientText3 = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
|
|
1578
|
+
check('common 的 byKind 收 plugin-missing / context-state',
|
|
1579
|
+
commonText3.includes("'plugin-missing'") && commonText3.includes("'context-state'"))
|
|
1580
|
+
check('apply 记 plugin-missing(插件没装好要能看见)',
|
|
1581
|
+
/Add-SyncNotice\s+-Kind\s+'plugin-missing'/.test(applyText3))
|
|
1582
|
+
check('压缩状态缺失记 context-state(压缩状态没跟过来要能看见)',
|
|
1583
|
+
/Add-SyncNotice\s+-Kind\s+'context-state'/.test(commonText3))
|
|
1584
|
+
check('post-exit 汇总里带这两类标题',
|
|
1585
|
+
postText3.includes('plugin-missing') && postText3.includes('context-state'))
|
|
1586
|
+
check('index.js 白名单含这两类(否则会被降级成 skipped)',
|
|
1587
|
+
indexText3.includes("'plugin-missing'") && indexText3.includes("'context-state'"))
|
|
1588
|
+
check('client.js 给这两类中文文案',
|
|
1589
|
+
clientText3.includes("'plugin-missing'") && clientText3.includes("'context-state'"))
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1526
1592
|
console.log('')
|
|
1527
1593
|
process.exit(failures === 0 ? 0 : 1)
|
|
1594
|
+
|