dsh-recall-plugin 2.1.0 → 2.2.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.
@@ -95,12 +95,21 @@ export function createMaintenance(ctx, rt, snaps, config) {
95
95
  return purged
96
96
  }
97
97
 
98
- // 扫描索引里出现过的全部会话:既不在 sessions 注册表、冷读日志又失败的,
99
- // 才认定「已删除」。两个保守闸门:
100
- // - sessionQuery 服务不存在时整体跳过——没有冷读能力就无法区分
101
- // 「已删除」和「只是冷着」,误删快照不可逆,宁可不清理;
102
- // - 归档会话(撤回功能自己归档的)日志仍在磁盘上,readSession 仍成功,
103
- // 不会被误清——只有日志真正消失才触发。
98
+ // 扫描索引里出现过的全部会话:不在 sessions 注册表、也不在磁盘会话目录
99
+ // 里的,才认定「已删除」。
100
+ // PF-7:一次 listSessions 建 id 集合替代逐会话 readSession 冷读——后者
101
+ // 对每个非 live 会话解压全量日志且跑在串行队列里,会话多的老工作区 gc
102
+ // 一到就把后续快照/撤回全堵在队尾;listSessions 是「目录级 header 枚举、
103
+ // 不触碰全量日志」(I8:记录 id 在 header.id),一次调用即得全部磁盘
104
+ // 会话 id 集。判定语义与旧「readSession 成败」等价且更保守:归档会话
105
+ // 日志仍在磁盘(集合中保留,不被误清——旧路径同样靠这一点)、日志损坏
106
+ // 但文件在的也保留(purge 不可逆,宁可少清)。
107
+ // 保守闸门保持:sessionQuery 服务(或 listSessions)不存在、枚举抛异常
108
+ // 时整体跳过——无法枚举就无法区分「已删除」和「只是冷着」,误删快照
109
+ // 不可逆,宁可不清理。
110
+ // titles 半项(PF-7 原案):探针(tests/probe/api-surface.test.js)确认
111
+ // SessionHeader 无 title 字段(标题住在事件日志里)→ 冷标题无法走
112
+ // listSessions,titles 冷读维持 readSession 现状。
104
113
  async function sweepDeletedSessions() {
105
114
  const ids = new Set()
106
115
  for (const s of state.snapshots.values()) {
@@ -108,17 +117,19 @@ export function createMaintenance(ctx, rt, snaps, config) {
108
117
  }
109
118
  if (!ids.size) return
110
119
  const query = ctx.get('sessionQuery')
111
- if (!query || typeof query.readSession !== 'function') return
120
+ if (!query || typeof query.listSessions !== 'function') return
121
+ let diskIds
122
+ try {
123
+ diskIds = new Set(((await query.listSessions()) || [])
124
+ .map((r) => r && r.header && r.header.id)
125
+ .filter(Boolean))
126
+ } catch (error) {
127
+ return
128
+ }
112
129
  for (const id of ids) {
113
130
  if (sessions.get(id)) continue
114
- let alive = false
115
- try {
116
- const log = await query.readSession(id)
117
- alive = Boolean(log)
118
- } catch (error) {
119
- alive = false
120
- }
121
- if (!alive) await purgeSession(id)
131
+ if (diskIds.has(id)) continue
132
+ await purgeSession(id)
122
133
  }
123
134
  }
124
135
 
@@ -257,7 +268,8 @@ export function createMaintenance(ctx, rt, snaps, config) {
257
268
  await runGc(sessionId, false)
258
269
  }
259
270
 
260
- // 模块收敛:runGc/runGcAll 之外的内部步骤不对外暴露面;enforceLimits
261
- // 保留导出供单测以工厂形态驱动(注入假 rt/ctx 钉执行链路)
262
- return { maybeMaintain, runGc, runGcAll, enforceLimits, enforceRetention }
271
+ // 模块收敛:runGc/runGcAll 之外的内部步骤不对外暴露面;enforceLimits /
272
+ // sweepDeletedSessions 保留导出供单测以工厂形态驱动(注入假 rt/ctx
273
+ // 执行链路;PF-7 sweep 判定矩阵依赖导出)。
274
+ return { maybeMaintain, runGc, runGcAll, enforceLimits, enforceRetention, sweepDeletedSessions }
263
275
  }
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { ENV_HINTS } from './diagnostics.js'
11
+ import { parseTreeId } from './snapshots.js'
11
12
 
12
13
  export function createRoutesCore(deps) {
13
14
  // ctx 不解构(A4):本域所有服务访问都已由 rt/snaps 封装,直接摸 ctx 会
@@ -64,7 +65,11 @@ export function createRoutesCore(deps) {
64
65
  if (result === null) return { ok: false, code: E.RECALL_NO_SNAPSHOT, message: '该消息没有可用的项目快照' }
65
66
  const snap2 = state.snapshots.get(id)
66
67
  const cutSeq = await snaps.resolveCutSeq(sessionId, id)
67
- return { ok: true, changes: result.changes, total: result.total, truncated: result.truncated, time: snap2 ? snap2.time : null, root: snap2 ? snap2.root : null, cutSeq }
68
+ // PF-1:treeId preview add -A 后的 index 树指纹,Client 确认时
69
+ // 透传回 execute——Host 与安全快照指纹比对即可判定「预览后文件是否
70
+ // 变化」,省掉 execute 侧整条重复 diff。旧版 Client 不认识该字段,
71
+ // 无值时 execute 退回 previewTotal 校验(向后兼容)。
72
+ return { ok: true, changes: result.changes, total: result.total, truncated: result.truncated, treeId: result.treeId || null, time: snap2 ? snap2.time : null, root: snap2 ? snap2.root : null, cutSeq }
68
73
  },
69
74
 
70
75
  'execute': async (args) => {
@@ -78,11 +83,15 @@ export function createRoutesCore(deps) {
78
83
  // P0-1:队列内第一步——执行前再查一次 agent 状态。检查放在互斥
79
84
  // 队列内,检查后紧接执行,中间不可能插进别的操作,窗口为零。
80
85
  if (agentBusy(sessionId, snap.root)) return { ok: false, code: E.RECALL_AGENT_BUSY, message: 'Agent 正在运行中,请先停止后再撤回' }
81
- // P0-3:preview→execute 失效校验。只由带 previewTotal 的新版
82
- // Client 触发(老版本/直调 API 不带则跳过,向后兼容)。校验失败
83
- // 连安全快照都不打——省一次全量 add。同数不同文件的边缘情形由
84
- // 下方 pre-rollback 安全快照兜底。
85
- if (args && typeof args.previewTotal === 'number') {
86
+ // P0-3 / PF-1:preview→execute 失效校验,两代并存——
87
+ // - 新版 Client 透传 previewTreeId(preview 时 add -A 后的 index 树
88
+ // 指纹):与下方安全快照输出的指纹比对,内容级一致判定,且免掉
89
+ // 一整条重复 diff 进程(一次撤回 4 条重进程 → 3 条)。
90
+ // - 旧版 Client 只带 previewTotal:退回条目总数校验(多付一次 diff,
91
+ // 同数不同文件的边缘情形由安全快照兜底)。
92
+ // - 都不带(直调 API):不校验,与 P0-3 同款可选语义。
93
+ const previewTreeId = args && typeof args.previewTreeId === 'string' && args.previewTreeId ? args.previewTreeId : null
94
+ if (!previewTreeId && args && typeof args.previewTotal === 'number') {
86
95
  const fresh = await snaps.diffFor(id)
87
96
  if (!fresh || fresh.total !== args.previewTotal) {
88
97
  return { ok: false, code: E.RECALL_STALE, message: '预览后项目文件发生了变化,请重新预览确认' }
@@ -95,15 +104,24 @@ export function createRoutesCore(deps) {
95
104
  // 用户可让插件从该 tag 恢复,堵住唯一的不可逆操作缺口。
96
105
  // 失败时 safetyOk 置 false:后续回退若也失败将无救援点(H1),
97
106
  // 行为退化为现状(fail-loud),不更差。
107
+ // PF-1:安全快照输出的树指纹就是「执行时刻的工作区状态」——与
108
+ // previewTreeId 不一致 → STALE(此时安全快照已打下,isSafetySnapshotId
109
+ // 让它不进索引,反而是额外的救援点)。安全快照失败时无指纹可比对,
110
+ // 跳过指纹校验继续回退(不阻断主流程的既有语义)。
98
111
  const safetyId = 'pre-rollback-' + Date.now()
99
112
  let safetyOk = false
113
+ let safetyTreeId = null
100
114
  try {
101
- await rt.runShell(rt.scripts.snapshotScript(snap.root, store, state.gitExe, safetyId, cfg.baseExcludes), { timeoutMs: 600000, stdoutMaxBytes: 65536 })
115
+ const out = await rt.runShell(rt.scripts.snapshotScript(snap.root, store, state.gitExe, safetyId, cfg.baseExcludes), { timeoutMs: 600000, stdoutMaxBytes: 65536 })
102
116
  safetyOk = true
117
+ safetyTreeId = parseTreeId(out)
103
118
  } catch (error) {
104
119
  // 安全快照失败不阻断回退本身:用户已确认覆盖,记录后照原计划执行
105
120
  rt.recordError('recall safety snapshot failed: ' + String(error))
106
121
  }
122
+ if (previewTreeId && safetyTreeId && safetyTreeId !== previewTreeId) {
123
+ return { ok: false, code: E.RECALL_STALE, message: '预览后项目文件发生了变化,请重新预览确认' }
124
+ }
107
125
  const rolled = await snaps.rollbackFor(id)
108
126
  if (rolled.ok) return rolled
109
127
  // 回退失败(rollbackFor 返回 partial,工作区可能半回退):用安全快照
@@ -8,22 +8,113 @@
8
8
  */
9
9
 
10
10
  import { isSafetySnapshotId } from './snapshots.js'
11
+ import { parseExcludeDump } from './dump-parse.js'
11
12
 
12
13
  export function createRoutesManage(deps) {
13
14
  const {
14
15
  ctx, rt, snaps, maint, state, cfg, supported, enqueue, runLimited,
15
16
  listExcludeFiles, dumpStores, locateSnapshotOnDisk, collectAllSnapshotRecords,
16
- listCache, excludeCache, sessionInfo, titleFromEvents, messageTextFromEvents,
17
+ listCache, excludeCache, usageCache, sessionInfo, titleFromEvents, messageTextFromEvents,
17
18
  applyResolvedConfig, readSettings, DEFAULTS, E,
18
19
  } = deps
19
20
  const { sessionTitles, messageTexts, liveTitleFast, liveMessageTextFast } = sessionInfo
20
21
 
22
+ // PF-6:list items 构建(磁盘 dump + 内存并集 + 排序)从 list 分支抽出——
23
+ // 同步路径与 stale 后台刷新共用同一实现(改一处漏一处的风险随合并消失)。
24
+ async function buildListItems() {
25
+ const allItems = []
26
+
27
+ // 磁盘全量:一条 shell dump。标题只查 live/缓存(liveTitleFast,同步
28
+ // 瞬时)——冷会话标题由 Client 拿到列表后异步调 titles 补齐。
29
+ const dump = await dumpStores()
30
+ const hints = new Map()
31
+ for (const [root, st] of state.stores.entries()) {
32
+ if (st && st.dir) hints.set(st.dir, root)
33
+ }
34
+ // 去重只用 id(消息 ID 全局唯一):带 root 进 key 会让同一快照因
35
+ // 「磁盘来源 root 缺失 / 内存来源 root 齐全」出现两条重复行
36
+ const byId = new Map()
37
+ function push(id, time, root, sessionId) {
38
+ if (!id || typeof id !== 'string') return
39
+ // F-G1 防御性展示过滤:修复前 rebuildOrphans 曾把 safety tag
40
+ // (pre-rollback-<ts>)strip 前缀后写进 index.json——存量污染条目
41
+ // 不做迁移清理(一次性数据,代价收益不划算),这里挡住可见性:
42
+ // 安全快照不是消息快照,本就不该出现在管理列表/树里。
43
+ if (isSafetySnapshotId(id)) return
44
+ const old = byId.get(id)
45
+ if (!old) {
46
+ const rec = {
47
+ id,
48
+ time: typeof time === 'number' ? time : 0,
49
+ root: root || null,
50
+ workspace: root ? root.replace(/[\\/]+$/, '').split(/[\\/]/).pop() : null,
51
+ sessionId: sessionId || null,
52
+ sessionTitle: liveTitleFast(sessionId)
53
+ }
54
+ // 消息文本只放已确认值:live 命中字符串则带,否则不设字段。
55
+ const liveText = liveMessageTextFast(sessionId, id)
56
+ if (liveText) rec.messageText = liveText
57
+ byId.set(id, rec)
58
+ allItems.push(rec)
59
+ return
60
+ }
61
+ // 与 collectAllSnapshotRecords 同款补全:磁盘先占位、内存后补全 root
62
+ if (!old.root && root) { old.root = root; old.workspace = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || null }
63
+ if (!old.sessionId && sessionId) { old.sessionId = sessionId; old.sessionTitle = liveTitleFast(sessionId) }
64
+ if (!old.messageText && id) { old.messageText = liveMessageTextFast(sessionId, id) }
65
+ if (!old.time && time) old.time = time
66
+ }
67
+ for (const [dir, info] of dump) {
68
+ const baseRoot = info.root || hints.get(dir) || null
69
+ for (const e of info.entries || []) {
70
+ if (!e || typeof e.id !== 'string') continue
71
+ push(e.id, e.time, (typeof e.root === 'string' && e.root) || baseRoot, e.sessionId)
72
+ }
73
+ }
74
+ // 内存兜底(刚拍未落盘的保险,正常已被磁盘 dump 覆盖)
75
+ for (const [id, s] of state.snapshots.entries()) {
76
+ push(id, s.time, s.root, s.sessionId)
77
+ }
78
+ allItems.sort((a, b) => (b.time || 0) - (a.time || 0))
79
+ return allItems
80
+ }
81
+
82
+ // PF-6:stale 时的后台缓存刷新(in-flight 去重)——stale 期间重复 list
83
+ // 复用同一进行中的 dump,不重复起进程(否则进程数反而放大)。完成后清
84
+ // stale 标记;失败静默(下次 stale 触发自然重试)。
85
+ function refreshListCacheInBackground() {
86
+ if (listCache.refreshing) return listCache.refreshing
87
+ listCache.refreshing = buildListItems()
88
+ .then((allItems) => {
89
+ listCache.items = allItems
90
+ listCache.at = Date.now()
91
+ listCache.stale = false
92
+ })
93
+ // 冒烟实证:这里的静默吞错曾让 stale 卡死近半小时无任何观测点——
94
+ // 失败必须留痕(console),否则只能靠行为异常反推
95
+ .catch((error) => { console.error('recall list refresh failed:', String(error && error.stack || error)) })
96
+ .finally(() => { listCache.refreshing = null })
97
+ return listCache.refreshing
98
+ }
99
+
21
100
  // 按过滤条件批量删除快照(工作区/会话两个树节点共用):先收集匹配
22
101
  // id 并按 root 分组,再整体进串行队列——与快照/gc 互斥,避免 git 锁
23
102
  // 竞态。每个 root 先 purge tag 再补载索引后重写 index.json,防止冷启动
24
103
  // 时用残缺内存覆盖同 store 其余磁盘快照。
104
+ // PF-6:缓存非空(含 stale)时直接由缓存 items 构造 records,省一次
105
+ // 全量 dumpStores——删除以「用户当前所见」为准(stale 说明有新快照未
106
+ // 入列表,用户没看到的也不在删除预期内);缓存为空才全量收集。
25
107
  async function deleteSnapshotsByFilter(match, sessionId) {
26
- const records = await collectAllSnapshotRecords()
108
+ let records
109
+ if (Array.isArray(listCache.items) && listCache.items.length) {
110
+ records = new Map()
111
+ for (const it of listCache.items) {
112
+ if (!it || typeof it.id !== 'string') continue
113
+ records.set(it.id, { id: it.id, root: it.root || null, sessionId: it.sessionId || null, time: typeof it.time === 'number' ? it.time : 0 })
114
+ }
115
+ } else {
116
+ records = await collectAllSnapshotRecords()
117
+ }
27
118
  const byRoot = new Map()
28
119
  for (const rec of records.values()) {
29
120
  if (!match(rec) || !rec.root) continue
@@ -60,6 +151,7 @@ export function createRoutesManage(deps) {
60
151
  }
61
152
  }
62
153
  listCache.items = null
154
+ usageCache.payload = null
63
155
  })
64
156
  return deleted
65
157
  }
@@ -136,6 +228,7 @@ export function createRoutesManage(deps) {
136
228
  // list 既合并内存也 dump 磁盘;无论完全/部分完成都必须失效,才能让
137
229
  // 成功删除的 store 立即从树上消失,而失败 store 仍保留供用户重试。
138
230
  listCache.items = null
231
+ usageCache.payload = null
139
232
  return { deleted, stores: clearedStores, failed }
140
233
  })
141
234
  }
@@ -145,17 +238,28 @@ export function createRoutesManage(deps) {
145
238
  // 设置页「撤回设置」标签的配置读取。不支持平台照常短路:Client
146
239
  // 显示不可用提示而不是空白表单,与 init 的 notice 语义对齐。
147
240
  if (!supported) return { ok: false, unsupported: true }
148
- // 30s 结果缓存:首次进入要并行 resolveStore + 逐文件 shell 读,
149
- // 二次打开/切标签不应重复付出这份代价;exclude-set 写入后失效。
241
+ // 30s 结果缓存:首次进入要 resolveStore + 读取,二次打开/切标签
242
+ // 不应重复付出这份代价;exclude-set 写入后失效。
150
243
  if (excludeCache.payload && Date.now() - excludeCache.at < 30000) return excludeCache.payload
151
244
  const byFile = await listExcludeFiles()
152
- // 并行读取各 exclude 文件内容:每个文件一条 shell,串行会放大延迟
153
- const files = await Promise.all(Array.from(byFile.entries()).map(async ([path, info]) => {
154
- let content = ''
155
- try { content = await snaps.readExclude(info.store) } catch (error) { content = '' }
156
- return { path, home: Boolean(info.store.home), roots: info.roots, content }
157
- }))
158
- const payload = { ok: true, files }
245
+ // PF-8:一条脚本 base64 读全部 exclude 文件——原每文件一条 Get-Content/
246
+ // cat 进程是首开 4-6 条链路里的大头;内容走 base64 对任意用户文本
247
+ // 免疫(定界不会被内容行打乱),parse 失败/文件缺失按空内容处理
248
+ // (与原 readExclude 对不存在文件输出空串的语义一致)。
249
+ let contents = new Map()
250
+ try {
251
+ const text = rt.scripts.stripBom(await rt.runShell(rt.scripts.excludeDumpScript(Array.from(byFile.keys())), { stdoutMaxBytes: 1048576 }))
252
+ contents = parseExcludeDump(text)
253
+ } catch (error) { /* dump 失败退回空内容列表(读失败的原语义) */ }
254
+ const payload = {
255
+ ok: true,
256
+ files: Array.from(byFile.entries()).map(([path, info]) => ({
257
+ path,
258
+ home: Boolean(info.store.home),
259
+ roots: info.roots,
260
+ content: contents.get(path) || ''
261
+ }))
262
+ }
159
263
  excludeCache.at = Date.now()
160
264
  excludeCache.payload = payload
161
265
  return payload
@@ -263,66 +367,19 @@ export function createRoutesManage(deps) {
263
367
  if (op === 'list') {
264
368
  const limitRaw = args && args.limit !== undefined ? Number(args.limit) : 200
265
369
  const safeLimit = Math.min(Math.max(Number.isFinite(limitRaw) ? Math.trunc(limitRaw) : 200, 1), 2000)
266
- if (listCache.items && Date.now() - listCache.at < 30000) {
267
- return { ok: true, items: listCache.items.slice(0, safeLimit), total: listCache.items.length }
268
- }
269
- const allItems = []
270
-
271
- // 磁盘全量:一条 shell dump。标题只查 live/缓存(liveTitleFast,同步
272
- // 瞬时)——冷会话标题由 Client 拿到列表后异步调 titles 补齐。
273
- const dump = await dumpStores()
274
- const hints = new Map()
275
- for (const [root, st] of state.stores.entries()) {
276
- if (st && st.dir) hints.set(st.dir, root)
277
- }
278
- // 去重只用 id(消息 ID 全局唯一):带 root 进 key 会让同一快照因
279
- // 「磁盘来源 root 缺失 / 内存来源 root 齐全」出现两条重复行
280
- const byId = new Map()
281
- function push(id, time, root, sessionId) {
282
- if (!id || typeof id !== 'string') return
283
- // F-G1 防御性展示过滤:修复前 rebuildOrphans 曾把 safety tag
284
- // (pre-rollback-<ts>)strip 前缀后写进 index.json——存量污染条目
285
- // 不做迁移清理(一次性数据,代价收益不划算),这里挡住可见性:
286
- // 安全快照不是消息快照,本就不该出现在管理列表/树里。
287
- if (isSafetySnapshotId(id)) return
288
- const old = byId.get(id)
289
- if (!old) {
290
- const rec = {
291
- id,
292
- time: typeof time === 'number' ? time : 0,
293
- root: root || null,
294
- workspace: root ? root.replace(/[\\/]+$/, '').split(/[\\/]/).pop() : null,
295
- sessionId: sessionId || null,
296
- sessionTitle: liveTitleFast(sessionId)
297
- }
298
- // 消息文本只放已确认值:live 命中字符串则带,否则不设字段。
299
- const liveText = liveMessageTextFast(sessionId, id)
300
- if (liveText) rec.messageText = liveText
301
- byId.set(id, rec)
302
- allItems.push(rec)
303
- return
304
- }
305
- // 与 collectAllSnapshotRecords 同款补全:磁盘先占位、内存后补全 root
306
- if (!old.root && root) { old.root = root; old.workspace = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || null }
307
- if (!old.sessionId && sessionId) { old.sessionId = sessionId; old.sessionTitle = liveTitleFast(sessionId) }
308
- if (!old.messageText && id) { old.messageText = liveMessageTextFast(sessionId, id) }
309
- if (!old.time && time) old.time = time
370
+ // PF-6:缓存非空且(fresh stale)→ 立即用旧 items 应答,对话中
371
+ // 打开快照管理不再等全量 dump(30s TTL 曾被每条消息的清空形同虚设)。
372
+ // stale 时后台刷新(in-flight 去重),Client 凭 stale 标记静默再拉
373
+ // 一次渐进补新。缓存为空 同步 dump(首开现状)。
374
+ if (listCache.items && (Date.now() - listCache.at < 30000 || listCache.stale)) {
375
+ const stale = Boolean(listCache.stale)
376
+ if (stale) refreshListCacheInBackground()
377
+ return { ok: true, items: listCache.items.slice(0, safeLimit), total: listCache.items.length, stale }
310
378
  }
311
- for (const [dir, info] of dump) {
312
- const baseRoot = info.root || hints.get(dir) || null
313
- for (const e of info.entries || []) {
314
- if (!e || typeof e.id !== 'string') continue
315
- push(e.id, e.time, (typeof e.root === 'string' && e.root) || baseRoot, e.sessionId)
316
- }
317
- }
318
- // 内存兜底(刚拍未落盘的保险,正常已被磁盘 dump 覆盖)
319
- for (const [id, s] of state.snapshots.entries()) {
320
- push(id, s.time, s.root, s.sessionId)
321
- }
322
-
323
- allItems.sort((a, b) => (b.time || 0) - (a.time || 0))
379
+ const allItems = await buildListItems()
324
380
  listCache.at = Date.now()
325
381
  listCache.items = allItems
382
+ listCache.stale = false
326
383
  return { ok: true, items: allItems.slice(0, safeLimit), total: allItems.length }
327
384
  }
328
385
  if (op === 'titles') {
@@ -391,6 +448,13 @@ export function createRoutesManage(deps) {
391
448
  return { ok: true, messageTexts: texts }
392
449
  }
393
450
  if (op === 'usage') {
451
+ // PF-3 顺带:全量 usage 结果 30s TTL(与 listCache 同款,删除/gc 后
452
+ // 由调用点失效)——ManageCard 每次 refresh 都重算的话,枚举再快
453
+ // 也是白付。仅缓存无 sessionId 的全量分支(client 唯一调用形态;
454
+ // 单工作区分支无调用方,不值得引入 key 维度)。
455
+ if (!sessionId && usageCache.payload && Date.now() - usageCache.at < 30000) {
456
+ return usageCache.payload
457
+ }
394
458
  let bytes = 0
395
459
  let homeStores = 0
396
460
  let fallbackStores = 0
@@ -404,17 +468,29 @@ export function createRoutesManage(deps) {
404
468
  const out = await rt.runShell(rt.scripts.diskUsageScript(store.dir), { stdoutMaxBytes: 4096 })
405
469
  bytes = parseInt(rt.scripts.stripBom(out).trim(), 10) || 0
406
470
  } else {
407
- for (const store of state.stores.values()) {
408
- if (!store || !store.dir) continue
409
- if (store.home) homeStores++
410
- else fallbackStores++
471
+ // PF-3 顺带:多 store 并行——读操作不碰 index.lock,但为防极端
472
+ // 磁盘争抢仍走 runLimited(并发 4)而不是裸 Promise.all;单 store
473
+ // 失败跳过的既有语义不变。
474
+ const knownStores = Array.from(state.stores.values()).filter((s) => s && s.dir)
475
+ const perStore = new Map()
476
+ await runLimited(knownStores.map((store) => async () => {
411
477
  try {
412
478
  const out = await rt.runShell(rt.scripts.diskUsageScript(store.dir), { stdoutMaxBytes: 4096 })
413
- bytes += parseInt(rt.scripts.stripBom(out).trim(), 10) || 0
479
+ perStore.set(store.dir, parseInt(rt.scripts.stripBom(out).trim(), 10) || 0)
414
480
  } catch (error) { /* 单 store 失败跳过 */ }
481
+ }), 4)
482
+ for (const store of knownStores) {
483
+ if (store.home) homeStores++
484
+ else fallbackStores++
485
+ bytes += perStore.get(store.dir) || 0
415
486
  }
416
487
  }
417
- return { ok: true, bytes, gitAvailable: state.gitExe !== '', homeStores, fallbackStores }
488
+ const payload = { ok: true, bytes, gitAvailable: state.gitExe !== '', homeStores, fallbackStores }
489
+ if (!sessionId) {
490
+ usageCache.at = Date.now()
491
+ usageCache.payload = payload
492
+ }
493
+ return payload
418
494
  }
419
495
  if (op === 'delete') {
420
496
  const scope = args && args.scope ? String(args.scope) : 'snapshot'
@@ -467,6 +543,7 @@ export function createRoutesManage(deps) {
467
543
  await snaps.saveIndex(finalRoot, sessionId)
468
544
  // 列表缓存失效:Client 删除后会立刻 refresh,必须看到最新状态
469
545
  listCache.items = null
546
+ usageCache.payload = null
470
547
  })
471
548
  return { ok: true }
472
549
  }
@@ -488,26 +565,27 @@ export function createRoutesManage(deps) {
488
565
  const done = sessionId
489
566
  ? await enqueue(() => maint.runGc(sessionId, true))
490
567
  : await enqueue(() => maint.runGcAll())
568
+ // gc 后占用显著下降:立即失效占用缓存,设置页 refresh 必须看到新值
569
+ usageCache.payload = null
491
570
  return { ok: true, gc: Boolean(done) }
492
571
  }
493
572
  if (op === 'lineage') {
494
- // F1:返回全部已知工作区的 fork lineage(childId ↔ parentId 撤回链),
495
- // 供快照管理树聚族。root 全集 = 内存 store + 磁盘 dump 的 root.txt。
496
- const roots = new Set(state.stores.keys())
497
- try {
498
- const dump = await dumpStores()
499
- for (const [dir, info] of dump) {
500
- if (info && info.root) roots.add(info.root)
501
- }
502
- } catch (error) { /* 磁盘枚举失败退回内存 */ }
573
+ // F1 / PF-4:返回全部已知工作区的 fork lineage(childId ↔ parentId
574
+ // 撤回链),供快照管理树聚族。原实现对每个 root 串行 loadLineage
575
+ // (每 root 一条进程,20 工作区 ≈ 10s,版本家族标记最后才亮)——
576
+ // LINEAGE 段并入 storesDump 后一次 dump 全拿,零新增进程。dump 的
577
+ // ==DIR 就是磁盘 store 目录(比 roots 全集更全,还免去对未知 root
578
+ // resolveStore 建目录的副作用);无 LINEAGE 段的旧输出按空 lineage
579
+ // 处理(parseStoresDump 容错)。
580
+ const hints = new Map()
581
+ for (const [root, st] of state.stores.entries()) {
582
+ if (st && st.dir) hints.set(st.dir, root)
583
+ }
584
+ let dump
585
+ try { dump = await dumpStores() } catch (error) { dump = new Map() }
503
586
  const out = []
504
- for (const root of roots) {
505
- let store = state.stores.get(root)
506
- if (!store) {
507
- try { store = await rt.resolveStore(root) } catch (error) { store = null }
508
- }
509
- if (!store) continue
510
- for (const e of await snaps.loadLineage(root)) out.push(e)
587
+ for (const info of dump.values()) {
588
+ for (const e of info.lineage || []) out.push(e)
511
589
  }
512
590
  return { ok: true, lineage: out }
513
591
  }