dsh-config-sync-plugin 0.3.65 → 0.3.67

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.
@@ -0,0 +1,407 @@
1
+ // 会话投影缓存守卫(session_projcache 陈旧记录自动清理)
2
+ //
3
+ // 解决的问题
4
+ // DSH 的「新建会话」不是每次真建,UI 会先在工作区里找一条**空白会话**复用:
5
+ // client-ui-workspace/createInWorkspace() → sessions.ids.find(summary.blank && ...)
6
+ // → createNamed({ sessionId: blank })
7
+ // 而 summary.blank 来自投影缓存 session_projcache\sessions\<id>.json 里的
8
+ // record.rows.sessionListMetadata.val.blank。
9
+ //
10
+ // 缓存是「写一半就停」的产物:某次会话创建时缓存写出了 blank:true + seq:-1,
11
+ // 之后日志继续追加(有了 turn/start、user/message),缓存却没被推进。
12
+ // 于是列表仍把这条会话当"空白",UI 挑它复用 → 宿主抛
13
+ // session/agent-busy: session "<id>" is owned by subagent routing
14
+ // (子会话 origin=subagent 不允许被主会话直接复用),新建会话直接失败。
15
+ //
16
+ // 处理办法
17
+ // 删掉那条 cache json,DSH 下次读列表时会按完整日志重建缓存,blank 也就跟着变 false。
18
+ // 这是纯文件操作,不碰任何上游代码、不改日志、不改工作区登记。
19
+ //
20
+ // 判定条件(四重,全中才算陈旧,宁可漏判不可误删)
21
+ // 1) 缓存能解析,且 record.rows.sessionListMetadata.val.blank === true
22
+ // 2) 能找到对应日志 sessions\<workspace>\<id>\session.v*.jsonl.zstd
23
+ // 3) 日志里确实有 turn/start 或 user/message 事件(真空会话不会有)
24
+ // 4) 日志最后事件 seq > 缓存记录的最大 seq(缓存确实落后于日志)
25
+ //
26
+ // 导出:
27
+ // scanSessionCaches(dshHome, opts) 只读扫描,返回候选与判定依据
28
+ // clearSessionCaches(dshHome, ids) 删除指定缓存(先备份)
29
+ // runGuard(dshHome, opts) 扫描 + 按需清理,供定时器与路由共用
30
+
31
+ import {
32
+ existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync,
33
+ } from 'node:fs'
34
+ import { join } from 'node:path'
35
+ import { splitFrames } from './session-log-lib.mjs'
36
+
37
+ /** 缓存相对 .dsh 的固定位置 */
38
+ const CACHE_REL = ['storages', 'session_projcache', 'sessions']
39
+ /** 日志相对 .dsh 的固定位置 */
40
+ const LOG_ROOT_REL = ['sessions']
41
+ /** 判定日志正文时最多读这么多字节(够覆盖首个 turn/start,减少大日志的解析成本) */
42
+ const HEAD_BYTES = 256 * 1024
43
+ /** 真空会话日志一般只有 header 帧,超过这个大小才值得去解析 */
44
+ const MIN_LOG_BYTES = 64
45
+
46
+ function safeStat(path) {
47
+ try {
48
+ return statSync(path)
49
+ } catch {
50
+ return null
51
+ }
52
+ }
53
+
54
+ function isDir(path) {
55
+ const st = safeStat(path)
56
+ return st !== null && st.isDirectory()
57
+ }
58
+
59
+ /** 缓存目录 */
60
+ export function cacheDirOf(dshHome) {
61
+ return join(dshHome, ...CACHE_REL)
62
+ }
63
+
64
+ /** 日志根目录 */
65
+ export function logRootOf(dshHome) {
66
+ return join(dshHome, ...LOG_ROOT_REL)
67
+ }
68
+
69
+ /**
70
+ * 建立 sessionId → 日志路径 的索引。
71
+ * 一次遍历 sessions\<workspace>\<sessionId>\session.v*.jsonl.zstd(两层,不做深递归)。
72
+ */
73
+ export function indexSessionLogs(dshHome) {
74
+ const root = logRootOf(dshHome)
75
+ const map = new Map()
76
+ if (!isDir(root)) return map
77
+ let workspaces
78
+ try {
79
+ workspaces = readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory())
80
+ } catch {
81
+ return map
82
+ }
83
+ for (const ws of workspaces) {
84
+ const wsPath = join(root, ws.name)
85
+ let sessions
86
+ try {
87
+ sessions = readdirSync(wsPath, { withFileTypes: true }).filter((e) => e.isDirectory())
88
+ } catch {
89
+ continue
90
+ }
91
+ for (const s of sessions) {
92
+ const sPath = join(wsPath, s.name)
93
+ let files
94
+ try {
95
+ files = readdirSync(sPath).filter((f) => /^session\.v\d+\.jsonl\.zstd$/i.test(f))
96
+ } catch {
97
+ continue
98
+ }
99
+ if (files.length === 0) continue
100
+ // 同一会话只会有一份现役日志;万一有多份取 mtime 最新的
101
+ let best = null
102
+ for (const f of files) {
103
+ const p = join(sPath, f)
104
+ const st = safeStat(p)
105
+ if (st === null) continue
106
+ if (best === null || st.mtimeMs > best.mtimeMs) best = { path: p, mtimeMs: st.mtimeMs, bytes: st.size }
107
+ }
108
+ if (best !== null) map.set(s.name, best)
109
+ }
110
+ }
111
+ return map
112
+ }
113
+
114
+ /** 一条缓存的概览(不解析日志) */
115
+ export function readCacheRecord(cachePath) {
116
+ const st = safeStat(cachePath)
117
+ if (st === null) return null
118
+ let json
119
+ try {
120
+ json = JSON.parse(readFileSync(cachePath, 'utf8'))
121
+ } catch (error) {
122
+ return { cachePath, bytes: st.size, mtimeMs: st.mtimeMs, broken: true, error: String(error && error.message) }
123
+ }
124
+ const record = json && json.record ? json.record : {}
125
+ const rows = record.rows && typeof record.rows === 'object' ? record.rows : {}
126
+ const meta = rows.sessionListMetadata && typeof rows.sessionListMetadata === 'object' ? rows.sessionListMetadata : null
127
+ // 缓存记录自身的最大 seq —— 用来判断它落后日志多少
128
+ let maxSeq = -1
129
+ for (const key of Object.keys(rows)) {
130
+ const row = rows[key]
131
+ if (row && typeof row.seq === 'number' && row.seq > maxSeq) maxSeq = row.seq
132
+ }
133
+ return {
134
+ cachePath,
135
+ bytes: st.size,
136
+ mtimeMs: st.mtimeMs,
137
+ version: json && json.version,
138
+ identity: record.identity && typeof record.identity === 'object' ? record.identity : null,
139
+ blank: meta !== null && meta.val && typeof meta.val === 'object' ? meta.val.blank === true : null,
140
+ blankMetaSeq: meta !== null && typeof meta.seq === 'number' ? meta.seq : null,
141
+ lastPromptAt: meta !== null && meta.val && typeof meta.val === 'object' ? meta.val.lastPromptAt ?? null : null,
142
+ maxSeq,
143
+ rowKeys: Object.keys(rows),
144
+ }
145
+ }
146
+
147
+ /**
148
+ * 只看日志头部若干帧,判断里面有没有真正发生过一轮对话。
149
+ * 返回 { hasTurn, turnSeq, hasUser, tailSeq, decodedFrames }
150
+ */
151
+ export function inspectLogHead(logPath) {
152
+ const st = safeStat(logPath)
153
+ const out = { logPath, bytes: st ? st.size : 0, mtimeMs: st ? st.mtimeMs : 0, hasTurn: false, turnSeq: null, hasUser: false, tailSeq: null, decodedFrames: 0 }
154
+ if (st === null || st.size < MIN_LOG_BYTES) return out
155
+ let buf
156
+ try {
157
+ buf = readFileSync(logPath)
158
+ } catch (error) {
159
+ out.error = String(error && error.message)
160
+ return out
161
+ }
162
+ const slice = buf.length > HEAD_BYTES ? buf.subarray(0, HEAD_BYTES) : buf
163
+ let frames
164
+ try {
165
+ frames = splitFrames(slice)
166
+ } catch (error) {
167
+ out.error = String(error && error.message)
168
+ return out
169
+ }
170
+ let text = ''
171
+ for (const f of frames) {
172
+ if (!f.decoded) continue
173
+ out.decodedFrames += 1
174
+ text += f.decoded.toString('utf8')
175
+ if (text.length > HEAD_BYTES * 4) break
176
+ }
177
+ for (const line of text.split('\n')) {
178
+ if (!line.trim()) continue
179
+ let obj
180
+ try {
181
+ obj = JSON.parse(line)
182
+ } catch {
183
+ continue
184
+ }
185
+ if (typeof obj.seq === 'number') out.tailSeq = obj.seq
186
+ if (obj.type === 'turn/start') {
187
+ out.hasTurn = true
188
+ if (out.turnSeq === null && typeof obj.seq === 'number') out.turnSeq = obj.seq
189
+ }
190
+ if (obj.type === 'user/message') out.hasUser = true
191
+ }
192
+ return out
193
+ }
194
+
195
+ /**
196
+ * 扫描全部投影缓存,标出陈旧记录。
197
+ *
198
+ * @param {string} dshHome
199
+ * @param {object} [opts]
200
+ * @param {boolean} [opts.deep=true] 是否去解析日志正文(false 只按缓存自身字段粗筛)
201
+ * @param {number} [opts.maxLogs=200] 最多解析多少份日志(防止极端情况下拖慢启动)
202
+ * @returns {{ ok:boolean, dshHome:string, cacheDir:string, scanned:number, stale:Array, blank:number, errors:Array }}
203
+ */
204
+ export function scanSessionCaches(dshHome, opts = {}) {
205
+ const deep = opts.deep !== false
206
+ const maxLogs = Number.isFinite(opts.maxLogs) ? opts.maxLogs : 200
207
+ const cacheDir = cacheDirOf(dshHome)
208
+ const report = { ok: true, dshHome, cacheDir, scanned: 0, blank: 0, stale: [], errors: [], logsInspected: 0 }
209
+ if (!isDir(cacheDir)) {
210
+ report.ok = false
211
+ report.errors.push(`缓存目录不存在:${cacheDir}`)
212
+ return report
213
+ }
214
+
215
+ let names
216
+ try {
217
+ names = readdirSync(cacheDir).filter((f) => f.toLowerCase().endsWith('.json'))
218
+ } catch (error) {
219
+ report.ok = false
220
+ report.errors.push(`读缓存目录失败:${String(error && error.message)}`)
221
+ return report
222
+ }
223
+
224
+ const logIndex = deep ? indexSessionLogs(dshHome) : new Map()
225
+ const judged = []
226
+
227
+ for (const name of names) {
228
+ const cachePath = join(cacheDir, name)
229
+ const rec = readCacheRecord(cachePath)
230
+ if (rec === null) continue
231
+ report.scanned += 1
232
+ if (rec.broken) {
233
+ // 缓存自己都解析不了,DSH 读它也会失败;但删除有风险(可能是别的格式版本),只报不改
234
+ report.errors.push(`缓存无法解析:${name}(${rec.error})`)
235
+ continue
236
+ }
237
+ if (rec.blank !== true) continue
238
+ report.blank += 1
239
+
240
+ const id = name.replace(/\.json$/i, '')
241
+ const item = {
242
+ id,
243
+ cachePath,
244
+ cacheBytes: rec.bytes,
245
+ cacheMtime: rec.mtimeMs,
246
+ cacheMaxSeq: rec.maxSeq,
247
+ blankMetaSeq: rec.blankMetaSeq,
248
+ cwd: rec.identity ? rec.identity.cwd ?? null : null,
249
+ createdAt: rec.identity ? rec.identity.createdAt ?? null : null,
250
+ logPath: null,
251
+ logBytes: null,
252
+ logTailSeq: null,
253
+ hasTurn: null,
254
+ hasUser: null,
255
+ stale: false,
256
+ reason: '',
257
+ }
258
+
259
+ if (!deep) {
260
+ // 粗筛:缓存 seq 还停在 -1 说明上一次写出后再没推进过,高度可疑
261
+ if (rec.maxSeq <= 0) {
262
+ item.stale = true
263
+ item.reason = `缓存从未推进(maxSeq=${rec.maxSeq})且仍标记 blank`
264
+ } else {
265
+ item.reason = '未检查日志(deep=false)'
266
+ }
267
+ judged.push(item)
268
+ continue
269
+ }
270
+
271
+ const log = logIndex.get(id)
272
+ if (log === undefined) {
273
+ item.reason = '找不到对应会话日志,跳过(可能是别的机器同步来的空壳)'
274
+ judged.push(item)
275
+ continue
276
+ }
277
+ if (report.logsInspected >= maxLogs) {
278
+ item.reason = `本次已达日志解析上限 ${maxLogs} 份,跳过`
279
+ judged.push(item)
280
+ continue
281
+ }
282
+ report.logsInspected += 1
283
+ item.logPath = log.path
284
+ item.logBytes = log.bytes
285
+ const head = inspectLogHead(log.path)
286
+ item.hasTurn = head.hasTurn
287
+ item.hasUser = head.hasUser
288
+ item.logTailSeq = head.tailSeq
289
+ if (head.error) item.reason = `日志解析出错:${head.error}`
290
+
291
+ const progressed = head.hasTurn || head.hasUser
292
+ if (!progressed) {
293
+ item.reason = '日志里确实没有对话事件(真空会话),缓存是对的'
294
+ judged.push(item)
295
+ continue
296
+ }
297
+ if (typeof head.tailSeq === 'number' && head.tailSeq <= rec.maxSeq) {
298
+ item.reason = `缓存并不落后日志(缓存 maxSeq=${rec.maxSeq},日志 tail=${head.tailSeq}),不动`
299
+ judged.push(item)
300
+ continue
301
+ }
302
+ item.stale = true
303
+ item.reason = `日志已有对话(turn=${head.hasTurn} 首轮 seq=${head.turnSeq},user=${head.hasUser},tail=${head.tailSeq}),缓存仍标 blank 且停在 seq=${rec.maxSeq}`
304
+ judged.push(item)
305
+ }
306
+
307
+ report.stale = judged.filter((x) => x.stale)
308
+ report.candidates = judged
309
+ return report
310
+ }
311
+
312
+ /**
313
+ * 删除指定会话的缓存(先挪到备份目录,不做物理删除)。
314
+ * 返回 { removed:[{id,from,to}], errors:[] }
315
+ */
316
+ export function clearSessionCaches(dshHome, ids, opts = {}) {
317
+ const cacheDir = cacheDirOf(dshHome)
318
+ const backupDir = opts.backupDir || join(dshHome, 'logs', 'session-cache-guard-backup')
319
+ const out = { removed: [], errors: [] }
320
+ const list = Array.isArray(ids) ? ids : []
321
+ if (list.length === 0) return out
322
+ let backupReady = false
323
+ for (const raw of list) {
324
+ const id = String(raw || '').trim()
325
+ if (id === '' || /[\\/]/.test(id) || id.includes('..')) {
326
+ out.errors.push(`非法会话 id:${raw}`)
327
+ continue
328
+ }
329
+ const from = join(cacheDir, `${id}.json`)
330
+ if (!existsSync(from)) {
331
+ out.errors.push(`缓存已不存在:${id}`)
332
+ continue
333
+ }
334
+ try {
335
+ if (!backupReady) {
336
+ mkdirSync(backupDir, { recursive: true })
337
+ backupReady = true
338
+ }
339
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
340
+ const to = join(backupDir, `${stamp}-${id}.json`)
341
+ renameSync(from, to)
342
+ out.removed.push({ id, from, to })
343
+ } catch (error) {
344
+ out.errors.push(`删除失败 ${id}:${String(error && error.message)}`)
345
+ }
346
+ }
347
+ return out
348
+ }
349
+
350
+ /** 追加一行日志到 .dsh\logs\session-cache-guard.log(失败不影响主流程) */
351
+ export function appendGuardLog(dshHome, text) {
352
+ try {
353
+ const dir = join(dshHome, 'logs')
354
+ mkdirSync(dir, { recursive: true })
355
+ const line = `[${new Date().toISOString()}] ${text}\n`
356
+ const file = join(dir, 'session-cache-guard.log')
357
+ let prev = ''
358
+ try {
359
+ const st = safeStat(file)
360
+ if (st !== null && st.size > 512 * 1024) prev = ''
361
+ else prev = readFileSync(file, 'utf8')
362
+ } catch {
363
+ prev = ''
364
+ }
365
+ writeFileSync(file, prev + line, 'utf8')
366
+ } catch {
367
+ /* 日志写不出来就算了 */
368
+ }
369
+ }
370
+
371
+ /**
372
+ * 扫描 + 按需清理,路由与定时器共用。
373
+ *
374
+ * @param {string} dshHome
375
+ * @param {object} [opts]
376
+ * @param {boolean} [opts.apply=true] 是否真的删(false 只报告)
377
+ * @param {string[]} [opts.ids] 只处理这些 id(不传=全部陈旧项)
378
+ * @param {boolean} [opts.deep=true]
379
+ * @param {string} [opts.source='manual'] 触发来源,写日志用
380
+ */
381
+ export function runGuard(dshHome, opts = {}) {
382
+ const apply = opts.apply !== false
383
+ const source = opts.source || 'manual'
384
+ const scan = scanSessionCaches(dshHome, { deep: opts.deep, maxLogs: opts.maxLogs })
385
+ const wanted = Array.isArray(opts.ids) && opts.ids.length > 0 ? opts.ids.map(String) : scan.stale.map((x) => x.id)
386
+ const result = {
387
+ ok: scan.ok,
388
+ dshHome,
389
+ source,
390
+ applied: apply,
391
+ scanned: scan.scanned,
392
+ blank: scan.blank,
393
+ staleCount: scan.stale.length,
394
+ stale: scan.stale.map((x) => ({ id: x.id, reason: x.reason, cwd: x.cwd, cacheMaxSeq: x.cacheMaxSeq, logTailSeq: x.logTailSeq, logPath: x.logPath })),
395
+ candidates: scan.candidates ? scan.candidates.map((x) => ({ id: x.id, stale: x.stale, reason: x.reason })) : [],
396
+ errors: scan.errors.slice(),
397
+ removed: [],
398
+ }
399
+ if (!apply || wanted.length === 0) return result
400
+ const cleared = clearSessionCaches(dshHome, wanted)
401
+ result.removed = cleared.removed
402
+ result.errors.push(...cleared.errors)
403
+ if (cleared.removed.length > 0) {
404
+ appendGuardLog(dshHome, `[${source}] 清理 ${cleared.removed.length} 条陈旧投影缓存:${cleared.removed.map((x) => x.id).join(', ')}`)
405
+ }
406
+ return result
407
+ }