dsh-recall-plugin 2.0.0 → 2.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.
@@ -0,0 +1,541 @@
1
+ /**
2
+ * dsh-recall-plugin — 管理路由域(R2 从 index.js 拆出)
3
+ *
4
+ * exclude-get/set、config-get/set/reset、manage(列表/标题/文本/占用/删除/
5
+ * 删除全部/gc/lineage)端点,以及 manage 用的删除辅助(deleteSnapshotsByFilter /
6
+ * deleteAllSnapshots)。依赖经 deps 注入;listCache/excludeCache 是 apply 级
7
+ * 可变 holder(改属性而非重绑定),与 index.js 的事件接线共享同一引用。
8
+ */
9
+
10
+ import { isSafetySnapshotId } from './snapshots.js'
11
+
12
+ export function createRoutesManage(deps) {
13
+ const {
14
+ ctx, rt, snaps, maint, state, cfg, supported, enqueue, runLimited,
15
+ listExcludeFiles, dumpStores, locateSnapshotOnDisk, collectAllSnapshotRecords,
16
+ listCache, excludeCache, sessionInfo, titleFromEvents, messageTextFromEvents,
17
+ applyResolvedConfig, readSettings, DEFAULTS, E,
18
+ } = deps
19
+ const { sessionTitles, messageTexts, liveTitleFast, liveMessageTextFast } = sessionInfo
20
+
21
+ // 按过滤条件批量删除快照(工作区/会话两个树节点共用):先收集匹配
22
+ // id 并按 root 分组,再整体进串行队列——与快照/gc 互斥,避免 git 锁
23
+ // 竞态。每个 root 先 purge tag 再补载索引后重写 index.json,防止冷启动
24
+ // 时用残缺内存覆盖同 store 其余磁盘快照。
25
+ async function deleteSnapshotsByFilter(match, sessionId) {
26
+ const records = await collectAllSnapshotRecords()
27
+ const byRoot = new Map()
28
+ for (const rec of records.values()) {
29
+ if (!match(rec) || !rec.root) continue
30
+ if (!byRoot.has(rec.root)) byRoot.set(rec.root, [])
31
+ byRoot.get(rec.root).push(rec.id)
32
+ }
33
+ let deleted = 0
34
+ await enqueue(async () => {
35
+ for (const [root, rootIds] of byRoot) {
36
+ let store = state.stores.get(root)
37
+ if (!store) {
38
+ try { store = await rt.resolveStore(root) } catch (error) { store = null }
39
+ }
40
+ if (!store) continue
41
+ try {
42
+ if (state.gitExe) {
43
+ // tag 分块删除:win32 命令行有 32767 字符上限,整批传大量 tag 会
44
+ // 在长历史工作区上爆掉;与 maintenance.purgeSession 同款 100 个/块。
45
+ const tags = rootIds.map((id) => 'snap-' + id)
46
+ for (let i = 0; i < tags.length; i += 100) {
47
+ await rt.runShell(rt.scripts.purgeTagsScript(store, state.gitExe, tags.slice(i, i + 100)), { timeoutMs: 120000, stdoutMaxBytes: 4096 })
48
+ }
49
+ }
50
+ if (!state.indexLoaded.has(root)) {
51
+ try { await snaps.loadIndex(root, sessionId) } catch (error) { /* 载入失败照常重写,退化为旧行为 */ }
52
+ }
53
+ for (const id of rootIds) state.snapshots.delete(id)
54
+ await snaps.saveIndex(root, sessionId)
55
+ deleted += rootIds.length
56
+ } catch (error) {
57
+ // 单个 root 失败不阻断其他 root:best-effort,错误进状态页可见的
58
+ // 错误缓冲,剩余 root 继续清理。
59
+ rt.recordError('recall batch delete failed for ' + root + ': ' + String(error))
60
+ }
61
+ }
62
+ listCache.items = null
63
+ })
64
+ return deleted
65
+ }
66
+
67
+ // 删除所有工作区的全部快照。树形管理的「工作区/会话」批量删除以
68
+ // index.json 中的记录为目标;但「全部删除」必须把 git tag 当作真相源:
69
+ // index 可能因旧版/崩溃/手动修复而为空或过期,不能因为索引里没有条目就
70
+ // 漏删真实快照。磁盘枚举到的 store 即使 root.txt 丢失也直接按目录操作。
71
+ async function deleteAllSnapshots() {
72
+ return enqueue(async () => {
73
+ const stores = new Map()
74
+ for (const [root, store] of state.stores.entries()) {
75
+ if (store && store.dir) stores.set(store.dir, { store, root })
76
+ }
77
+ const dump = await dumpStores()
78
+ for (const [dir, info] of dump.entries()) {
79
+ const known = stores.get(dir)
80
+ if (known) {
81
+ if (!known.root && info.root) known.root = info.root
82
+ known.entries = info.entries || []
83
+ } else {
84
+ stores.set(dir, {
85
+ // 全局删除只动该目录下的 git/index;不必、也不能依赖可反解的 root。
86
+ store: rt.storeFromDir(dir, false),
87
+ root: info.root || null,
88
+ entries: info.entries || []
89
+ })
90
+ }
91
+ }
92
+
93
+ if (stores.size === 0) return { deleted: 0, stores: 0, failed: 0 }
94
+
95
+ const gitExe = await rt.resolveGit()
96
+ if (!gitExe) {
97
+ const message = '未检测到 git CLI,无法验证并删除快照 tag'
98
+ rt.recordError('recall delete all failed: ' + message)
99
+ return { deleted: 0, stores: 0, failed: stores.size || 1, message }
100
+ }
101
+
102
+ let deleted = 0
103
+ let clearedStores = 0
104
+ let failed = 0
105
+ for (const { store, root } of stores.values()) {
106
+ try {
107
+ // 先列出实际 tag;不要使用 entries 推导 tag,entries 是可丢失缓存。
108
+ const output = await rt.runShell(rt.scripts.listTagsScript(store, gitExe), { timeoutMs: 120000, stdoutMaxBytes: 4194304 })
109
+ const tags = rt.scripts.stripBom(output).split(/\r?\n/).map((tag) => tag.trim()).filter((tag) => tag.indexOf('snap-') === 0)
110
+ for (let i = 0; i < tags.length; i += 100) {
111
+ await rt.runShell(rt.scripts.purgeTagsScript(store, gitExe, tags.slice(i, i + 100)), { timeoutMs: 120000, stdoutMaxBytes: 4096 })
112
+ }
113
+ // purgeTagsScript 为幂等 best-effort,故必须回读校验,避免脚本吞掉
114
+ // 个别失败后仍错误地把 index.json 清空。
115
+ const remainedOutput = await rt.runShell(rt.scripts.listTagsScript(store, gitExe), { timeoutMs: 120000, stdoutMaxBytes: 4194304 })
116
+ const remained = rt.scripts.stripBom(remainedOutput).split(/\r?\n/).map((tag) => tag.trim()).filter((tag) => tag.indexOf('snap-') === 0)
117
+ if (remained.length) throw new Error('仍有 ' + remained.length + ' 个快照 tag 未删除')
118
+
119
+ // tag 清理被确认后才清空索引。直接写已枚举的 store,兼容 root.txt
120
+ // 缺失/错位的旧仓库;不能调用 saveIndex(root),后者会重新按 root 寻址。
121
+ await rt.writeTextViaShell(store.dir + (rt.isWin ? '\\' : '/') + 'index.json', '[]')
122
+ for (const tag of tags) state.snapshots.delete(tag.slice('snap-'.length))
123
+ if (root) {
124
+ for (const [id, snap] of state.snapshots.entries()) {
125
+ if (snap && snap.root === root) state.snapshots.delete(id)
126
+ }
127
+ state.indexLoaded.add(root)
128
+ }
129
+ deleted += tags.length
130
+ clearedStores += 1
131
+ } catch (error) {
132
+ failed += 1
133
+ rt.recordError('recall delete all failed for ' + store.dir + ': ' + String(error))
134
+ }
135
+ }
136
+ // list 既合并内存也 dump 磁盘;无论完全/部分完成都必须失效,才能让
137
+ // 成功删除的 store 立即从树上消失,而失败 store 仍保留供用户重试。
138
+ listCache.items = null
139
+ return { deleted, stores: clearedStores, failed }
140
+ })
141
+ }
142
+
143
+ return {
144
+ 'exclude-get': async () => {
145
+ // 设置页「撤回设置」标签的配置读取。不支持平台照常短路:Client
146
+ // 显示不可用提示而不是空白表单,与 init 的 notice 语义对齐。
147
+ if (!supported) return { ok: false, unsupported: true }
148
+ // 30s 结果缓存:首次进入要并行 resolveStore + 逐文件 shell 读,
149
+ // 二次打开/切标签不应重复付出这份代价;exclude-set 写入后失效。
150
+ if (excludeCache.payload && Date.now() - excludeCache.at < 30000) return excludeCache.payload
151
+ 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 }
159
+ excludeCache.at = Date.now()
160
+ excludeCache.payload = payload
161
+ return payload
162
+ },
163
+
164
+ 'exclude-set': async (args) => {
165
+ if (!supported) return { ok: false, unsupported: true }
166
+ const path = args && args.path ? String(args.path) : ''
167
+ const content = args && typeof args.content === 'string' ? args.content : ''
168
+ // 路径白名单:重新枚举当前已知 exclude 文件并要求精确命中,
169
+ // 客户端伪造的任意路径在这里被拒(见 listExcludeFiles 注释)
170
+ const byFile = await listExcludeFiles()
171
+ const info = byFile.get(path)
172
+ if (!info) return { ok: false, code: E.RECALL_UNKNOWN_PATH, message: '未知的排除文件路径' }
173
+ await snaps.writeExclude(info.store, content)
174
+ // 写入后立即失效:设置页保存后刷新必须看到最新内容
175
+ excludeCache.payload = null
176
+ return { ok: true }
177
+ },
178
+
179
+ // 设置页「插件配置」卡片读配置:resolved 全量值 + 用户已覆盖字段 + env
180
+ // 锁定字段(环境变量优先级最高)+ 可写性(只读 provider 禁存)。
181
+ 'config-get': async () => {
182
+ const envLocks = {
183
+ gcSnaps: Boolean(process.env && process.env.DSH_RECALL_GC_SNAPS),
184
+ gcHours: Boolean(process.env && process.env.DSH_RECALL_GC_HOURS),
185
+ }
186
+ let overridden = {}
187
+ let writable = false
188
+ try {
189
+ const settings = ctx.get('settings')
190
+ if (settings && typeof settings.describe === 'function') {
191
+ const list = settings.describe()
192
+ const ours = (Array.isArray(list) ? list : []).find((d) => d && d.ns === 'dsh-recall')
193
+ if (ours && ours.user && typeof ours.user === 'object') overridden = ours.user
194
+ writable = settings.writable !== false
195
+ }
196
+ } catch (error) { /* describe 不可用按「无覆盖」处理 */ }
197
+ return {
198
+ ok: true,
199
+ values: {
200
+ gcSnaps: cfg.gcSnaps,
201
+ gcHours: cfg.gcHours,
202
+ maxFileBytes: cfg.maxFileBytes,
203
+ maxSnapshotsPerWorkspace: cfg.maxSnapshotsPerWorkspace,
204
+ baseExcludes: cfg.baseExcludes.slice(),
205
+ refillDraft: cfg.refillDraft,
206
+ snapshotEnabled: cfg.snapshotEnabled,
207
+ archiveOriginal: cfg.archiveOriginal,
208
+ retentionDays: cfg.retentionDays,
209
+ },
210
+ overridden,
211
+ envLocks,
212
+ writable,
213
+ }
214
+ },
215
+
216
+ // 设置页「插件配置」卡片存配置:白名单字段 + 类型清洗后经 settings.update
217
+ // 写进用户层,watch 链路把新值热更新进 cfg,无需重启。
218
+ 'config-set': async (args) => {
219
+ const patch = args && args.patch && typeof args.patch === 'object' ? args.patch : {}
220
+ const clean = {}
221
+ if (patch.gcSnaps !== undefined) clean.gcSnaps = Number(patch.gcSnaps)
222
+ if (patch.gcHours !== undefined) clean.gcHours = Number(patch.gcHours)
223
+ if (patch.maxFileBytes !== undefined) clean.maxFileBytes = Number(patch.maxFileBytes)
224
+ if (patch.maxSnapshotsPerWorkspace !== undefined) {
225
+ const n = Number(patch.maxSnapshotsPerWorkspace)
226
+ // 0 或负值 = 不限制(schema 由 number 校验,非法 NaN 在 settings.write 层被拒)
227
+ if (!Number.isFinite(n)) return { ok: false, code: E.RECALL_BAD_TYPE, message: '快照总量上限必须是数字' }
228
+ clean.maxSnapshotsPerWorkspace = Math.max(0, n)
229
+ }
230
+ if (patch.refillDraft !== undefined) clean.refillDraft = Boolean(patch.refillDraft)
231
+ if (patch.snapshotEnabled !== undefined) clean.snapshotEnabled = Boolean(patch.snapshotEnabled)
232
+ if (patch.archiveOriginal !== undefined) clean.archiveOriginal = Boolean(patch.archiveOriginal)
233
+ if (patch.retentionDays !== undefined) {
234
+ const n = Number(patch.retentionDays)
235
+ // 0/负值 = 不启用(schema 校验 base 由 number 承担,NaN 由 settings.write 拒)
236
+ if (!Number.isFinite(n) || n < 0) return { ok: false, code: E.RECALL_BAD_TYPE, message: '保留天数必须是 >= 0 的数字(0 表示不启用)' }
237
+ clean.retentionDays = Math.trunc(n)
238
+ }
239
+ if (patch.baseExcludes !== undefined) {
240
+ if (!Array.isArray(patch.baseExcludes)) return { ok: false, code: E.RECALL_BAD_TYPE, message: 'baseExcludes 必须是字符串数组' }
241
+ clean.baseExcludes = patch.baseExcludes.filter((p) => typeof p === 'string' && p.trim())
242
+ }
243
+ if (!Object.keys(clean).length) return { ok: false, code: E.RECALL_EMPTY_PATCH, message: '没有可写入的配置字段' }
244
+ let settings = null
245
+ try { settings = ctx.get('settings') } catch (error) { settings = null }
246
+ if (!settings || typeof settings.update !== 'function') {
247
+ return { ok: false, code: E.RECALL_SETTINGS_UNAVAILABLE, message: '设置服务不可用:请在 profile 的 cordis.patch.yml 按 id: recall 覆盖配置' }
248
+ }
249
+ try {
250
+ await settings.update('dsh-recall', clean)
251
+ } catch (error) {
252
+ return { ok: false, code: E.RECALL_SETTINGS_WRITE_FAILED, message: '配置写入失败:' + String(error && error.message ? error.message : error) }
253
+ }
254
+ return { ok: true }
255
+ },
256
+
257
+ // 设置页「快照管理」卡片:列表 / 磁盘占用 / 单条删除 / 手动 gc。
258
+ // 全部走串行队列——删除 tag 与 gc 与快照争的是同一个 git 仓库。
259
+ 'manage': async (args) => {
260
+ if (!supported) return { ok: false, unsupported: true }
261
+ const op = args && args.op ? String(args.op) : 'list'
262
+ const sessionId = args && args.sessionId ? String(args.sessionId) : null
263
+ if (op === 'list') {
264
+ const limitRaw = args && args.limit !== undefined ? Number(args.limit) : 200
265
+ 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
310
+ }
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))
324
+ listCache.at = Date.now()
325
+ listCache.items = allItems
326
+ return { ok: true, items: allItems.slice(0, safeLimit), total: allItems.length }
327
+ }
328
+ if (op === 'titles') {
329
+ // supported 已在 manage 入口短路(A3:此处重复检查是死代码)
330
+ const ids = Array.from(new Set(
331
+ (Array.isArray(args && args.sessionIds) ? args.sessionIds.map(String) : []).filter(Boolean)
332
+ )).slice(0, 100)
333
+ const out = {}
334
+ // 并发限 4:冷标题 readSession 是重 IO,限制后列表不受影响、标题渐进补齐
335
+ await runLimited(ids.map((sid) => async () => {
336
+ if (out[sid] !== undefined) return
337
+ let title = liveTitleFast(sid)
338
+ if (title === null) {
339
+ const query = ctx.get('sessionQuery')
340
+ if (query && typeof query.readSession === 'function') {
341
+ try {
342
+ const log = await query.readSession(sid)
343
+ title = titleFromEvents(log && log.events)
344
+ } catch (error) { title = null }
345
+ }
346
+ }
347
+ sessionTitles.set(sid, title)
348
+ out[sid] = title
349
+ }), 4)
350
+ return { ok: true, titles: out }
351
+ }
352
+ if (op === 'messages') {
353
+ // supported 已在 manage 入口短路(A3:此处重复检查是死代码)
354
+ const reqs = Array.isArray(args && args.requests) ? args.requests.slice(0, 200) : []
355
+ const bySession = new Map()
356
+ for (const r of reqs) {
357
+ const sid = r && r.sessionId ? String(r.sessionId) : null
358
+ const mid = r && r.messageId ? String(r.messageId) : null
359
+ if (!sid || !mid) continue
360
+ if (!bySession.has(sid)) bySession.set(sid, [])
361
+ bySession.get(sid).push(mid)
362
+ }
363
+ const texts = {}
364
+ await runLimited(Array.from(bySession.entries()).map(([sid, mids]) => async () => {
365
+ // 该会话所有消息都已缓存(含 null)时,不必 readSession 冷读
366
+ const allCached = mids.every((mid) => messageTexts.has(String(sid) + '\u0000' + String(mid)))
367
+ let log = null
368
+ if (!allCached) {
369
+ const query = ctx.get('sessionQuery')
370
+ if (query && typeof query.readSession === 'function') {
371
+ try {
372
+ log = await query.readSession(sid)
373
+ } catch (error) { log = null }
374
+ }
375
+ }
376
+ for (const mid of mids) {
377
+ const key = String(sid) + '\u0000' + String(mid)
378
+ // 缓存命中(含 null)直接复用,避免已确认无文本的消息反复冷读
379
+ if (messageTexts.has(key)) {
380
+ texts[mid] = messageTexts.get(key)
381
+ continue
382
+ }
383
+ let text = liveMessageTextFast(sid, mid)
384
+ if (text === null && log && Array.isArray(log.events)) {
385
+ text = messageTextFromEvents(log.events, mid)
386
+ }
387
+ messageTexts.set(key, text)
388
+ texts[mid] = text
389
+ }
390
+ }), 4)
391
+ return { ok: true, messageTexts: texts }
392
+ }
393
+ if (op === 'usage') {
394
+ let bytes = 0
395
+ let homeStores = 0
396
+ let fallbackStores = 0
397
+ if (sessionId) {
398
+ const root = await rt.resolveRoot(sessionId)
399
+ if (!root) return { ok: false, code: E.RECALL_NO_ROOT, message: '无法解析当前工作区' }
400
+ const store = state.stores.get(root)
401
+ if (!store) return { ok: false, code: E.RECALL_NO_STORE, message: '当前工作区尚未创建快照存储' }
402
+ if (store.home) homeStores++
403
+ else fallbackStores++
404
+ const out = await rt.runShell(rt.scripts.diskUsageScript(store.dir), { stdoutMaxBytes: 4096 })
405
+ bytes = parseInt(rt.scripts.stripBom(out).trim(), 10) || 0
406
+ } else {
407
+ for (const store of state.stores.values()) {
408
+ if (!store || !store.dir) continue
409
+ if (store.home) homeStores++
410
+ else fallbackStores++
411
+ try {
412
+ const out = await rt.runShell(rt.scripts.diskUsageScript(store.dir), { stdoutMaxBytes: 4096 })
413
+ bytes += parseInt(rt.scripts.stripBom(out).trim(), 10) || 0
414
+ } catch (error) { /* 单 store 失败跳过 */ }
415
+ }
416
+ }
417
+ return { ok: true, bytes, gitAvailable: state.gitExe !== '', homeStores, fallbackStores }
418
+ }
419
+ if (op === 'delete') {
420
+ const scope = args && args.scope ? String(args.scope) : 'snapshot'
421
+ const root = args && args.root ? String(args.root) : null
422
+ const targetSessionId = args && args.sessionId ? String(args.sessionId) : null
423
+ const id = args && args.messageId ? String(args.messageId) : ''
424
+ if (scope === 'workspace') {
425
+ if (!root) return { ok: false, code: E.RECALL_NO_ROOT, message: '缺少工作区路径' }
426
+ const deleted = await deleteSnapshotsByFilter((rec) => rec.root === root, sessionId)
427
+ return { ok: true, deleted }
428
+ }
429
+ if (scope === 'session') {
430
+ if (!targetSessionId) return { ok: false, code: E.RECALL_NO_SESSION, message: '缺少会话 ID' }
431
+ // 树形中会话挂在具体工作区下,客户端会传 root 限定范围;不传则保持
432
+ // 旧语义(删该会话全部工作区的快照),兼容老调用方。
433
+ const deleted = await deleteSnapshotsByFilter(
434
+ (rec) => rec.sessionId === targetSessionId && (!root || rec.root === root),
435
+ sessionId
436
+ )
437
+ return { ok: true, deleted }
438
+ }
439
+ // 管理列表来自磁盘(跨工作区全量),而内存 state.snapshots 只含当前
440
+ // 工作区 + 预热过的——冷启动时列表里有、内存里没有,只查内存会误报
441
+ // 「不存在」。解析链:内存命中 → Client 透传的条目 root → 磁盘 index 反查。
442
+ let snap = state.snapshots.get(id) || null
443
+ let snapRoot = snap ? snap.root : root
444
+ let store = null
445
+ if (snapRoot) {
446
+ try { store = await rt.resolveStore(snapRoot) } catch (error) { store = null }
447
+ }
448
+ if (!store) {
449
+ // 兜底:扫 home 容器与降级目录的 index.json,找到含该 id 的 store
450
+ const found = await locateSnapshotOnDisk(id)
451
+ if (found) { store = found.store; snapRoot = found.root }
452
+ }
453
+ if (!store) return { ok: false, code: E.RECALL_NO_SNAPSHOT, message: '该快照不存在' }
454
+ const finalStore = store
455
+ const finalRoot = snapRoot
456
+ await enqueue(async () => {
457
+ if (state.gitExe) {
458
+ await rt.runShell(rt.scripts.purgeTagsScript(finalStore, state.gitExe, ['snap-' + id]), { timeoutMs: 120000, stdoutMaxBytes: 4096 })
459
+ }
460
+ // 兜底路径到这里时内存可能还没载入过该 root 的索引——先 loadIndex
461
+ // 补齐内存视图,再删目标条目后重写,避免用残缺内存覆盖同 store
462
+ // 其余磁盘快照。
463
+ if (!state.indexLoaded.has(finalRoot)) {
464
+ try { await snaps.loadIndex(finalRoot, sessionId) } catch (error) { /* 载入失败照常重写,退化为旧行为 */ }
465
+ }
466
+ state.snapshots.delete(id)
467
+ await snaps.saveIndex(finalRoot, sessionId)
468
+ // 列表缓存失效:Client 删除后会立刻 refresh,必须看到最新状态
469
+ listCache.items = null
470
+ })
471
+ return { ok: true }
472
+ }
473
+ if (op === 'deleteAll') {
474
+ const result = await deleteAllSnapshots()
475
+ if (result.failed > 0) {
476
+ return {
477
+ ok: false,
478
+ code: E.RECALL_PARTIAL_DELETE,
479
+ deleted: result.deleted,
480
+ message: result.message || ('已删除 ' + result.deleted + ' 条快照,但有 ' + result.failed + ' 个存储未完成;请查看最近错误后重试')
481
+ }
482
+ }
483
+ return { ok: true, deleted: result.deleted, stores: result.stores }
484
+ }
485
+ if (op === 'gc') {
486
+ // 带会话上下文:只 gc 该会话的工作区;无上下文(设置卡片):全部已知
487
+ // store 逐个 gc。两者都排进串行队列,与快照互斥。
488
+ const done = sessionId
489
+ ? await enqueue(() => maint.runGc(sessionId, true))
490
+ : await enqueue(() => maint.runGcAll())
491
+ return { ok: true, gc: Boolean(done) }
492
+ }
493
+ 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) { /* 磁盘枚举失败退回内存 */ }
503
+ 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)
511
+ }
512
+ return { ok: true, lineage: out }
513
+ }
514
+ return { ok: false, code: E.RECALL_UNKNOWN_OP, message: '未知的管理操作: ' + op }
515
+ },
516
+
517
+ // 设置页「插件配置」卡片恢复默认:整段清空 user 层回组合 base——官方
518
+ // settings RPC 的 replace 明确是「restoration/reset 路径」。老版本服务
519
+ // 没有 replace 时降级 settings.update 写 DEFAULTS。
520
+ 'config-reset': async () => {
521
+ let settings = null
522
+ try { settings = ctx.get('settings') } catch (error) { settings = null }
523
+ if (!settings || typeof settings.update !== 'function') {
524
+ return { ok: false, code: E.RECALL_SETTINGS_UNAVAILABLE, message: '设置服务不可用:请在 profile 的 cordis.patch.yml 按 id: recall 覆盖配置' }
525
+ }
526
+ try {
527
+ if (typeof settings.replace === 'function') {
528
+ await settings.replace('dsh-recall', {})
529
+ } else {
530
+ await settings.update('dsh-recall', Object.assign({}, DEFAULTS, { baseExcludes: DEFAULTS.baseExcludes.slice() }))
531
+ }
532
+ } catch (error) {
533
+ return { ok: false, code: E.RECALL_SETTINGS_WRITE_FAILED, message: '恢复默认失败:' + String(error && error.message ? error.message : error) }
534
+ }
535
+ // 重置后热更运行中的 cfg(与 config-set 同链路的 watch 触发,这里做
536
+ // 双保险:descriptor 已变更,applyResolvedConfig 立即落地)
537
+ applyResolvedConfig(readSettings())
538
+ return { ok: true }
539
+ }
540
+ }
541
+ }