dsh-profile-config-sync 0.6.47 → 0.7.1

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,347 @@
1
+ // 退出后执行(macOS / Linux)—— post-exit.ps1 的 Node 版等价物。
2
+ //
3
+ // 为什么必须有这一层:插件跑在 DSH 进程里,自己等不了自己退出。Windows 版用
4
+ // post-exit.ps1(PowerShell + Start-Process),macOS / Linux 上没有 PowerShell,
5
+ // 于是 0.6.47 之前这边整条「退出后推送 / 拉取 / 还原 / 重启」都是死路:
6
+ // spawnWatcher() 拉 powershell.exe 必然 ENOENT,面板上点了按钮什么都没发生。
7
+ //
8
+ // 用法(由插件在运行期以 detached 方式拉起):
9
+ // node post-exit.mjs -Mode pull|push|restore|relaunch|update -WatchPid <dsh pid> \
10
+ // -DshHome ~/.dsh [-RepoRoot ~/dsh-config] [-AppRoot /Applications/DeepSeek Harness.app] \
11
+ // [-Restart] [-CloseWhenIdle] [-BackupDir <snap>] [-SnapshotKind profile|plugin|session] \
12
+ // [-PluginDir <plugin>] [-PidFile <file>] [-MaxWaitMinutes 30]
13
+ //
14
+ // 契约(与 PowerShell 版一致,面板读的是同一份结果文件):
15
+ // - 只认 -WatchPid:那个进程真的消失后才动手,绝不在客户端运行期 apply;
16
+ // - 动作做完(无论成败)写 <DshHome>/auto-sync-result.json,客户端下次启动读它弹提示;
17
+ // - -Restart 时把客户端重新拉起来(macOS 用 `open -a`,Linux 用可执行文件本身);
18
+ // - 互斥锁 <DshHome>/auto-sync.lock 里记自己的 pid,别的同步动作看到它会排队。
19
+
20
+ import { spawn, spawnSync } from 'node:child_process'
21
+ import {
22
+ appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync,
23
+ } from 'node:fs'
24
+ import { clientExecutable, listClientProcesses } from './platform.mjs'
25
+ import { hostname } from 'node:os'
26
+ import { dirname, join, resolve } from 'node:path'
27
+ import { fileURLToPath } from 'node:url'
28
+
29
+ const SELF_DIR = dirname(fileURLToPath(import.meta.url))
30
+ const IS_MAC = process.platform === 'darwin'
31
+
32
+ /** 把 `-Key value` / `-Key=value` 混写的参数解析成对象(与 sync-engine.mjs 同语义)。 */
33
+ function parseArgs(argv) {
34
+ const out = {}
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const tok = String(argv[i])
37
+ if (!tok.startsWith('-')) continue
38
+ const clean = tok.replace(/^-+/, '')
39
+ const eq = clean.indexOf('=')
40
+ if (eq > 0) { out[clean.slice(0, eq)] = clean.slice(eq + 1); continue }
41
+ const next = argv[i + 1]
42
+ if (next !== undefined && !String(next).startsWith('-')) { out[clean] = String(next); i++ }
43
+ else out[clean] = true
44
+ }
45
+ return out
46
+ }
47
+
48
+ const a = parseArgs(process.argv.slice(2))
49
+ const mode = String(a.Mode || a.mode || '').toLowerCase()
50
+ const watchPid = Number(a.WatchPid || a.watchPid || 0) || 0
51
+ const dshHome = resolve(String(a.DshHome || a.dshHome || join(process.env.HOME || '', '.dsh')))
52
+ const repoRoot = String(a.RepoRoot || a.repoRoot || '')
53
+ const appRoot = String(a.AppRoot || a.appRoot || '')
54
+ const workspaceHome = String(a.WorkspaceHome || a.workspaceHome || '')
55
+ const profileName = String(a.ProfileName || a.profileName || 'desktop')
56
+ const restart = a.Restart === true || a.restart === true
57
+ const closeWhenIdle = a.CloseWhenIdle === true || a.closeWhenIdle === true
58
+ const backupDir = String(a.BackupDir || a.backupDir || '')
59
+ const snapshotKind = String(a.SnapshotKind || a.snapshotKind || 'profile')
60
+ const pluginDir = String(a.PluginDir || a.pluginDir || '')
61
+ const pidFile = String(a.PidFile || a.pidFile || '')
62
+ const maxWaitMinutes = Number(a.MaxWaitMinutes ?? a.maxWaitMinutes ?? 30)
63
+ const maxWait = Number.isFinite(maxWaitMinutes) && maxWaitMinutes >= 0 ? maxWaitMinutes : 30
64
+ // 夹具用:跳过「等客户端退出」这一步(自检里 DSH 本来就在跑,否则每套夹具都要等 30 分钟)。
65
+ const forceRun = a.ForceRun === true || a.forceRun === true
66
+ const updateTgz = String(a.UpdateTgz || a.updateTgz || '')
67
+ const updateVersion = String(a.UpdateVersion || a.updateVersion || '')
68
+
69
+ const KINDS = ['pull', 'push', 'restore', 'update', 'relaunch']
70
+ if (!KINDS.includes(mode)) {
71
+ console.error(`post-exit: -Mode 只能是 ${KINDS.join(' / ')}(收到 "${mode}")`)
72
+ process.exit(2)
73
+ }
74
+
75
+ const logsDir = join(dshHome, 'logs')
76
+ try { mkdirSync(logsDir, { recursive: true }) } catch { /* 建不出来就让下面的写日志失败被忽略 */ }
77
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
78
+ const logFile = join(logsDir, `auto-sync-${mode}-${stamp}.log`)
79
+ const resultFile = join(dshHome, 'auto-sync-result.json')
80
+ const lockFile = join(dshHome, 'auto-sync.lock')
81
+
82
+ function log(text) {
83
+ const line = `[${new Date().toISOString().slice(11, 19)}] ${text}\n`
84
+ try { appendFileSync(logFile, line, 'utf8') } catch { /* 日志写不进去不能影响同步 */ }
85
+ try { process.stdout.write(line) } catch { /* 没有终端就静默 */ }
86
+ }
87
+
88
+ function writeJsonAtomic(path, obj) {
89
+ const tmp = `${path}.tmp-${process.pid}`
90
+ try {
91
+ mkdirSync(dirname(path), { recursive: true })
92
+ writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8')
93
+ writeFileSync(path, readFileSync(tmp, 'utf8'), 'utf8')
94
+ rmSync(tmp, { force: true })
95
+ return true
96
+ } catch {
97
+ try { rmSync(tmp, { force: true }) } catch { /* 忽略 */ }
98
+ return false
99
+ }
100
+ }
101
+
102
+ function readNotices() {
103
+ try {
104
+ const p = join(dshHome, 'sync-notices.json')
105
+ if (!existsSync(p)) return null
106
+ const j = JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
107
+ return j && Number(j.total) > 0 ? j : null
108
+ } catch { return null }
109
+ }
110
+
111
+ function writeResult(ok, code, message, restored) {
112
+ const payload = {
113
+ mode,
114
+ ok: Boolean(ok),
115
+ at: Date.now(),
116
+ code: Number(code) || 0,
117
+ message: String(message || ''),
118
+ restored: Boolean(restored),
119
+ log: logFile,
120
+ appRoot,
121
+ restart,
122
+ platform: process.platform,
123
+ host: (() => { try { return hostname() } catch { return '' } })(),
124
+ notices: readNotices(),
125
+ }
126
+ if (writeJsonAtomic(resultFile, payload)) log(`结果已写入:${resultFile}`)
127
+ else log('写结果文件失败(不影响本次同步本身)')
128
+ }
129
+
130
+ /** 进程还活着吗(pid 复用也当活着,宁可多等一轮)。 */
131
+ function alive(pid) {
132
+ if (!pid) return false
133
+ try { process.kill(pid, 0); return true } catch { return false }
134
+ }
135
+
136
+ /**
137
+ * 客户端是否还在跑。
138
+ *
139
+ * 0.6.49:**不能**按进程名模糊匹配。本进程自己的命令行里就带着
140
+ * "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/.../node post-exit.mjs",
141
+ * 用 `pgrep -f "DeepSeek Harness"` 会匹配到自己 → 客户端早退了它还在等,等到 30 分钟超时
142
+ * 一件正事都不做;`pkill -f` 更会把自己杀掉。现在按客户端可执行文件路径精确匹配(见
143
+ * runtime/platform.mjs 的 listClientProcesses / looksLikeClientProcess)。
144
+ * 返回 true / false;判不了(没有 ps)返回 null。
145
+ */
146
+ function clientRunning() {
147
+ const list = listClientProcesses(appRoot, process.pid)
148
+ if (list === null) return null
149
+ return list.length > 0
150
+ }
151
+
152
+ /** 写等待日志:面板只读结果文件,这个日志是给人排查用的。 */
153
+ function waitLog(text) {
154
+ try { appendFileSync(join(logsDir, 'auto-sync-wait.log'), `[${new Date().toISOString()}] [${mode}] ${text}\n`, 'utf8') } catch { /* 忽略 */ }
155
+ }
156
+
157
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
158
+
159
+ /** 等 DSH 完全退出。超时返回 false。 */
160
+ async function waitForExit() {
161
+ if (forceRun) { waitLog('夹具模式:跳过等待'); return true }
162
+ if (!watchPid) return true
163
+ const deadline = Date.now() + maxWait * 60 * 1000
164
+ waitLog(`等待开始(pid ${watchPid})`)
165
+ let sawRunning = false
166
+ while (Date.now() < deadline) {
167
+ const byPid = alive(watchPid)
168
+ const byName = clientRunning()
169
+ const running = byPid || byName === true
170
+ if (running) sawRunning = true
171
+ if (!byPid && byName !== true) { waitLog('DSH 已完全退出'); return true }
172
+ if (closeWhenIdle && sawRunning && !byPid) {
173
+ // 插件请求过关闭(用户点了「立即拉取」这类):pid 没了但还有同名进程赖着,
174
+ // 说明是收进托盘的残留,明确授权下按可执行文件路径精确结束。
175
+ waitLog('pid 已退出但仍有客户端进程,按 -CloseWhenIdle 收掉残留')
176
+ // 按可执行文件路径精确结束(按名字会把自己这个等待进程也一起杀掉)
177
+ const procs = listClientProcesses(appRoot, process.pid) || []
178
+ for (const pid of procs) {
179
+ try { process.kill(pid, 'SIGTERM') } catch { /* 已经退了 */ }
180
+ }
181
+ }
182
+ await sleep(2000)
183
+ }
184
+ waitLog('等待超时,放弃本次同步')
185
+ return false
186
+ }
187
+
188
+ /** 客户端自带 Node 优先,其次当前进程的 node。 */
189
+ function nodeExe() {
190
+ const bundled = appRoot ? join(appRoot, 'Contents', 'Resources', 'runtime', 'primary-runtime', 'dependencies', 'node', 'bin', 'node') : ''
191
+ if (bundled && existsSync(bundled)) return bundled
192
+ return process.execPath
193
+ }
194
+
195
+ /** 执行体:仓库里的优先(随仓库更新),其次插件自带的。 */
196
+ function engine() {
197
+ // 顺序:插件自带 → 仓库那份。
198
+ // 0.6.49:原来仓库优先,可仓库里那份可能是旧版(换机后先 pull 的机器上尤其常见),
199
+ // 旧版不认新参数(-DryRun 会被当未知参数忽略,计划步骤直接变成真还原)。插件自带的
200
+ // 永远是「正在跑的这份代码」,仓库那份只在插件目录都找不到时兜底。
201
+ const candidates = [
202
+ join(SELF_DIR, 'sync-engine.mjs'),
203
+ pluginDir ? join(pluginDir, 'runtime', 'sync-engine.mjs') : '',
204
+ repoRoot ? join(repoRoot, 'sync-engine.mjs') : '',
205
+ ].filter(Boolean)
206
+ return candidates.find((p) => existsSync(p)) || ''
207
+ }
208
+
209
+ function runEngine(args, timeoutMs = 30 * 60 * 1000) {
210
+ const eng = engine()
211
+ if (!eng) return { code: 3, out: '', err: '插件与仓库里都没有 sync-engine.mjs' }
212
+ const argv = [eng]
213
+ if (mode !== 'restore' && mode !== 'relaunch' && mode !== 'update') argv.push(mode)
214
+ else if (mode === 'restore') argv.push('restore')
215
+ argv.push('-RepoRoot', repoRoot || dirname(eng), '-DshHome', dshHome)
216
+ if (appRoot) argv.push('-AppRoot', appRoot)
217
+ if (workspaceHome) argv.push('-WorkspaceHome', workspaceHome)
218
+ argv.push('-ProfileName', profileName)
219
+ argv.push(...args)
220
+ log(`执行:${nodeExe()} ${argv.join(' ')}`)
221
+ const r = spawnSync(nodeExe(), argv, { encoding: 'utf8', timeout: timeoutMs, maxBuffer: 32 * 1024 * 1024 })
222
+ const out = String(r.stdout || '')
223
+ const err = String(r.stderr || '')
224
+ for (const line of (out + err).split(/\r?\n/)) if (line.trim()) log(` ${line}`)
225
+ return { code: typeof r.status === 'number' ? r.status : (r.error ? 1 : 0), out, err }
226
+ }
227
+
228
+ /** 把客户端重新拉起来(macOS 用 open -a,Linux 直接起可执行文件)。 */
229
+ function relaunch() {
230
+ try {
231
+ if (IS_MAC && appRoot) {
232
+ const r = spawnSync('open', ['-a', appRoot], { encoding: 'utf8' })
233
+ if (r.status === 0) return true
234
+ log(`open -a 失败:${String(r.stderr || '').trim()}`)
235
+ }
236
+ // 可执行文件交给 platform.mjs 认(macOS .app / Linux 解包目录都对)
237
+ const exe = clientExecutable(appRoot)
238
+ if (exe && existsSync(exe)) {
239
+ const child = spawn(exe, [], { detached: true, stdio: 'ignore' })
240
+ child.unref()
241
+ return true
242
+ }
243
+ log('找不到客户端可执行文件,无法自动重启')
244
+ return false
245
+ } catch (e) {
246
+ log(`重启客户端失败:${e && e.message ? e.message : e}`)
247
+ return false
248
+ }
249
+ }
250
+
251
+ /** 插件更新:把已经下好的 tgz 或 URL 交给 install-plugin.mjs。 */
252
+ function installUpdate() {
253
+ const installer = [join(SELF_DIR, 'install-plugin.mjs'), pluginDir ? join(pluginDir, 'runtime', 'install-plugin.mjs') : '']
254
+ .filter(Boolean).find((p) => existsSync(p))
255
+ if (!installer) return { ok: false, code: 3, error: '插件目录里没有 runtime/install-plugin.mjs' }
256
+ const args = [installer, '-PluginDir', pluginDir || '', '-Version', updateVersion || '']
257
+ // 0.6.49:安装器的参数名是 -TgzFile(已下好的本地包)/ -TgzUrls(候选下载地址)。
258
+ // 原来这里传的是 -UpdateTgz(那是**本脚本**自己的参数名),安装器不认识 → 更新永远
259
+ // 报「没有可用的下载地址」。两个脚本的参数名不是同一套,别串用。实测踩过。
260
+ if (updateTgz) args.push('-TgzFile', updateTgz)
261
+ if (a.UpdateSha256) args.push('-Sha256', String(a.UpdateSha256))
262
+ if (a.UpdateIntegrity) args.push('-Integrity', String(a.UpdateIntegrity))
263
+ if (a.UpdateSha1) args.push('-Sha1', String(a.UpdateSha1))
264
+ args.push('-DshHome', dshHome)
265
+ log(`安装更新:${nodeExe()} ${args.join(' ')}`)
266
+ const r = spawnSync(nodeExe(), args, { encoding: 'utf8', timeout: 10 * 60 * 1000, maxBuffer: 16 * 1024 * 1024 })
267
+ const text = String(r.stdout || '') + String(r.stderr || '')
268
+ for (const line of text.split(/\r?\n/)) if (line.trim()) log(` ${line}`)
269
+ const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
270
+ if (!line) return { ok: false, code: 1, error: `安装脚本没有返回结果:${text.trim().slice(-300) || '(无输出)'}` }
271
+ try { return JSON.parse(line.slice('RESULT:'.length)) } catch { return { ok: false, code: 1, error: '安装结果不是合法 JSON' } }
272
+ }
273
+
274
+ /** 释放互斥锁(只在还持有的时候)。 */
275
+ function releaseLock() {
276
+ try {
277
+ const held = JSON.parse(readFileSync(lockFile, 'utf8'))
278
+ if (Number(held && held.pid) !== process.pid) return
279
+ } catch { return }
280
+ try { rmSync(lockFile, { force: true }) } catch { /* 忽略 */ }
281
+ }
282
+
283
+ /** 收尾:写结果 → 放锁 → 退出。所有分支都走这里,别让锁留在盘上。 */
284
+ function finish(code, ok, message, restored) {
285
+ writeResult(ok, code, message, restored)
286
+ releaseLock()
287
+ process.exit(Number(code) || 0)
288
+ }
289
+
290
+ // ---------- 主流程 ----------
291
+ try {
292
+ if (pidFile) {
293
+ try {
294
+ mkdirSync(dirname(pidFile), { recursive: true })
295
+ writeFileSync(pidFile, String(process.pid), 'utf8')
296
+ } catch { /* 拿不到 pid 文件只是父进程少一次确认,不影响执行 */ }
297
+ }
298
+ // 接管互斥锁:等待阶段记的是那个等待进程的 pid,这里换成真正干活的进程。
299
+ try { writeFileSync(lockFile, JSON.stringify({ pid: process.pid, mode, at: Date.now() }), 'utf8') } catch { /* 忽略 */ }
300
+
301
+ log(`开始:mode=${mode} watchPid=${watchPid} repo=${repoRoot || '(未配置)'}`)
302
+
303
+ const exited = await waitForExit()
304
+ if (!exited) finish(2, false, '等客户端退出超时,本次同步没执行', false)
305
+ // 进程刚退时文件句柄还没释放,留一点余量
306
+ await sleep(1500)
307
+
308
+ if (mode === 'relaunch') {
309
+ const ok = relaunch()
310
+ finish(ok ? 0 : 1, ok, ok ? '客户端已重新启动' : '重启客户端失败,请手动打开', false)
311
+ }
312
+
313
+ if (mode === 'update') {
314
+ const r = installUpdate()
315
+ if (!r.ok) finish(5, false, `插件更新失败:${r.error || '详见日志'}`, false)
316
+ if (restart) relaunch()
317
+ finish(0, true, `插件已更新到 ${updateVersion || r.version || '新版本'}(重启后生效)`, false)
318
+ }
319
+
320
+ if (mode === 'restore') {
321
+ const args = []
322
+ if (backupDir) args.push('-BackupDir', backupDir)
323
+ if (snapshotKind && snapshotKind !== 'profile') args.push('-SnapshotKind', snapshotKind)
324
+ if (pluginDir && snapshotKind === 'plugin') args.push('-PluginDir', pluginDir)
325
+ args.push('-Force')
326
+ const r = runEngine(args)
327
+ const ok = r.code === 0
328
+ if (restart) relaunch()
329
+ finish(ok ? 0 : 5, ok, ok
330
+ ? '已还原到所选备份(还原前的状态已留底,可再还原一次)'
331
+ : '还原失败,详见日志;还原前的状态已留底', false)
332
+ }
333
+
334
+ // pull / push
335
+ const r = runEngine(['-Force'])
336
+ // 3 = 另一个同步动作正在进行(互斥):什么都没做,但不是故障
337
+ const skipped = r.code === 3
338
+ const failed = r.code !== 0 && !skipped
339
+ if (restart) relaunch()
340
+ if (skipped) finish(0, true, `另一个同步动作正在进行,本次${mode === 'pull' ? '拉取' : '推送'}已跳过(不是故障)`, false)
341
+ if (failed) finish(5, false, `${mode === 'pull' ? '拉取' : '推送'}失败(详见日志)`, false)
342
+ finish(0, true, mode === 'pull' ? '云端配置已拉取到本机' : '本机改动已推送到云端', false)
343
+ } catch (error) {
344
+ // 任何未预料的异常都要落盘 + 放锁,否则面板永远停在「排队中」
345
+ log(`未预料的异常:${(error && error.stack) || error}`)
346
+ finish(1, false, `执行异常:${(error && error.message) || error}`, false)
347
+ }
@@ -737,13 +737,13 @@ if ($Mode -eq 'update') {
737
737
  }
738
738
  $gotB64 = ''
739
739
  try {
740
- $fs = [System.IO.File]::OpenRead($tmp)
741
- try {
742
- $ms = New-Object System.IO.MemoryStream
743
- $sha.TransformBlock($fs, 0, $fs.Length, $null, 0) | Out-Null
744
- $sha.TransformFinalBlock([byte[]]::new(0), 0, 0) | Out-Null
745
- $gotB64 = [Convert]::ToBase64String($sha.Hash)
746
- } finally { $fs.Dispose() }
740
+ $bytes = [System.IO.File]::ReadAllBytes($tmp)
741
+ # 0.7.1 修复:旧写法把 FileStream 传给 TransformBlock(byte[], int, int, byte[], int)。
742
+ # .NET 的签名第一参是 byte[],PowerShell 7 找不到重载 → catch → 报「无法计算 sha512」,
743
+ # 更新在 0.6.47 就死在这(实测 Windows 报 Get-FileHash 不可用)。正确做法是先读成 byte[]。
744
+ $sha.TransformBlock($bytes, 0, $bytes.Length, $bytes, 0) | Out-Null
745
+ $sha.TransformFinalBlock([byte[]]::new(0), 0, 0) | Out-Null
746
+ $gotB64 = [Convert]::ToBase64String($sha.Hash)
747
747
  } catch {
748
748
  $msg = '插件更新失败:本机 PowerShell 无法计算安装包 ' + $algo + '(Get-FileHash 不可用且 .NET 回退也失败)'
749
749
  Log $msg
@@ -0,0 +1,46 @@
1
+ // 「插件设置与工作流」组的源文件清单 —— 面板(index.js)与引擎(sync-engine.mjs)共用一份。
2
+ //
3
+ // 一行一个源:`id` 是仓库里的文件名(`settings/<id>`),`rel` 相对 `<DshHome>`,
4
+ // `profileRel` 相对 `<DshHome>/profiles/<name>`。与 PowerShell 的 Get-SyncSettingsMap 同一份清单,
5
+ // 加新插件设置时**三个地方**都要跟着加(这里、PS 那份、面板只读这张表)。
6
+ //
7
+ // 为什么这组要单独列而不是整目录抓:这些文件散落在 <DshHome> 的树里,周围都是 .db / 缓存 / 会话,
8
+ // 整目录抓会顺带把几百 MB 的运行时数据搬进仓库。
9
+
10
+ import { join } from 'node:path'
11
+
12
+ export const SETTINGS_SOURCES = [
13
+ { id: 'our-free-model.json', rel: ['our-free-model', 'settings.json'] },
14
+ { id: 'comfyui-workflows.json', rel: ['data', 'dsh-comfyui', 'workflows.json'] },
15
+ { id: 'dsh-pet-main-config.jsonc', rel: ['dsh-pet', 'main-config.jsonc'] },
16
+ { id: 'dsh-market-state.json', profileRel: ['.dsh-market', 'state.json'] },
17
+ { id: 'dsh-pet-memory.json', rel: ['dsh-pet', 'memory.json'] },
18
+ { id: 'our-free-model-picks.json', rel: ['our-free-model', 'picks.json'] },
19
+ { id: 'dsh-im-interface-language.json', rel: ['integrations', 'dsh-im', 'interface-language.json'] },
20
+ { id: 'dsh-qq-config.json', rel: ['integrations', 'dsh-qq', 'config.json'] },
21
+ { id: 'dsh-qq-workspaces.json', rel: ['integrations', 'dsh-qq', 'workspaces.json'] },
22
+ { id: 'redteam-preset-declare.json', rel: ['redteam', 'preset-declare.json'] },
23
+ { id: 'task-board-ledger.json', rel: ['task-board', 'ledger-v2.json'] },
24
+ { id: 'task-board-scheduler.json', rel: ['task-board', 'scheduler-v2.json'] },
25
+ { id: 'dsh-workspaces.json', rel: ['storages', 'workspace.json'] },
26
+ { id: 'workspace-archives.json', rel: ['dsh-session-manager', 'workspace-archives.v1.json'] },
27
+ ]
28
+
29
+ export function settingsSourcePath(dshHome, profileDir, entry) {
30
+ return entry.profileRel ? join(profileDir, ...entry.profileRel) : join(dshHome, ...entry.rel)
31
+ }
32
+
33
+ /**
34
+ * 只带语义的运行时计数要清零,否则每轮抓取都「有改动」:
35
+ * our-free-model 的 settings.json 里这几个字段是插件自己每秒刷新的。
36
+ */
37
+ export const SETTINGS_VOLATILE_FIELDS = { 'our-free-model.json': ['catalogSyncedAt', 'reloadedAt', 'reloadCount'] }
38
+
39
+ /** 把易变字段的数值抹成 0(只动数字,别的一个字节都不碰)。 */
40
+ export function zeroVolatileFields(text, id) {
41
+ const fields = SETTINGS_VOLATILE_FIELDS[id]
42
+ if (!fields || !text) return text
43
+ let out = text
44
+ for (const k of fields) out = out.replace(new RegExp(`("${k}"\\s*:\\s*)\\d+`, 'g'), '$10')
45
+ return out
46
+ }