dsh-config-sync-plugin 0.0.0-stage → 0.3.57

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,1461 @@
1
+ /**
2
+ * 无 UI 环境下的宿主半身自检:
3
+ * node tools/selftest.mjs [repoPath]
4
+ *
5
+ * 用一个假 ctx 拉起 index.js 的 apply(),验证两件事:
6
+ * 1. 两个路由都注册上了;
7
+ * 2. GET /config-sync/status 返回合法 JSON(结构字段齐全);
8
+ * 3. POST /config-sync/prepare 能在仓库根生成 .cmd,且带进程检查与正确参数。
9
+ * 不碰 DSH、不写 profile。
10
+ */
11
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'
12
+ import { tmpdir } from 'node:os'
13
+ import { dirname, join } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { apply } from '../index.js'
16
+
17
+ const repoArg = process.argv[2] || 'D:\\dsh-config'
18
+ const routes = new Map()
19
+
20
+ // prepare 写的是仓库根固定文件名。若那里已经有给用户用的真文件,先记下内容,断言完原样还原。
21
+ const FILE_NAME = { push: '同步-推送.cmd', pull: '同步-拉取.cmd', restore: '同步-还原.cmd' }
22
+ const backup = new Map()
23
+ for (const action of ['pull', 'push', 'restore']) {
24
+ const file = join(repoArg, FILE_NAME[action])
25
+ if (existsSync(file)) backup.set(file, readFileSync(file, 'utf8'))
26
+ }
27
+
28
+ const registered = await new Promise((resolve, reject) => {
29
+ const timer = setTimeout(() => reject(new Error('apply() 没有注册任何路由(webServer 未被 inject?)')), 5000)
30
+ const ctx = {
31
+ inject: (names, cb) => {
32
+ const scoped = {
33
+ effect: (fn) => fn(),
34
+ webServer: {
35
+ register: (route) => {
36
+ routes.set(route.path, route.handler)
37
+ clearTimeout(timer)
38
+ resolve(true)
39
+ return () => { }
40
+ },
41
+ },
42
+ logger: { warn: () => { } },
43
+ }
44
+ cb(scoped)
45
+ },
46
+ }
47
+ try { apply(ctx, { repoPath: repoArg, profileName: 'desktop' }) } catch (e) { reject(e) }
48
+ })
49
+
50
+ function fakeRes() {
51
+ const res = {
52
+ statusCode: 200,
53
+ headers: {},
54
+ body: '',
55
+ setHeader: (k, v) => { res.headers[k] = v },
56
+ end: (chunk) => { if (chunk) res.body += chunk },
57
+ destroy: () => { },
58
+ }
59
+ return res
60
+ }
61
+
62
+ function fakeReq({ method = 'GET', headers = {}, body = '' } = {}) {
63
+ const handlers = {}
64
+ const req = {
65
+ method,
66
+ headers,
67
+ destroy: () => { },
68
+ on: (event, fn) => { handlers[event] = fn; return req },
69
+ }
70
+ setImmediate(() => {
71
+ if (body) handlers.data?.(body)
72
+ handlers.end?.()
73
+ })
74
+ return req
75
+ }
76
+
77
+ function call(path, init) {
78
+ const handler = routes.get(path)
79
+ if (!handler) throw new Error(`路由未注册:${path}`)
80
+ const res = fakeRes()
81
+ const req = fakeReq(init)
82
+ return new Promise((resolve) => {
83
+ const done = () => resolve(res)
84
+ const origEnd = res.end
85
+ res.end = (chunk) => { origEnd(chunk); done() }
86
+ handler(req, res)
87
+ })
88
+ }
89
+
90
+ let failures = 0
91
+ function check(label, cond, detail = '') {
92
+ if (cond) console.log(` [OK] ${label}`)
93
+ else { failures++; console.log(` [X] ${label}${detail ? ' — ' + detail : ''}`) }
94
+ }
95
+
96
+ console.log('== dsh-config-sync-plugin 宿主半身自检 ==')
97
+ check('apply() 注册了路由', routes.size === 10 && routes.has('/config-sync/update') && routes.has('/config-sync/scope') && routes.has('/config-sync/extra-config') && routes.has('/config-sync/conflict') && routes.has('/config-sync/roots') && routes.has('/config-sync/feedback'), `实际 ${routes.size} 条:${[...routes.keys()].join(', ')}`)
98
+
99
+ const status = await call('/config-sync/status', { headers: { host: 'localhost:3080' } })
100
+ const body = JSON.parse(status.body || '{}')
101
+ check('status 返回 200', status.statusCode === 200, String(status.statusCode))
102
+ check('status.ok === true', body.ok === true, status.body.slice(0, 160))
103
+ check('含 repo / version / bundles / deps / advice',
104
+ Boolean(body.repo && body.version && body.bundles && body.deps && Array.isArray(body.advice)))
105
+ // 仓库可能正处在「本机还没有内容」的合法状态(0.3.35 起:等拉取 / 等初始化推送)。
106
+ // 这类状态下依赖仓库内容的断言没有验证意义,明确标 SKIP,别把环境状态当成代码失败。
107
+ const repoReady = Boolean(body.repo?.exists)
108
+ if (repoReady) check('repo 探测到仓库', true)
109
+ else console.log(` [SKIP] repo 探测到仓库 — 本机仓库还没有内容(${body.repo?.path || '?'},mode=${body.repo?.mode || '?'})`)
110
+ check('版本契约两个字段都读到',
111
+ typeof body.version?.local === 'string' && typeof body.version?.contract === 'string',
112
+ `${body.version?.local} / ${body.version?.contract}`)
113
+ check('bundle 数量与解析结果都在',
114
+ typeof body.bundles?.total === 'number' && Array.isArray(body.bundles?.unresolved))
115
+ check('依赖缺失是数组', Array.isArray(body.deps?.missing))
116
+ check('status 带回备份快照地址', Boolean(body.backup && body.backup.latest), body.backup && body.backup.latest)
117
+ check('备份快照目录在本机真实存在', Boolean(body.backup && body.backup.latest && existsSync(body.backup.latest)), body.backup && body.backup.root)
118
+ console.log(' 建议:' + (body.advice || []).join(' | '))
119
+ const latestSnapshot = (body.backup && body.backup.latest) || ''
120
+
121
+ function restoreCmd(file) {
122
+ const before = backup.get(file)
123
+ if (before === undefined) unlinkSync(file)
124
+ else writeFileSync(file, before, 'utf8')
125
+ }
126
+
127
+ if (repoReady) {
128
+ for (const action of ['pull', 'push', 'restore']) {
129
+ const prepared = await call('/config-sync/prepare', {
130
+ method: 'POST',
131
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
132
+ body: JSON.stringify({ action }),
133
+ })
134
+ const payload = JSON.parse(prepared.body || '{}')
135
+ check(`prepare(${action}) 返回 200 且 ok`, prepared.statusCode === 200 && payload.ok === true, prepared.body.slice(0, 160))
136
+ check(`prepare(${action}) 写出了 cmd`, existsSync(payload.path || ''), payload.path || '(无路径)')
137
+ check(`prepare(${action}) 的文件名是中文`, /[\\/][^\\/]*[\u4e00-\u9fa5][^\\/]*\.cmd$/.test(payload.path || ''), payload.path || '(无路径)')
138
+ if (existsSync(payload.path || '')) {
139
+ // prepare 会就地覆盖仓库根的 同步-推送/拉取/还原.cmd —— 那是给人用的真文件,
140
+ // 自检只借用这条路径做断言,结束后必须还原成原样(没有过就删掉)。
141
+ const text = readFileSync(payload.path, 'utf8')
142
+ check(`cmd 里带进程检查`, /DeepSeek Harness\.exe/.test(text))
143
+ // GIT_SSH_COMMAND 的第一个词必须是可执行程序/完整命令,绝不能以 -i 这种参数开头。
144
+ // 踩过的坑:探测不到 ssh.exe 时拼出 `-i "key" -o …`,git 交给 sh 直接 invalid option。
145
+ if (action !== 'restore' && /GIT_SSH_COMMAND=/.test(text)) {
146
+ const line = text.split('\r\n').find((l) => l.includes('GIT_SSH_COMMAND=')) || ''
147
+ const value = line.slice(line.indexOf('GIT_SSH_COMMAND=') + 'GIT_SSH_COMMAND='.length).trim()
148
+ check(`GIT_SSH_COMMAND 以程序/命令开头(不是裸参数)`,
149
+ !/^-/.test(value.replace(/^\s+/, '')),
150
+ value.slice(0, 120))
151
+ }
152
+ if (action === 'restore') {
153
+ check('还原 cmd 先 DryRun 再确认再真跑', /-DryRun/.test(text) && /set \/p GO=/.test(text) && text.includes('restore.ps1'))
154
+ check('还原 cmd 里写着快照地址', Boolean(latestSnapshot) && text.includes(latestSnapshot), latestSnapshot || '(status 没给快照)')
155
+ check('还原 cmd 把 -BackupDir 明写出来', text.includes(`-BackupDir "${latestSnapshot}"`), latestSnapshot || '(无)')
156
+ check('prepare(restore) 响应里带快照字段', Boolean(payload.backup && payload.backup.dir), JSON.stringify(payload.backup || null))
157
+ } else {
158
+ check(`cmd 里调的是 sync.ps1 ${action}`, new RegExp(`sync\\.ps1".*${action}`).test(text))
159
+ if (action === 'pull') {
160
+ // pull 会覆盖本机配置,脚本必须在真跑之前要一次 y 确认
161
+ check('pull cmd 里有确认守卫(set /p GO=)', /set \/p GO=/.test(text))
162
+ check('pull cmd 说明"会覆盖本机配置"', text.includes('覆盖本机配置'))
163
+ check('prepare(pull) 返回 warnings(本机领先时提示别点错)',
164
+ Array.isArray(payload.warnings) && payload.warnings.length > 0,
165
+ JSON.stringify(payload.warnings || null))
166
+ } else {
167
+ check(`prepare(${action}) 不需要确认守卫`, !/set \/p GO=/.test(text))
168
+ }
169
+ check(`prepare(${action}) 给了中文标签`, typeof payload.label === 'string' && /[\u4e00-\u9fa5]/.test(payload.label), payload.label || '(无)')
170
+ check(`${action} cmd 用中文写动作名`,
171
+ text.includes(action === 'push' ? '推送' : '拉取'),
172
+ action)
173
+ }
174
+ check('cmd 用的是 CRLF', text.includes('\r\n'))
175
+ restoreCmd(payload.path)
176
+ }
177
+ }
178
+
179
+ // 一键生成三个:一次 POST 写出三份,且各自内容正确
180
+ const allRes = await call('/config-sync/prepare', {
181
+ method: 'POST',
182
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
183
+ body: JSON.stringify({ action: 'all' }),
184
+ })
185
+ const allPayload = JSON.parse(allRes.body || '{}')
186
+ check('prepare(all) 返回 200 且 ok', allRes.statusCode === 200 && allPayload.ok === true, allRes.body.slice(0, 160))
187
+ check('prepare(all) 一次写出三份脚本', Array.isArray(allPayload.built) && allPayload.built.length === 3, String(allPayload.built && allPayload.built.length))
188
+ check('prepare(all) 覆盖 push/pull/restore',
189
+ Array.isArray(allPayload.built) && ['push', 'pull', 'restore'].every((a) => allPayload.built.some((b) => b.action === a)),
190
+ JSON.stringify((allPayload.built || []).map((b) => b.action)))
191
+ check('prepare(all) 三份文件都真实存在',
192
+ Array.isArray(allPayload.built) && allPayload.built.every((b) => existsSync(b.path || '')),
193
+ JSON.stringify((allPayload.built || []).map((b) => existsSync(b.path || ''))))
194
+ check('prepare(all) 里 restore 那份带快照地址',
195
+ Array.isArray(allPayload.built) && allPayload.built.some((b) => b.action === 'restore' && b.backup && b.backup.dir),
196
+ JSON.stringify((allPayload.built || []).filter((b) => b.action === 'restore').map((b) => b.backup)))
197
+ for (const b of (allPayload.built || [])) restoreCmd(b.path)
198
+ } else {
199
+ // 本机还没有仓库内容:prepare 的正确预期不是「必定写出脚本」,而是「按云端空不空分流」——
200
+ // 云端也空 → 只生成推送(那次就是初始化推送);云端有内容 → 拒绝推送、只放行拉取。
201
+ const cloudEmpty = body.repo?.remoteEmpty === true
202
+ const pPush = await call('/config-sync/prepare', {
203
+ method: 'POST',
204
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
205
+ body: JSON.stringify({ action: 'push' }),
206
+ })
207
+ const pushPayload = JSON.parse(pPush.body || '{}')
208
+ if (cloudEmpty) {
209
+ check('两边都空:prepare(push) 放行(走初始化推送)', pPush.statusCode === 200 && pushPayload.ok === true, pPush.body.slice(0, 160))
210
+ check('两边都空:生成的推送 cmd 带初始化提示',
211
+ existsSync(pushPayload.path || '') && readFileSync(pushPayload.path, 'utf8').includes('sync.ps1'),
212
+ pushPayload.path || '(无路径)')
213
+ if (existsSync(pushPayload.path || '')) restoreCmd(pushPayload.path)
214
+ } else {
215
+ check('云端有内容:prepare(push) 被拒,并指向「先拉取」',
216
+ pPush.statusCode === 400 && /云端仓库已经有内容/.test(pushPayload.error || ''),
217
+ pPush.body.slice(0, 160))
218
+ }
219
+ const pPull = await call('/config-sync/prepare', {
220
+ method: 'POST',
221
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
222
+ body: JSON.stringify({ action: 'pull' }),
223
+ })
224
+ const pullPayload = JSON.parse(pPull.body || '{}')
225
+ if (cloudEmpty) {
226
+ check('两边都空:prepare(pull) 被拒(没有东西可拉)',
227
+ pPull.statusCode === 400 && /连不上云端|云端仓库已经有内容|空/.test(pullPayload.error || ''),
228
+ pPull.body.slice(0, 160))
229
+ } else {
230
+ check('云端有内容:prepare(pull) 放行', pPull.statusCode === 200 && pullPayload.ok === true, pPull.body.slice(0, 160))
231
+ if (existsSync(pullPayload.path || '')) {
232
+ check('pull cmd 里有确认守卫(set /p GO=)', /set \/p GO=/.test(readFileSync(pullPayload.path, 'utf8')))
233
+ check('cmd 用的是 CRLF', readFileSync(pullPayload.path, 'utf8').includes('\r\n'))
234
+ restoreCmd(pullPayload.path)
235
+ }
236
+ }
237
+ const pAll = await call('/config-sync/prepare', {
238
+ method: 'POST',
239
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
240
+ body: JSON.stringify({ action: 'all' }),
241
+ })
242
+ const allP = JSON.parse(pAll.body || '{}')
243
+ const acts = (allP.built || []).map((b) => b.action)
244
+ check('prepare(all) 按状态组合脚本(两边空→推送+还原;否则→拉取+还原)',
245
+ pAll.statusCode === 200
246
+ && (cloudEmpty ? acts.includes('push') && !acts.includes('pull') : acts.includes('pull') && !acts.includes('push')),
247
+ JSON.stringify(acts))
248
+ check('prepare(all) 带上 initPush 标记(面板据此显示「初始化推送」)',
249
+ Boolean(allP.bootstrap) && allP.bootstrap.initPush === cloudEmpty,
250
+ JSON.stringify(allP.bootstrap && { initPush: allP.bootstrap.initPush }))
251
+ for (const b of (allP.built || [])) restoreCmd(b.path)
252
+ }
253
+
254
+ const cross = await call('/config-sync/prepare', {
255
+ method: 'POST',
256
+ headers: { host: 'localhost:3080', origin: 'https://evil.example', 'content-type': 'application/json' },
257
+ body: JSON.stringify({ action: 'push' }),
258
+ })
259
+ check('跨站请求被拒(403)', cross.statusCode === 403, String(cross.statusCode))
260
+
261
+ const bad = await call('/config-sync/prepare', {
262
+ method: 'POST',
263
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
264
+ body: JSON.stringify({ action: 'delete-everything' }),
265
+ })
266
+ check('非法 action 被拒(400)', bad.statusCode === 400, String(bad.statusCode))
267
+
268
+ // --- 云端仓库设置:展示字段 + 保存校验(只写本机设置文件,不动 git remote) ---
269
+ check('status 带回远端地址与私钥字段',
270
+ Boolean(body.remote && typeof body.remote.url === 'string' && typeof body.remote.sshKey === 'string' && body.remote.settingsPath),
271
+ JSON.stringify(body.remote && { url: body.remote.url, key: body.remote.sshKey, from: body.remote.sshKeyFrom }))
272
+ check('status 说得出云端仓库是否已配置', Boolean(body.remote) && typeof body.remote.configured === 'boolean', String(body.remote && body.remote.configured))
273
+ check('status 的私钥来源可解释', Boolean(body.remote && ['settings', 'default', 'none'].includes(body.remote.sshKeyFrom)), body.remote && body.remote.sshKeyFrom)
274
+
275
+ const settingsFile = body.remote.settingsPath
276
+ const prevSettings = existsSync(settingsFile) ? readFileSync(settingsFile, 'utf8') : null
277
+ const putSettings = (payload) => call('/config-sync/settings', {
278
+ method: 'POST',
279
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
280
+ body: JSON.stringify(payload),
281
+ })
282
+
283
+ // 非法地址
284
+ const badUrl = await putSettings({ remoteUrl: 'ftp://x/y', sshKey: body.remote.sshKey })
285
+ check('非法远端地址被拒(400)', badUrl.statusCode === 400, String(badUrl.statusCode))
286
+
287
+ // 不存在的私钥
288
+ const badKey = await putSettings({ remoteUrl: body.remote.url, sshKey: 'C:\\nope\\no.key' })
289
+ check('不存在的私钥被拒(400)', badKey.statusCode === 400, String(badKey.statusCode))
290
+
291
+ // 合法保存:沿用当前地址,所以不会触发 git remote set-url(自检不该改用户仓库)
292
+ const okSave = await putSettings({ remoteUrl: body.remote.url, sshKey: body.remote.sshKey })
293
+ const okPayload = JSON.parse(okSave.body || '{}')
294
+ check('合法设置保存成功', okSave.statusCode === 200 && okPayload.ok === true, okSave.body.slice(0, 160))
295
+ check('保存后不回写非当前地址(gitRemoteSet=false,自检不动仓库)', okPayload.gitRemoteSet === false, String(okPayload.gitRemoteSet))
296
+ check('保存后设置文件落盘', existsSync(settingsFile), settingsFile)
297
+ check('设置文件含 remoteUrl 字段', existsSync(settingsFile) && readFileSync(settingsFile, 'utf8').includes('remoteUrl'))
298
+
299
+ // 保存后再生成一次 push,确认私钥被接进脚本(此时设置文件里的 sshKey 已生效)
300
+ const again = await call('/config-sync/prepare', {
301
+ method: 'POST',
302
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
303
+ body: JSON.stringify({ action: 'push' }),
304
+ })
305
+ const againPayload = JSON.parse(again.body || '{}')
306
+ if (repoReady) {
307
+ check('保存后再生成 push 成功', again.statusCode === 200 && againPayload.ok === true, again.body.slice(0, 160))
308
+ if (existsSync(againPayload.path || '')) {
309
+ const text = readFileSync(againPayload.path, 'utf8')
310
+ const keyInFile = okPayload.remote && okPayload.remote.sshKey
311
+ check('push 脚本带 GIT_SSH_COMMAND', text.includes('GIT_SSH_COMMAND'))
312
+ check('push 脚本里的私钥路径与设置一致', Boolean(keyInFile) && text.includes(keyInFile), keyInFile || '(无)')
313
+ restoreCmd(againPayload.path)
314
+ }
315
+ } else {
316
+ check('本机无内容时:保存设置后 push 仍按云端状态分流(不会因为改了设置就放行)',
317
+ (again.statusCode === 200 && againPayload.ok === true) || (again.statusCode === 400 && /云端仓库已经有内容/.test(againPayload.error || '')),
318
+ again.body.slice(0, 160))
319
+ if (existsSync(againPayload.path || '')) restoreCmd(againPayload.path)
320
+ }
321
+
322
+ // 设置里留着一条已失效的路径(目录被移走)时:必须报 exists=false 且不静默回退到自动探测
323
+ {
324
+ const dead = mkdtempSync(join(tmpdir(), 'cfg-sync-dead-'))
325
+ const currentRaw = existsSync(settingsFile) ? readFileSync(settingsFile, 'utf8') : null
326
+ let prev = {}
327
+ try { prev = currentRaw ? JSON.parse(currentRaw) : {} } catch { prev = {} }
328
+ writeFileSync(settingsFile, JSON.stringify({ ...prev, repoPath: dead }, null, 2), 'utf8')
329
+ const st = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
330
+ check('失效路径下 exists=false(不假装仓库在)', st.repo && st.repo.exists === false, JSON.stringify(st.repo && { path: st.repo.path, exists: st.repo.exists, source: st.repo.source }))
331
+ check('失效路径不会被静默换成自动探测的仓库', st.repo && st.repo.source === 'settings', String(st.repo && st.repo.source))
332
+ const blocked = await call('/config-sync/prepare', {
333
+ method: 'POST',
334
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
335
+ body: JSON.stringify({ action: 'restore' }),
336
+ })
337
+ // 路径不存在/还是空目录时按设计是允许生成的(新机器第一步 pull 会自动克隆),
338
+ // 但必须带 bootstrap 说明,不能静默当作仓库已就绪。
339
+ const blockedPayload = JSON.parse(blocked.body || '{}')
340
+ check('失效路径下生成带 bootstrap 提示', blockedPayload.ok === true && Boolean(blockedPayload.bootstrap), blocked.body.slice(0, 160))
341
+ if (currentRaw === null) { try { unlinkSync(settingsFile) } catch { } } else writeFileSync(settingsFile, currentRaw, 'utf8')
342
+ rmSync(dead, { recursive: true, force: true })
343
+ }
344
+
345
+ // 还原设置文件(保存动作会覆盖它,用户可能本来就有内容)
346
+ if (prevSettings === null) { try { unlinkSync(settingsFile) } catch { } }
347
+ else writeFileSync(settingsFile, prevSettings, 'utf8')
348
+
349
+ // --- 仓库路径:可配置、默认只读、非法路径要拦、没配就生成不了 ---
350
+ check('status 带回仓库路径来源', Boolean(body.repo && ['settings', 'config', 'env', 'auto', 'none'].includes(body.repo.source)), body.repo && body.repo.source)
351
+ check('status 说得出仓库是否已配置', Boolean(body.repo) && typeof body.repo.configured === 'boolean', String(body.repo && body.repo.configured))
352
+
353
+ const badRepo = await putSettings({ repoPath: 'C:\\nope\\not-a-repo' })
354
+ // 新机器上仓库还没克隆时,这个路径本来就不存在 —— 允许保存(等着首次拉取去克隆),不再当错误拦。
355
+ check('不存在的仓库路径可以保存(待克隆目标)', badRepo.statusCode === 200, String(badRepo.statusCode))
356
+
357
+ // 「像仓库的子目录」(有内容但不是仓库)必须被拒;仓库为空时那个子目录可能压根不存在,
358
+ // 不存在的路径按设计允许保存(等首次拉取去建),这时只做 SKIP,不当失败。
359
+ const notRepoDir = body.repo.path ? body.repo.path + '\\profile' : 'C:\\Windows'
360
+ const notRepo = await putSettings({ repoPath: notRepoDir })
361
+ if (existsSync(notRepoDir)) {
362
+ check('不像仓库的目录被拒(400)', notRepo.statusCode === 400, String(notRepo.statusCode))
363
+ } else {
364
+ console.log(` [SKIP] 不像仓库的目录被拒 — ${notRepoDir} 不存在(非空目录才该被拒)`)
365
+ }
366
+
367
+ const okRepo = await putSettings({ repoPath: body.repo.path })
368
+ const okRepoPayload = JSON.parse(okRepo.body || '{}')
369
+ check('合法仓库路径保存成功', okRepo.statusCode === 200 && okRepoPayload.ok === true, okRepo.body.slice(0, 160))
370
+ check('保存后设置文件里出现 repoPath', existsSync(settingsFile) && readFileSync(settingsFile, 'utf8').includes('repoPath'))
371
+
372
+ // 还原设置文件(保存动作会覆盖它,用户可能本来就有内容)
373
+ if (prevSettings === null) { try { unlinkSync(settingsFile) } catch { } }
374
+ else writeFileSync(settingsFile, prevSettings, 'utf8')
375
+
376
+ // --- 同步内容勾选(scope):默认全勾;勾选落盘到本机 config-sync-scope.json(不进仓库) ---
377
+ // 这里会真的写用户的 scope 文件,所以先备份、断言完原样还原(和上面设置文件同一套做法)。
378
+ const dshHomeDir = dirname(settingsFile)
379
+ const scopeFile = join(dshHomeDir, 'config-sync-scope.json')
380
+ const prevScope = existsSync(scopeFile) ? readFileSync(scopeFile, 'utf8') : null
381
+ const scopeGet = await call('/config-sync/scope', { headers: { host: 'localhost:3080' } })
382
+ const scopeBody = JSON.parse(scopeGet.body || '{}')
383
+ check('scope 返回 200', scopeGet.statusCode === 200, String(scopeGet.statusCode))
384
+ check('scope 列出十二组同步内容', Array.isArray(scopeBody.groups) && scopeBody.groups.length === 12, `${(scopeBody.groups || []).length} 组`)
385
+ check('scope 每组都带标题 / 说明 / 明细项',
386
+ (scopeBody.groups || []).every((g) => g && typeof g.title === 'string' && typeof g.desc === 'string' && Array.isArray(g.items)),
387
+ (scopeBody.groups || []).map((g) => g.id).join(', '))
388
+ check('没配过时默认全勾(组与明细都参与同步)', (scopeBody.groups || []).every((g) => g.enabled === true))
389
+ check('deleteCloud 默认关闭(取消勾选不删云端副本)', scopeBody.deleteCloud === false)
390
+ check('scope 带回本机文件路径(面板要显示出来)', Boolean(scopeBody.path && scopeBody.path.endsWith('config-sync-scope.json')), scopeBody.path || '(空)')
391
+
392
+ // 挑一个「本机真实存在、且允许单独排除」的明细项来测组内排除(不能用编出来的名字:
393
+ // 服务端会把不存在的排除项清掉,否则以后勾不回来——那反而会被判失败)
394
+ const exTarget = (scopeBody.groups || [])
395
+ .filter((g) => g.id !== 'skills')
396
+ .map((g) => ({ group: g.id, item: (g.items || []).find((i) => i.excludable !== false) }))
397
+ .find((x) => Boolean(x.item)) || null
398
+ const groupsPayload = { skills: { enabled: false, excluded: [] } }
399
+ if (exTarget) groupsPayload[exTarget.group] = { enabled: true, excluded: [exTarget.item.id] }
400
+ const scopePost = await call('/config-sync/scope', {
401
+ method: 'POST',
402
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
403
+ body: JSON.stringify({ deleteCloud: true, groups: groupsPayload }),
404
+ })
405
+ const scopePostBody = JSON.parse(scopePost.body || '{}')
406
+ check('scope 保存返回 ok', scopePost.statusCode === 200 && scopePostBody.ok === true, scopePost.body.slice(0, 160))
407
+ check('scope 落盘到本机 config-sync-scope.json', existsSync(scopeFile), scopeFile)
408
+ check('落盘记住取消的组、组内排除项与 deleteCloud',
409
+ existsSync(scopeFile) && (() => {
410
+ try {
411
+ const o = JSON.parse(readFileSync(scopeFile, 'utf8'))
412
+ const okGroup = o.deleteCloud === true && o.groups?.skills?.enabled === false
413
+ const okItem = !exTarget || (Array.isArray(o.groups?.[exTarget.group]?.excluded) && o.groups[exTarget.group].excluded.includes(exTarget.item.id))
414
+ return okGroup && okItem
415
+ } catch { return false }
416
+ })(), scopeFile)
417
+ check('全勾的组不写进文件(默认就是全勾,文件只留差异)',
418
+ existsSync(scopeFile) && !readFileSync(scopeFile, 'utf8').includes('"storages-record"'), scopeFile)
419
+ check('不存在的排除项会被清掉(免得以后看不见却一直挡着同步)',
420
+ existsSync(scopeFile) && (() => {
421
+ try {
422
+ const o = JSON.parse(readFileSync(scopeFile, 'utf8'))
423
+ const ids = []
424
+ for (const [id, g] of Object.entries(o.groups || {})) for (const x of (g.excluded || [])) ids.push(`${id}:${x}`)
425
+ const real = new Set()
426
+ for (const g of (scopeBody.groups || [])) for (const i of (g.items || [])) real.add(`${g.id}:${i.id}`)
427
+ return ids.every((x) => real.has(x))
428
+ } catch { return false }
429
+ })(), scopeFile)
430
+ const scopeAfter = JSON.parse((await call('/config-sync/scope', { headers: { host: 'localhost:3080' } })).body || '{}')
431
+ check('读回来的状态与保存的一致',
432
+ (scopeAfter.groups || []).some((g) => g.id === 'skills' && g.enabled === false)
433
+ && (!exTarget || (scopeAfter.groups || []).some((g) => g.id === exTarget.group && g.items.some((i) => i.id === exTarget.item.id && i.enabled === false))),
434
+ (scopeAfter.groups || []).map((g) => `${g.id}:${g.enabled}`).join(', '))
435
+ if (prevScope === null) { try { unlinkSync(scopeFile) } catch { } } else writeFileSync(scopeFile, prevScope, 'utf8')
436
+
437
+ // --- 同步冲突清单:pull 被本机文件挡住时,脚本写清单、面板读清单、用户逐项选 ---
438
+ const conflictFile = join(dshHomeDir, 'sync-conflicts.json')
439
+ const prevConflict = existsSync(conflictFile) ? readFileSync(conflictFile, 'utf8') : null
440
+ // 真机上可能正躺着一份待处理的清单(那是用户的数据):先挪开再测,finally 原样放回
441
+ if (prevConflict !== null) { try { unlinkSync(conflictFile) } catch { } }
442
+ try {
443
+ const confEmpty = JSON.parse((await call('/config-sync/conflict', { headers: { host: 'localhost:3080' } })).body || '{}')
444
+ check('冲突接口:没有清单时 exists=false,不报错', confEmpty.ok === true && confEmpty.exists === false,
445
+ `exists=${confEmpty.exists}`)
446
+
447
+ // 备份目录:本机 / 云端两份副本分目录存,同一相对路径一一对应
448
+ const backupRoot = join(dshHomeDir, 'backups', 'conflict-selftest-拉取冲突-Pull-conflict')
449
+ mkdirSync(join(backupRoot, '本机-Local', 'mnemon'), { recursive: true })
450
+ mkdirSync(join(backupRoot, '云端-Cloud', 'mnemon'), { recursive: true })
451
+ mkdirSync(join(backupRoot, '本机-Local', '__selftest-probe__'), { recursive: true })
452
+ mkdirSync(join(backupRoot, '云端-Cloud', '__selftest-probe__'), { recursive: true })
453
+ writeFileSync(join(backupRoot, '本机-Local', 'mnemon', 'a.json'), 'LOCAL-COPY')
454
+ writeFileSync(join(backupRoot, '云端-Cloud', 'mnemon', 'a.json'), 'CLOUD-COPY')
455
+ writeFileSync(join(backupRoot, '本机-Local', '__selftest-probe__', 'probe.txt'), 'FROM-LOCAL')
456
+ writeFileSync(join(backupRoot, '云端-Cloud', '__selftest-probe__', 'probe.txt'), 'FROM-CLOUD')
457
+ writeFileSync(join(backupRoot, '说明-README.txt'), 'DSH 配置同步 —— 拉取冲突备份\r\n', 'utf8')
458
+ const probeDst = join(repoArg, '__selftest-probe__', 'probe.txt')
459
+
460
+ writeFileSync(conflictFile, JSON.stringify({
461
+ at: '2026-11-12 20:05:00',
462
+ repo: repoArg,
463
+ head: 'aaaaaaa',
464
+ remoteHead: 'bbbbbbb',
465
+ backupDir: backupRoot,
466
+ items: [
467
+ { path: 'mnemon/data/a.json', kind: 'untracked', localSize: 12, remoteSize: 20, binary: false, localPreview: 'L1', remotePreview: 'R1', localSaved: true, cloudSaved: true, choice: '' },
468
+ { path: '__selftest-probe__/probe.txt', kind: 'modified', localSize: 10, remoteSize: 10, binary: false, localPreview: 'LP', remotePreview: 'RP', localSaved: true, cloudSaved: true, choice: '' },
469
+ ],
470
+ }, null, 2), 'utf8')
471
+
472
+ const confGet = JSON.parse((await call('/config-sync/conflict', { headers: { host: 'localhost:3080' } })).body || '{}')
473
+ check('冲突清单:GET 带回条目、两侧预览、备份目录与两份副本标记',
474
+ confGet.ok === true && confGet.exists === true && (confGet.items || []).length === 2
475
+ && confGet.items[0].localPreview === 'L1' && confGet.items[0].remotePreview === 'R1'
476
+ && confGet.items[0].localSaved === true && confGet.items[0].cloudSaved === true
477
+ && String(confGet.backupDir || '').endsWith('拉取冲突-Pull-conflict'),
478
+ `${(confGet.items || []).length} 项`)
479
+
480
+ const confPost = JSON.parse((await call('/config-sync/conflict', {
481
+ method: 'POST',
482
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
483
+ body: JSON.stringify({ items: [{ path: 'mnemon/data/a.json', choice: 'cloud' }] }),
484
+ })).body || '{}')
485
+ check('冲突清单:POST 保存选择(只覆盖传进来的项)',
486
+ confPost.ok === true && confPost.total === 2 && confPost.chosen === 1 && confPost.pending === 1,
487
+ `total=${confPost.total} chosen=${confPost.chosen} pending=${confPost.pending}`)
488
+ const confOnDisk = JSON.parse(readFileSync(conflictFile, 'utf8'))
489
+ check('冲突清单:选择落盘,未传的项保持原值',
490
+ confOnDisk.items[0].choice === 'cloud' && confOnDisk.items[1].choice === '')
491
+
492
+ const confUnknown = JSON.parse((await call('/config-sync/conflict', {
493
+ method: 'POST',
494
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
495
+ body: JSON.stringify({ items: [{ path: 'not/in/list.txt', choice: 'cloud' }] }),
496
+ })).body || '{}')
497
+ check('冲突清单:清单外的 path 被忽略(不让面板往 JSON 里塞任意路径)',
498
+ confUnknown.ok === true && confOnDisk.items.every((it) => it.path !== 'not/in/list.txt')
499
+ && JSON.parse(readFileSync(conflictFile, 'utf8')).items.length === 2)
500
+
501
+ // 两份副本都能单独还原:写回的是同一相对路径,来源按 side 选
502
+ const restoreLocal = JSON.parse((await call('/config-sync/conflict', {
503
+ method: 'POST',
504
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
505
+ body: JSON.stringify({ action: 'restore', path: '__selftest-probe__/probe.txt', side: 'local' }),
506
+ })).body || '{}')
507
+ check('冲突清单:还原本机副本(side=local,写回工作区)',
508
+ restoreLocal.ok === true && restoreLocal.side === 'local'
509
+ && existsSync(probeDst) && readFileSync(probeDst, 'utf8') === 'FROM-LOCAL',
510
+ restoreLocal.error || '')
511
+
512
+ const restoreCloud = JSON.parse((await call('/config-sync/conflict', {
513
+ method: 'POST',
514
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
515
+ body: JSON.stringify({ action: 'restore', path: '__selftest-probe__/probe.txt', side: 'cloud' }),
516
+ })).body || '{}')
517
+ check('冲突清单:还原云端副本(side=cloud,写回工作区)',
518
+ restoreCloud.ok === true && restoreCloud.side === 'cloud'
519
+ && existsSync(probeDst) && readFileSync(probeDst, 'utf8') === 'FROM-CLOUD',
520
+ restoreCloud.error || '')
521
+
522
+ const restoreMissing = JSON.parse((await call('/config-sync/conflict', {
523
+ method: 'POST',
524
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
525
+ body: JSON.stringify({ action: 'restore', path: 'mnemon/data/a.json', side: 'cloud' }),
526
+ })).body || '{}')
527
+ check('冲突清单:备份里缺某一侧副本时明确报错,不假装成功',
528
+ restoreMissing.ok === false && /云端副本/.test(String(restoreMissing.error || '')))
529
+
530
+ const confReset = JSON.parse((await call('/config-sync/conflict', {
531
+ method: 'POST',
532
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
533
+ body: JSON.stringify({ action: 'reset' }),
534
+ })).body || '{}')
535
+ check('冲突清单:放弃清单会删掉文件', confReset.ok === true && confReset.cleared === true && !existsSync(conflictFile))
536
+
537
+ const statusConf = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
538
+ check('status 带回冲突概要(面板据此决定是否显示这张卡)',
539
+ statusConf.conflicts && statusConf.conflicts.exists === false && typeof statusConf.conflicts.total === 'number',
540
+ JSON.stringify(statusConf.conflicts || null))
541
+ } finally {
542
+ if (prevConflict === null) { try { unlinkSync(conflictFile) } catch { } } else writeFileSync(conflictFile, prevConflict, 'utf8')
543
+ try { rmSync(join(repoArg, '__selftest-probe__'), { recursive: true, force: true }) } catch { }
544
+ try { rmSync(backupRoot, { recursive: true, force: true }) } catch { }
545
+ }
546
+ // --- 必需组:profile 是 apply 的前置条件(缺了直接 Die),所以不许取消勾选 ---
547
+ const reqPost = await call('/config-sync/scope', {
548
+ method: 'POST',
549
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
550
+ body: JSON.stringify({ deleteCloud: false, groups: { profile: { enabled: false, excluded: ['package.json'] } } }),
551
+ })
552
+ check('必需组不能取消:POST 关掉 profile 也不落盘',
553
+ reqPost.statusCode === 200
554
+ && (!existsSync(scopeFile) || !readFileSync(scopeFile, 'utf8').includes('"profile"')),
555
+ existsSync(scopeFile) ? readFileSync(scopeFile, 'utf8').slice(0, 120) : '(文件不存在)')
556
+ const reqAfter = JSON.parse((await call('/config-sync/scope', { headers: { host: 'localhost:3080' } })).body || '{}')
557
+ const profileGroup = (reqAfter.groups || []).find((g) => g.id === 'profile') || {}
558
+ check('回读里 profile 仍是勾选、并标了 required',
559
+ profileGroup.enabled === true && profileGroup.required === true,
560
+ `enabled=${profileGroup.enabled} required=${profileGroup.required}`)
561
+ check('其余组没有 required 标记(只有真正会报错的那组被钉死)',
562
+ (reqAfter.groups || []).filter((g) => g.id !== 'profile').every((g) => g.required !== true))
563
+ if (prevScope === null) { try { unlinkSync(scopeFile) } catch { } } else writeFileSync(scopeFile, prevScope, 'utf8')
564
+ // D:\dsh-config,所以这里退一步做静态断言——宿主源码里确实有这道守卫,且提示指向面板。
565
+ {
566
+ const here = dirname(fileURLToPath(import.meta.url))
567
+ const src = readFileSync(join(here, '..', 'index.js'), 'utf8')
568
+ check('宿主在没仓库时拒绝生成(有守卫)', src.includes('还没有配置仓库目录'), 'index.js')
569
+ check('守卫提示指向面板「本机仓库」卡,而不是让人去改 cordis.patch.yml',
570
+ /还没有配置仓库目录[\s\S]{0,160}本机仓库/.test(src), 'index.js')
571
+ check('云端仓库没配时也拒绝生成推送/拉取(有守卫)', src.includes('还没有配置云端仓库地址'), 'index.js')
572
+ check('还原不受云端仓库影响(守卫排除 restore)', /action !== 'restore'/.test(src), 'index.js')
573
+ check('仓库没有 origin 时会 remote add(而不是 set-url 失败)', /'remote', 'add', 'origin'/.test(src), 'index.js')
574
+ // 「只装了插件、仓库还没克隆」也要能生成脚本:执行体退回插件自带的 runtime。
575
+ check('生成脚本时执行体有 runtime 兜底', /pluginRoot\(\)[\s\S]{0,80}'runtime'/ .test(src) || /'runtime', name/.test(src), 'index.js')
576
+ check('仓库未克隆时返回 bootstrap 提示', src.includes('bootstrap'), 'index.js')
577
+ // 同一份 selftest 会跑在两种布局里:发布仓库(<root>\tools\ + <root>\runtime\)
578
+ // 和配置仓库里的 plugin\dsh-config-sync\tools\(<root>\sync.ps1 + <root>\tools\)。
579
+ // 所以这里按实际文件探测,而不是写死向下几层。
580
+ const pluginRoot = existsSync(join(here, '..', 'package.json')) ? join(here, '..') : join(here, '..', '..')
581
+ const repoRoot = join(here, '..', '..', '..')
582
+ const packScript = [join(pluginRoot, 'tools', 'pack-plugin.ps1'), join(repoRoot, 'tools', 'pack-plugin.ps1')].find((p) => existsSync(p)) || ''
583
+ check('打包脚本会把 ps1 打进 runtime', Boolean(packScript), packScript || 'tools/pack-plugin.ps1')
584
+ const syncScript = [join(pluginRoot, 'runtime', 'sync.ps1'), join(pluginRoot, 'sync.ps1'), join(repoRoot, 'runtime', 'sync.ps1')].find((p) => existsSync(p)) || ''
585
+ check('sync.ps1 支持首次自动初始化仓库', Boolean(syncScript) && readFileSync(syncScript, 'utf8').includes('Initialize-RepoIfNeeded'), syncScript || 'sync.ps1')
586
+ // 冲突备份要「两份副本 + 中英文说明」,面板才能对哪一份都执行还原
587
+ const syncSrc = syncScript ? readFileSync(syncScript, 'utf8') : ''
588
+ check('冲突备份:本机/云端两份副本分目录(目录名带中英文)',
589
+ syncSrc.includes('本机-Local') && syncSrc.includes('云端-Cloud'), syncScript || 'sync.ps1')
590
+ check('冲突备份:云端副本按字节落盘(cat-file blob + cmd 重定向,不过 PowerShell 转码)',
591
+ syncSrc.includes('Save-BlobToFile') && /cat-file blob/.test(syncSrc), 'sync.ps1')
592
+ check('冲突备份:目录名写明用途(拉取冲突 / Pull conflict)',
593
+ syncSrc.includes('拉取冲突-Pull-conflict'), 'sync.ps1')
594
+ check('冲突备份:附中英双语说明文件与清单快照',
595
+ syncSrc.includes('说明-README.txt') && syncSrc.includes('清单-Conflicts.json'), 'sync.ps1')
596
+ check('冲突备份:每项都记录两份副本是否备份成功(面板据此置灰按钮)',
597
+ syncSrc.includes('localSaved') && syncSrc.includes('cloudSaved'), 'sync.ps1')
598
+ // 0.3.42:初始化推送的两个拦路虎(都是实测撞出来的,不能让它们再回来)
599
+ check('初始化推送不会被自己刚写进去的内容挡住(认识同步仓库的标志文件)',
600
+ syncSrc.includes('$isSyncRepo') && syncSrc.includes("Join-Path $RepoRoot 'dsh-sync-common.ps1'"),
601
+ 'sync.ps1 的 stray 判据又只认空目录了')
602
+ const captureScript42 = [join(pluginRoot, 'runtime', 'capture.ps1'), join(pluginRoot, 'capture.ps1'), join(repoRoot, 'capture.ps1')].find((p) => existsSync(p)) || ''
603
+ const cap43 = captureScript42 ? readFileSync(captureScript42, 'utf8') : ''
604
+ check('根外路径体检里没有漏写 $ 的变量((v.Replace 会被当成命令执行)',
605
+ Boolean(cap43) && !/\(\s*v\.Replace\(/.test(cap43) && cap43.includes('($v.Replace('),
606
+ captureScript42 || 'capture.ps1')
607
+ // 重启客户端必须脱离进度窗口的控制台/作业,否则手动关窗口会把刚重启的客户端一起带走。
608
+ const postExit = [join(pluginRoot, 'runtime', 'post-exit.ps1'), join(pluginRoot, 'post-exit.ps1'), join(repoRoot, 'post-exit.ps1')].find((p) => existsSync(p)) || ''
609
+ const postExitSrc = postExit ? readFileSync(postExit, 'utf8') : ''
610
+ check('重启客户端走 explorer 代启(不被进度窗口连坐)',
611
+ postExitSrc.includes('function Start-Detached') && /explorer\.exe/.test(postExitSrc) && postExitSrc.includes('Start-Detached $exe'),
612
+ postExit || 'post-exit.ps1')
613
+
614
+ // 进度窗口的收尾:推送/拉取完成后窗口留着等用户自己关(不自动消失),
615
+ // 且客户端是在这之前由 explorer 拉起来的 —— 所以点 × 关掉窗口不会把客户端带走。
616
+ check('推送/拉取完成后进度窗口不自动关闭(等按键或点 ×)',
617
+ postExitSrc.includes("if ($Mode -eq 'pull' -or $Mode -eq 'push'") && postExitSrc.includes('RawUI.ReadKey'),
618
+ postExit || 'post-exit.ps1')
619
+ check('插件更新完成后窗口同样留着(不与同步窗口两套行为)',
620
+ /-eq 'pull'.*?-eq 'push'.*?-eq 'update'/.test(postExitSrc) && postExitSrc.includes('插件更新已完成'),
621
+ postExit || 'post-exit.ps1')
622
+ check('客户端在窗口开始等待之前就已拉起(关窗口不影响它)',
623
+ postExitSrc.indexOf('if ($Restart) { RestartClient }') > 0
624
+ && postExitSrc.indexOf('if ($Restart) { RestartClient }') < postExitSrc.lastIndexOf('Finish 0'),
625
+ postExit || 'post-exit.ps1')
626
+
627
+ // 执行体优先级:仓库里那份 sync.ps1 是随配置仓库同步来的副本,插件升级后可能还是旧版;
628
+ // 旧版没有冲突清单/exit 6,会把 pull 退回「直接 git pull + 失败回滚」——
629
+ // 真实故障:面板 18 项全选「用云端」,清单读都没读就被旧执行体覆盖回滚。
630
+ check('执行体选择:插件 runtime 优先、仓库副本兜底',
631
+ postExitSrc.includes('function Find-PluginScript')
632
+ && postExitSrc.indexOf('function Find-PluginScript') < postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'"),
633
+ postExit || 'post-exit.ps1')
634
+ check('仓库 sync.ps1 只作兜底(不得排在插件前面)',
635
+ postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'") > 0
636
+ && postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'") < postExitSrc.indexOf('if (-not $sync -and $RepoRoot)'),
637
+ postExit || 'post-exit.ps1')
638
+
639
+ // 更新源自检:raw.githubusercontent.com 在部分网络下直连不通,而 Node 的 fetch 不读系统代理,
640
+ // 超时一到就 abort(面板上那句 "This operation was aborted")。所以内置候选必须带实时反代排在前面。
641
+ // 不要用 jsDelivr 兜清单:它对 @main 这类分支别名缓存很久,发版后仍返回上一版清单(实测 + purge 也没立刻刷新)。
642
+ const indexSrc = readFileSync(join(pluginRoot, 'index.js'), 'utf8')
643
+ check('更新清单带实时反代候选(gh-proxy 排在最前,raw 兜底)',
644
+ indexSrc.includes('gh-proxy.com') && indexSrc.includes('ghfast.top') &&
645
+ indexSrc.includes('UPDATE_MANIFEST_MIRRORS') && !indexSrc.includes('cdn.jsdelivr.net/gh/QcWyGm'),
646
+ 'index.js')
647
+ check('清单按候选依次尝试并汇总失败原因', indexSrc.includes('async function fetchManifestAuto'), 'index.js')
648
+ check('清单超时放宽到 30 秒(raw 慢链路 10 秒会假失败)',
649
+ indexSrc.includes('UPDATE_FETCH_TIMEOUT = 30 * 1000'), 'index.js')
650
+ // 0.3.7:更新拆成「只下载」和「退出后安装」两段。
651
+ // 为什么:DSH 开着的时候覆盖插件目录,宿主会重新同步插件树、把「配置同步」面板卸载掉 ——
652
+ // 用户看到的就是"更新到一半页面自己跳走,还得点回来才能按重启"。所以覆盖必须留到退出之后。
653
+ check('宿主有「只下载」动作(prepare → update-staging,不碰插件目录)',
654
+ indexSrc.includes("action === 'prepare'") && indexSrc.includes('async function downloadPackage') &&
655
+ indexSrc.includes('update-staging'), 'index.js')
656
+ check('只下载会按候选地址逐个试并校验 sha256',
657
+ /function downloadPackage[\s\S]{0,1200}createHash\('sha256'\)/.test(indexSrc), 'index.js')
658
+ check('宿主有「装并重启」动作(install-restart,把本地包交给退出后的脚本)',
659
+ indexSrc.includes("action === 'install-restart'") &&
660
+ /action === 'install-restart'[\s\S]{0,900}-UpdateTgz/.test(indexSrc), 'index.js')
661
+ check('退出后的安装直接吃已下好的本地包(不重复下载)',
662
+ postExitSrc.includes('Test-Path -LiteralPath $UpdateTgz -PathType Leaf'),
663
+ postExit || 'post-exit.ps1')
664
+ check('运行中静默安装仍保留给 CLI/兼容(界面不用它)',
665
+ indexSrc.includes("action === 'install-live'") && indexSrc.includes('function runInstallPlugin'), 'index.js')
666
+ check('只重启走 relaunch(不碰仓库也不装插件)',
667
+ indexSrc.includes("mode: 'relaunch'") && postExitSrc.includes("'relaunch'"), postExit || 'post-exit.ps1')
668
+ const installer = [join(pluginRoot, 'runtime', 'install-plugin.ps1'), join(pluginRoot, 'install-plugin.ps1')].find((p) => existsSync(p)) || ''
669
+ const installerSrc = installer ? readFileSync(installer, 'utf8') : ''
670
+ check('安装器存在并自报结果(RESULT: 行)', Boolean(installer) && installerSrc.includes('RESULT:'), installer || 'runtime/install-plugin.ps1')
671
+ check('安装器覆盖前先备份、写坏能回滚',
672
+ installerSrc.includes('function Restore-Backup') && installerSrc.includes('plugin-{0}-{1}'),
673
+ installer || 'runtime/install-plugin.ps1')
674
+ check('安装器按候选地址逐个下载', installerSrc.includes("-split '\\|'"), installer || 'runtime/install-plugin.ps1')
675
+ const clientSrc = readFileSync(join(pluginRoot, 'client.js'), 'utf8')
676
+ check('面板按钮走「下载更新 → 重启并安装」,不再运行中安装',
677
+ clientSrc.includes("action: 'prepare'") && clientSrc.includes("action: 'install-restart'") &&
678
+ !clientSrc.includes("action: 'install-live'") &&
679
+ clientSrc.includes('重启并安装') && clientSrc.includes('Restart & install'), 'client.js')
680
+ check('面板会展示「已下载,待安装」这一态',
681
+ clientSrc.includes('preparedReady') && clientSrc.includes('已下载,待安装'), 'client.js')
682
+
683
+ // 0.3.8:同步内容勾选 —— 面板写 <DshHome>\config-sync-scope.json,capture/apply 读同一个文件。
684
+ // 关键契约:默认全勾、未勾选一律跳过、deleteCloud 默认关(关着时绝不删云端副本)。
685
+ const pickRuntime = (name) => [join(pluginRoot, 'runtime', name), join(pluginRoot, name)].find((p) => existsSync(p)) || ''
686
+ const commonSrc = pickRuntime('dsh-sync-common.ps1') ? readFileSync(pickRuntime('dsh-sync-common.ps1'), 'utf8') : ''
687
+ const captureSrc = pickRuntime('capture.ps1') ? readFileSync(pickRuntime('capture.ps1'), 'utf8') : ''
688
+ const applySrc = pickRuntime('apply.ps1') ? readFileSync(pickRuntime('apply.ps1'), 'utf8') : ''
689
+ const pickTool = (name) => [join(pluginRoot, 'runtime', 'tools', name), join(pluginRoot, 'tools', name)].find((p) => existsSync(p)) || ''
690
+ const helperSrc = pickTool('fix-session-cwd.mjs') ? readFileSync(pickTool('fix-session-cwd.mjs'), 'utf8') : ''
691
+ // 执行体没跑起来时 PowerShell 只喷红字、$LASTEXITCODE 还是上一条命令残留的 0,
692
+ // 整次同步就被当成成功(写 ok:true + 刷分水岭),本机改动静默滞留。三道锁缺一不可。
693
+ check('调用执行体前压哨兵值,且终止错误被捕获后一律判失败',
694
+ postExitSrc.includes('$LASTEXITCODE = -1')
695
+ && postExitSrc.includes('$invokeOk = $false')
696
+ && /catch \{[\s\S]{0,400}执行体调用异常/.test(postExitSrc)
697
+ && /if \(-not \$invokeOk\)[\s\S]{0,260}\$code = 1/.test(postExitSrc),
698
+ 'post-exit.ps1')
699
+ check('调用执行体前确认文件仍存在(安装覆盖到一半也能拦住)',
700
+ /\$sync = Find-PluginScript 'sync\.ps1'[\s\S]{0,1200}Test-Path -LiteralPath \$sync/.test(postExitSrc),
701
+ 'post-exit.ps1')
702
+ check('同步失败时不刷新同步分水岭(免得失败变成静默漏推)',
703
+ postExitSrc.includes('RestartClient -SkipWatermark:$failed')
704
+ && postExitSrc.includes('function RestartClient([switch]$SkipWatermark)')
705
+ && /if \(-not \$SkipWatermark\)/.test(postExitSrc),
706
+ 'post-exit.ps1')
707
+
708
+ const SCOPE_GROUPS = ['profile', 'prompt', 'skills', 'presets', 'storages-record', 'settings', 'mnemon', 'local-plugins', 'plugin-data', 'extra', 'workspace', 'conversations']
709
+ check('公共脚本提供 scope 读取与判断函数',
710
+ ['Get-SyncScope', 'Test-SyncGroupEnabled', 'Test-SyncItemEnabled', 'Test-SyncDeleteCloud', 'Skip-SyncGroup', 'Skip-SyncItem']
711
+ .every((n) => commonSrc.includes(`function ${n}`)), 'dsh-sync-common.ps1')
712
+ check('scope 文件不存在时按全勾处理(老机器行为不变)',
713
+ commonSrc.includes('config-sync-scope.json') && /function Get-SyncScope[\s\S]{0,700}Test-Path/.test(commonSrc),
714
+ 'dsh-sync-common.ps1')
715
+ check('capture 十组都按勾选判断',
716
+ SCOPE_GROUPS.every((g) => captureSrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)),
717
+ SCOPE_GROUPS.filter((g) => !captureSrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)).join(', ') || 'capture.ps1')
718
+ const EXCLUDABLE = ['skills', 'presets', 'settings', 'local-plugins', 'prompt', 'storages-record', 'plugin-data', 'extra', 'workspace', 'conversations']
719
+ check('capture 组内还能单独排除(skills / presets / settings / local-plugins / prompt / 台账 / 插件数据 / 额外路径 / 工作区 / 会话)',
720
+ EXCLUDABLE.every((g) => captureSrc.includes(`Test-SyncItemEnabled $Scope '${g}'`)),
721
+ EXCLUDABLE.filter((g) => !captureSrc.includes(`Test-SyncItemEnabled $Scope '${g}'`)).join(', ') || 'capture.ps1')
722
+ check('apply 十组都按勾选跳过(未勾选的不还原)',
723
+ SCOPE_GROUPS.every((g) => applySrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)),
724
+ SCOPE_GROUPS.filter((g) => !applySrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)).join(', ') || 'apply.ps1')
725
+ check('deleteCloud 默认关:关着时跳过就只是跳过,不删云端副本',
726
+ /function Skip-SyncGroup[\s\S]{0,400}Test-SyncDeleteCloud/.test(commonSrc)
727
+ && commonSrc.includes('if (-not (Test-SyncDeleteCloud $Scope)) { return }'), 'dsh-sync-common.ps1')
728
+ check('apply 的 -PruneSkills 不会删掉被排除的本机 Skill',
729
+ applySrc.includes("(Test-SyncItemEnabled $Scope 'skills' $_.Name)"), 'apply.ps1')
730
+ check('会话按工作区过滤,且未勾选的会话不会被铺回本机',
731
+ captureSrc.includes('$skipSessDirs') && applySrc.includes('$skipConvDirs'), 'capture/apply')
732
+
733
+ // 0.3.51:插件数据(自动枚举)与额外路径(用户自选),规则落在 config-sync-extra.json
734
+ check('两组 id 进了公共脚本、capture、apply 与面板',
735
+ commonSrc.includes("'plugin-data', 'extra'")
736
+ && captureSrc.includes("Test-SyncGroupEnabled $Scope 'plugin-data'")
737
+ && applySrc.includes("Test-SyncGroupEnabled $Scope 'plugin-data'")
738
+ && indexSrc.includes("id: 'plugin-data'") && indexSrc.includes("id: 'extra'"), 'all')
739
+ check('规则文件:config-sync-extra.json + 排除名单整份替换(空数组也要能生效)',
740
+ commonSrc.includes('config-sync-extra.json')
741
+ && commonSrc.includes("if ($j.pluginData.PSObject.Properties['exclude']) { $pd.exclude = @("), 'dsh-sync-common.ps1')
742
+ check('单文件上限卡在 GitHub 硬限 100MB(配置调大也压回来)',
743
+ commonSrc.includes('$SyncExtraHardMaxBytes = 104857600') && commonSrc.includes('[Math]::Min([int64]$v, [int64]$SyncExtraHardMaxBytes)'), 'dsh-sync-common.ps1')
744
+ check('插件数据按 dav 目录枚举,系统/已覆盖目录进默认 skipDirs',
745
+ commonSrc.includes('function Get-PluginDataSlots') && commonSrc.includes("'profiles', 'skills', '.agent-presets', 'storages'"), 'dsh-sync-common.ps1')
746
+ check('抓取写 manifest(路径占位符化,方便另一台展开)',
747
+ captureSrc.includes("Join-Path $pdDst 'manifest.json'") && captureSrc.includes("src = (ConvertTo-TokenText $slot.src $pdRoots)"), 'capture.ps1')
748
+ check('写回先展开占位符、再逐文件合并并留底',
749
+ /Copy-TreeInto \$slotSrc \$dst \$bk/.test(applySrc) && applySrc.includes('$miss = @(Get-MissingTokens $expanded)'), 'apply.ps1')
750
+ check('面板有 /config-sync/extra-config 接口与规则卡',
751
+ indexSrc.includes("const ROUTE_EXTRA_CONFIG = '/config-sync/extra-config'")
752
+ && indexSrc.includes('async function handleExtraConfig')
753
+ && clientSrc.includes("fetch('/config-sync/extra-config'") && clientSrc.includes('function ExtraCard'), 'index/client')
754
+ check('凭据文件默认不进仓库:*vault* 在名单里,且抓取前按内容嗅探再拦一道',
755
+ commonSrc.includes("'*vault*'") && indexSrc.includes("'*vault*'")
756
+ && commonSrc.includes('function Test-SyncExtraSecret') && commonSrc.includes('$SyncExtraSecretMarkers')
757
+ && captureSrc.includes('Get-SyncExtraSecretSkips'), 'common/index/capture')
758
+ check('符号链接/junction 不跟进(插件目录常把外部数据链进来)',
759
+ commonSrc.includes('[IO.FileAttributes]::ReparsePoint'), 'dsh-sync-common.ps1')
760
+ check('「插件数据与额外路径」卡先只读,点「修改」才能改、点「保存」才落盘',
761
+ clientSrc.includes('readOnly: !editing')
762
+ && clientSrc.includes('disabled: !editing')
763
+ && /const \[editing, setEditing\] = react\.useState\(false\)[\s\S]{0,1200}setEditing\(false\)/.test(clientSrc)
764
+ && clientSrc.includes('M(\'取消\', \'Cancel\')'), 'client.js')
765
+ const rmIdx = clientSrc.indexOf('() => removePath')
766
+ const rmBefore = rmIdx >= 0 ? clientSrc.slice(rmIdx - 180, rmIdx) : ''
767
+ check('额外路径的「移除」按钮只在编辑态出现(只读时整行只剩名字和路径)',
768
+ rmBefore.includes("editing ? h('button'") && !rmBefore.includes('disabled: !editing'), 'client.js')
769
+ check('工作区登记表也跟着过滤(不会「数据跳过了、登记表还写着」)',
770
+ captureSrc.includes("$entries = @($entries | Where-Object { Test-SyncItemEnabled $Scope 'workspace' $_.Id })")
771
+ && applySrc.includes("$plan = @($plan | Where-Object { Test-SyncItemEnabled $Scope 'workspace' $_.Id })"),
772
+ 'capture/apply')
773
+
774
+ // apply 的非零退出码等同于「拉取失败」,post-exit 会据此回滚;
775
+ // 所以「没有 pnpm」这种环境差异不能让整次拉取失败 —— 只要 node_modules 在,依赖就是好的。
776
+ check('依赖已就绪时 apply 不因缺少 pnpm 而失败退出',
777
+ applySrc.includes("Join-Path $ProfileDir 'node_modules'")
778
+ && applySrc.includes('$skipBecauseReady'), 'apply.ps1')
779
+ check('node_modules 不存在时仍然明确报错(不静默放过)',
780
+ /if \(Test-Path -LiteralPath \$nodeModules\)[\s\S]{0,300}exit 1/.test(applySrc), 'apply.ps1')
781
+
782
+ // 登记表:同一路径撞了两台机器各自建的 ID 时,必须保留当前机器在用的 ID,
783
+ // 否则 defaultWorkspaceId 悬空、整张表校验不过(工作区列表空、会话读不出)。
784
+ check('登记表同路径冲突时保留本机 ID(不是仓库 ID)',
785
+ applySrc.includes('$localIdSet')
786
+ && applySrc.indexOf('Where-Object { $localIdSet.ContainsKey($_) }')
787
+ < applySrc.indexOf('Where-Object { $mfIdSet.ContainsKey($_) }'),
788
+ 'apply.ps1')
789
+ check('defaultWorkspaceId 以本机为准(原值还在表里就不动)',
790
+ applySrc.includes('$localDefault')
791
+ && applySrc.includes('$ids -contains $localDefault')
792
+ && applySrc.includes("$localGlobal['defaultWorkspaceId'] = $ids[0]"),
793
+ 'apply.ps1')
794
+
795
+ // 会话还原的前提:能展开 {{APP_ROOT}} 占位符。做不到就别铺 —— 铺了 DSH 一个都不登记,
796
+ // 用户看到的就是「工作区还在、会话全没了」(真实事故)。
797
+ check('node 探测覆盖常见安装位置(不只有 PATH)',
798
+ commonSrc.includes("nodejs\\node.exe")
799
+ && commonSrc.includes('function Get-HostNodeExe'),
800
+ 'dsh-sync-common.ps1')
801
+ check('找不到 Node 时跳过会话还原而不是铺坏文件',
802
+ /if \(\$cwdMap\.Count -gt 0 -or \$projMap\.Count -gt 0\) \{[\s\S]{0,400}跳过会话还原[\s\S]{0,200}return/.test(applySrc),
803
+ 'apply.ps1')
804
+ check('会话还原用的是统一探测到的执行器(Node 或客户端 Electron)',
805
+ applySrc.includes('$nodeRunner = Get-HostNodeRunner $AppRoot')
806
+ && applySrc.includes('$nodeRunner.Electron')
807
+ && commonSrc.includes('function Get-HostNodeRunner'),
808
+ 'apply.ps1')
809
+ // 客户端 Electron 是 GUI 子系统,stdout 抓不到 —— 结果必须落文件,否则面板/日志永远报失败
810
+ check('会话头部修正的结果写成文件(Electron 跑时 stdout 抓不到)',
811
+ helperSrc.includes('const outPath = process.argv[3]')
812
+ && helperSrc.includes('emit(result)')
813
+ && applySrc.includes('$resultPath'),
814
+ 'fix-session-cwd.mjs')
815
+ check('面板有「同步内容」卡:逐组勾选 + 展开明细 + deleteCloud 开关',
816
+ clientSrc.includes('function ScopeCard') && clientSrc.includes('callScope(')
817
+ && clientSrc.includes('同步内容') && clientSrc.includes('Sync content')
818
+ && clientSrc.includes('取消勾选时顺手删掉云端副本'), 'client.js')
819
+ // 必需组(profile)三处钉死:脚本侧判断、宿主保存、面板复选框
820
+ check('必需组在脚本侧钉死(手改 JSON 关掉也按开启处理)',
821
+ commonSrc.includes('$SyncRequiredGroups')
822
+ && /function Test-SyncGroupEnabled[\s\S]{0,260}Test-SyncRequiredGroup/.test(commonSrc),
823
+ 'dsh-sync-common.ps1')
824
+ check('必需组在宿主侧钉死(保存时拒绝写入关闭状态)',
825
+ indexSrc.includes('SCOPE_REQUIRED_GROUPS')
826
+ && /for \(const \[id, g\] of Object\.entries\(groupsIn\)\)[\s\S]{0,260}scopeGroupRequired\(id\)\) continue/.test(indexSrc),
827
+ 'index.js')
828
+ check('必需组在面板上不可勾掉(复选框禁用 + 标注)',
829
+ clientSrc.includes('g.required === true') && clientSrc.includes('必需内容'), 'client.js')
830
+ // 只读优先:不做「勾一下就写盘」,要先点「修改」、再点「保存」
831
+ check('面板默认只读:勾选前必须先点「修改」',
832
+ clientSrc.includes('const [editing, setEditing]')
833
+ && clientSrc.includes("disabled: busy || !editing")
834
+ && clientSrc.includes("M('修改', 'Edit')")
835
+ && /onClick: \(\) => save\(state\)/.test(clientSrc), 'client.js')
836
+ // 展开/收起改成点整行,单独的「明细」按钮要消失
837
+ check('取消「明细」按钮:展开收起靠点当前行',
838
+ !clientSrc.includes("M('明细', 'Details')")
839
+ && clientSrc.includes('onClick: canExpand')
840
+ && clientSrc.includes("expanded ? '▾' : '▸'"), 'client.js')
841
+ check('同步内容卡与问题反馈卡挂在页面最下面(其后不再有别的 Section)', (() => {
842
+ // 顺序:概览 → 同步目标 → 自动化与插件更新 → 退出后执行 → 还原备份 → 同步内容 → 问题反馈;
843
+ // 判据是「顺序」而不是写死紧跟,中间还会插卡(本机路径就插在同步目标之前)。
844
+ const order = ["概览", "同步目标", "自动化与插件更新", "退出后执行", "还原备份", "同步内容", "问题反馈"]
845
+ .map((k) => ({ k, at: clientSrc.indexOf(`Section(M('${k}'`) }))
846
+ if (order.some((p) => p.at < 0)) return false
847
+ if (!order.every((p, i) => (i === 0 ? true : p.at > order[i - 1].at))) return false
848
+ // 问题反馈必须是最后一个 Section
849
+ const tail = clientSrc.slice(order[order.length - 1].at + 1)
850
+ return !/Section\(M\(/.test(tail)
851
+ })(), 'client.js')
852
+ // 「还原备份」卡:地址可改(留空=默认)、列出快照、点「立即还原」先出确认框再排队
853
+ check('控件:还原备份卡有备份目录、快照列表与立即还原',
854
+ clientSrc.includes('backupRoot') && clientSrc.includes('backup.snapshots')
855
+ && clientSrc.includes("M('立即还原', 'Restore now')") && clientSrc.includes("M('还原备份', 'Restore backup')"), 'client.js')
856
+ check('控件:还原先弹确认(差异预览)再排队,不是点了就动手',
857
+ clientSrc.includes("action: 'restore-preview'") && clientSrc.includes("action: 'restore-now'")
858
+ && clientSrc.includes('askRestore') && clientSrc.includes('doRestore')
859
+ && clientSrc.includes('pvRemovePlugins') && clientSrc.includes('pvRemoveFiles'), 'client.js')
860
+ check('控件:快照行显示相对时间、类型徽章与内容摘要',
861
+ clientSrc.includes('const rel = (at)') && clientSrc.includes('kindBadge') && clientSrc.includes('snapSummary'), 'client.js')
862
+ check('控件:三类备份各有还原入口,认不出类型的给手动还原指引(不留死路)',
863
+ clientSrc.includes("kindOf(s) === 'plugin' ? M('回滚插件'") && clientSrc.includes("M('还原会话', 'Restore sessions')")
864
+ && clientSrc.includes("M('手动还原', 'How to restore')") && clientSrc.includes('manualTargets'), 'client.js')
865
+
866
+ // 0.3.25 起「还原」与「立即拉取」共用一条流水线:面板排队 → 客户端退出 → 可见进度窗口执行 → 自动重启
867
+ const restoreScript = [join(pluginRoot, 'runtime', 'restore.ps1'), join(repoRoot, 'restore.ps1')].find((p) => existsSync(p)) || ''
868
+ const restoreSrc = restoreScript ? readFileSync(restoreScript, 'utf8') : ''
869
+ check('post-exit 有 restore 分支:执行体是 restore.ps1,profile 带 -RollbackToPoint、其它类型带 -SnapshotKind',
870
+ postExitSrc.includes("if ($Mode -eq 'restore')")
871
+ && postExitSrc.includes("Find-PluginScript 'restore.ps1'")
872
+ && postExitSrc.includes('RollbackToPoint')
873
+ && postExitSrc.includes("$rargs['SnapshotKind'] = $SnapshotKind"), postExit || 'post-exit.ps1')
874
+ check('post-exit 的 restore 分支沿用同一套返回码判据(哨兵 -1 + 没跑完即失败)',
875
+ /if \(\$Mode -eq 'restore'\)[\s\S]{0,3000}?\$LASTEXITCODE = -1/.test(postExitSrc)
876
+ && /if \(\$Mode -eq 'restore'\)[\s\S]{0,3500}?执行体没有正常跑完/.test(postExitSrc),
877
+ 'post-exit.ps1')
878
+ check('post-exit 的 restore 分支有专属收尾文案',
879
+ postExitSrc.includes('完成(已还原)') && postExitSrc.includes('还原失败'), 'post-exit.ps1')
880
+ check('restore.ps1 提供 -RollbackToPoint 时点回退',
881
+ restoreSrc.includes('[switch]$RollbackToPoint') && restoreSrc.includes('3.5 时点回退'), 'restore.ps1')
882
+ check('时点回退:撤走的插件只删 junction 链接(不穿进去删目标)',
883
+ /if \(\$item\.LinkType\)[\s\S]{0,220}\[IO\.Directory\]::Delete/.test(restoreSrc.replace(/\r/g, '')), 'restore.ps1')
884
+ check('时点回退:写 rollback-manifest.json(可再还原,不留糊涂账)',
885
+ restoreSrc.includes('rollback-manifest.json') && restoreSrc.includes('rollback\\files'), 'restore.ps1')
886
+ check('时点回退:相对路径基准先归一成完整路径(避免 8.3 短名算错)',
887
+ restoreSrc.includes('(Get-Item -LiteralPath $ProfileDir -Force).FullName'), 'restore.ps1')
888
+ check('备份列表带插件数(面板要显示 N 个插件)',
889
+ indexSrc.includes('plugins = Object.keys(pkg?.dependencies') && indexSrc.includes('plugins: x.plugins'), 'index.js')
890
+ check('技能市场台账的勾选项 id 用文件名,不是整个 {id,src} 对象(否则落盘成 [object Object])',
891
+ /items: ledger\.map\(\(f\) => \(\{ id: f\.id, label: f\.id \}\)\)/.test(indexSrc), 'index.js')
892
+ check('restore-now 复用 spawnWatcher,并把快照目录与类型带进执行体',
893
+ /action === 'restore-now'[\s\S]{0,1200}?spawnWatcher\(\{[\s\S]{0,240}?mode: 'restore'/.test(indexSrc)
894
+ && indexSrc.includes("const extraArgs = ['-BackupDir', snap.dir]")
895
+ && indexSrc.includes("extraArgs.push('-SnapshotKind', snap.kind)")
896
+ && indexSrc.includes("extraArgs.push('-PluginDir', PLUGIN_ROOT)"), 'index.js')
897
+ check('restore.ps1 支持 -SnapshotKind 三型(profile / plugin / session)',
898
+ restoreSrc.includes("ValidateSet('profile', 'plugin', 'session')")
899
+ && restoreSrc.includes("$SnapshotKind -eq 'plugin'")
900
+ && restoreSrc.includes("$SnapshotKind -eq 'session'")
901
+ && restoreSrc.includes('function Copy-Tree'), 'restore.ps1')
902
+ check('快照分类不能只看 package.json(profile 也带 dsh 字段)',
903
+ indexSrc.includes('function classifySnapshot') && indexSrc.includes('/^dsh-profile-/i.test(pkgName)')
904
+ && indexSrc.includes("pkgName === PACKAGE_ID"), 'index.js')
905
+ check('restore-preview 与 prepare 共用同一套快照校验(口径不漂移)',
906
+ indexSrc.includes('function resolveSnapshotDir')
907
+ && (indexSrc.match(/resolveSnapshotDir\(dshHome, body\.backupDir\)/g) || []).length >= 2, 'index.js')
908
+ check('还原不需要仓库也能排队(只动本机快照)',
909
+ /const isRestore = action === 'restore-now'/.test(indexSrc) && /if \(!repo && !isRestore\) throw/.test(indexSrc), 'index.js')
910
+ }
911
+
912
+ // 提交说明:面板里填的那句要进 push 脚本,时间由 sync.ps1 执行时追加
913
+ const noted = await call('/config-sync/prepare', {
914
+ method: 'POST',
915
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
916
+ body: JSON.stringify({ action: 'push', message: '修 侧栏入口 "和" 特殊字符' }),
917
+ })
918
+ const notedPayload = JSON.parse(noted.body || '{}')
919
+ if (repoReady) {
920
+ check('prepare(push) 接受提交说明', noted.statusCode === 200 && notedPayload.ok === true, noted.body.slice(0, 160))
921
+ check('提交说明进了脚本(-Message)', existsSync(notedPayload.path || '') && readFileSync(notedPayload.path, 'utf8').includes('-Message'))
922
+ check('提交说明里的双引号被清洗掉',
923
+ Boolean(notedPayload.message) && !notedPayload.message.includes('"'),
924
+ notedPayload.message || '(无)')
925
+ if (existsSync(notedPayload.path || '')) restoreCmd(notedPayload.path)
926
+ } else if (body.repo?.remoteEmpty === true) {
927
+ // 两边都空:这次带说明的 push 就是初始化推送,放行;说明字段照样要清洗
928
+ check('两边都空:带说明的 push 放行(走初始化推送)',
929
+ noted.statusCode === 200 && notedPayload.ok === true, noted.body.slice(0, 160))
930
+ check('提交说明里的双引号被清洗掉',
931
+ Boolean(notedPayload.message) && !notedPayload.message.includes('"'),
932
+ notedPayload.message || '(无)')
933
+ if (existsSync(notedPayload.path || '')) restoreCmd(notedPayload.path)
934
+ check('提交说明清洗在源码里(去双引号)',
935
+ /\$\{.*message.*\}/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8'))
936
+ || /replace\(\/\["\\r\\n\]/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8')),
937
+ 'index.js')
938
+ } else {
939
+ // 仓库还没内容、云端已有内容时,带说明的 push 同样该被拒;说明字段的清洗逻辑用静态断言兜住
940
+ check('本机无内容时:带说明的 push 仍被拒(不被说明字段绕过门禁)',
941
+ noted.statusCode === 400 && /云端仓库已经有内容/.test(notedPayload.error || ''),
942
+ noted.body.slice(0, 160))
943
+ check('提交说明清洗在源码里(去双引号)',
944
+ /\$\{.*message.*\}/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8'))
945
+ || /replace\(\/\["\\r\\n\]/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8')),
946
+ 'index.js')
947
+ }
948
+ const pullNote = await call('/config-sync/prepare', {
949
+ method: 'POST',
950
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
951
+ body: JSON.stringify({ action: 'pull', message: '不该进拉取脚本' }),
952
+ })
953
+ const pullNotePayload = JSON.parse(pullNote.body || '{}')
954
+ if (pullNote.statusCode === 400) {
955
+ // 两边都空:拉取直接被拒(没有内容可拉),说明字段自然也进不了脚本
956
+ check('两边都空时带说明的拉取同样被拒(说明字段绕不过门禁)',
957
+ /没有内容可拉|连不上云端/.test(pullNotePayload.error || ''), pullNotePayload.error || '(无错误)')
958
+ } else {
959
+ check('拉取脚本不吃提交说明',
960
+ existsSync(pullNotePayload.path || '') && !readFileSync(pullNotePayload.path, 'utf8').includes('不该进拉取脚本'),
961
+ pullNotePayload.path || '(无)')
962
+ if (existsSync(pullNotePayload.path || '')) restoreCmd(pullNotePayload.path)
963
+ }
964
+
965
+ // 配置仓库根目录那 6 个执行体,是「插件还没装 / 正在升级」时的兜底副本。
966
+ // 它们一直靠人工同步,结果漂成半新半旧:sync/apply/common/post-exit 已升到 0.3.23,
967
+ // capture/restore 还停在两天前的旧版 —— 平时不显形,只有 pull 真正走进「仓库副本」
968
+ // 那条兜底路才会跑到旧逻辑。所以按字节比对,漂了就报,不再指望人记得。
969
+ console.log('')
970
+ console.log('== 配置仓库执行体副本一致性 ==')
971
+ const execNames = ['apply.ps1', 'capture.ps1', 'dsh-sync-common.ps1', 'post-exit.ps1', 'restore.ps1', 'sync.ps1']
972
+ // 两种布局都认:发布仓库(<root>\runtime)与配置仓库里的 plugin\ 镜像(<root>\runtime)
973
+ const hereSelf = dirname(fileURLToPath(import.meta.url))
974
+ const pluginRootSelf = existsSync(join(hereSelf, '..', 'package.json')) ? join(hereSelf, '..') : join(hereSelf, '..', '..')
975
+ const pluginRuntime = join(pluginRootSelf, 'runtime')
976
+ if (!existsSync(repoArg) || !existsSync(pluginRuntime) || !repoReady) {
977
+ console.log(` [SKIP] 没有配置仓库内容(${repoArg},mode=${body.repo?.mode || '?'})或没有插件 runtime,跳过逐字节比对`)
978
+ console.log(' (初始化推送会把这几份副本一起写进仓库,届时断言自动恢复)')
979
+ } else {
980
+ for (const name of execNames) {
981
+ const mirror = join(repoArg, name)
982
+ const source = join(pluginRuntime, name)
983
+ let same = false
984
+ let detail = ''
985
+ if (!existsSync(mirror)) detail = `配置仓库没有 ${name}`
986
+ else if (!existsSync(source)) detail = `插件 runtime 没有 ${name}`
987
+ else {
988
+ same = readFileSync(mirror).equals(readFileSync(source))
989
+ if (!same) detail = `副本 ${readFileSync(mirror).length}B / 正本 ${readFileSync(source).length}B,跑 tools/sync-plugin-mirror.ps1 重新同步`
990
+ }
991
+ check(`执行体副本与插件 runtime 逐字节一致:${name}`, same, detail)
992
+ }
993
+ // tools\fix-session-cwd.mjs 同样是随仓库同步的副本,改了插件忘了同步会静默跑旧逻辑
994
+ const mirrorTool = join(repoArg, 'tools', 'fix-session-cwd.mjs')
995
+ const sourceTool = join(pluginRuntime, 'tools', 'fix-session-cwd.mjs')
996
+ const toolSame = existsSync(mirrorTool) && existsSync(sourceTool) && readFileSync(mirrorTool).equals(readFileSync(sourceTool))
997
+ check('执行体副本与插件 runtime 逐字节一致:tools/fix-session-cwd.mjs', toolSame,
998
+ existsSync(mirrorTool) ? '内容已漂移,跑 tools/sync-plugin-mirror.ps1 重新同步' : '配置仓库没有 tools/fix-session-cwd.mjs')
999
+ }
1000
+
1001
+ // 内置运行时链接修复(0.3.24):客户端升级会清空 resources\runtime,
1002
+ // 装卸插件的 pnpm 调用随即报 MODULE_NOT_FOUND(真正运行时在 ~\.dsh\dsh-runtimes 下)。
1003
+ // apply 每次落地幂等补回 junction,这 4 条断言盯住「函数在、被调用、不覆盖、探针对」。
1004
+ console.log('')
1005
+ console.log('== 内置运行时链接修复 ==')
1006
+ {
1007
+ const commonPath = join(pluginRuntime, 'dsh-sync-common.ps1')
1008
+ const applyPath = join(pluginRuntime, 'apply.ps1')
1009
+ const commonText = existsSync(commonPath) ? readFileSync(commonPath, 'utf8') : ''
1010
+ const applyText = existsSync(applyPath) ? readFileSync(applyPath, 'utf8') : ''
1011
+ check('common 提供 Repair-PrimaryRuntimeLink 函数',
1012
+ /function\s+Repair-PrimaryRuntimeLink\s*\(/.test(commonText),
1013
+ '插件 runtime 的 dsh-sync-common.ps1 里没有该函数')
1014
+ check('apply.ps1 落地时调用该函数(不靠人手补链接)',
1015
+ /Repair-PrimaryRuntimeLink\s+\$AppRoot\s+\$DshHome/.test(applyText),
1016
+ 'apply.ps1 里找不到调用点,升级后链接不会自动补回')
1017
+ check('已有真实运行时目录时绝不覆盖(只告警不重建)',
1018
+ /LinkType/.test(commonText) && /客户端自带运行时目录存在/.test(commonText) && /本次不动/.test(commonText),
1019
+ '缺少 LinkType 判据:可能把客户端自带的真实目录当成链接处理')
1020
+ check('探针落在 pnpm.mjs 本身,不是只看目录存在',
1021
+ /dependencies\\pnpm\\bin\\pnpm\.mjs/.test(commonText),
1022
+ '探针路径不是 pnpm.mjs,运行时缺文件时会被误判为已就绪')
1023
+ }
1024
+
1025
+ // 空白本机仓库 → 只允许拉取(0.3.26):新机器把路径指到一个空目录不是错误,
1026
+ // 而是「等着从云端拉」的正常状态。断言盯四件事:状态判定、不报异常、push 全线拦住、pull 放行。
1027
+ console.log('')
1028
+ console.log('== 空白本机仓库:只允许拉取 ==')
1029
+ {
1030
+ const indexNew = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1031
+ const clientNew = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1032
+ const syncNew = existsSync(join(pluginRuntime, 'sync.ps1')) ? readFileSync(join(pluginRuntime, 'sync.ps1'), 'utf8') : ''
1033
+ check('index.js 提供 repoPhase 四态判定(ok/empty/missing/unusable)',
1034
+ /function repoPhase\(dir\)/.test(indexNew) && /return others\.length === 0 \? 'empty' : 'unusable'/.test(indexNew),
1035
+ 'repoPhase 缺失或 empty 判据变了:空目录会被当成「不像仓库」继续报异常')
1036
+ check('只有插件自己生成的 同步-*.cmd 与隐藏项算「空」',
1037
+ /同步-\[\\s\\S\]\*\\?\.cmd/i.test(indexNew) || /同步-\[/i.test(indexNew),
1038
+ 'empty 判据没有排除 同步-*.cmd:生成过脚本之后就会被误判成 unusable')
1039
+ check('status 暴露 phase / remoteFiles / pushAllowed / pullAllowed',
1040
+ /phase,\s*\n\s*empty: phase === 'empty'/.test(indexNew)
1041
+ && /remoteFiles,/.test(indexNew) && /remoteEmpty: remoteFiles === 0/.test(indexNew)
1042
+ && /pushAllowed: phase === 'ok' \|\| \(phase === 'empty' && remoteFiles === 0\)/.test(indexNew)
1043
+ && /pullAllowed: phase === 'ok' \|\| \(\(phase === 'empty' \|\| phase === 'missing'\) && remoteFiles !== 0\)/.test(indexNew),
1044
+ 'status 没有暴露新门禁字段(remoteFiles / pushAllowed / pullAllowed),面板只能靠分支数猜')
1045
+ check('仓库三态 mode(ok / await-pull / await-init)按文件数算',
1046
+ /mode: phase === 'ok'[\s\S]{0,120}?remoteFiles === 0 \? 'await-init' : 'await-pull'/.test(indexNew),
1047
+ 'mode 还在看分支数:远端只剩空分支时会被判成 await-pull,拉取只能拉到空目录、死循环')
1048
+ check('远端探测先数分支、再数分支树里的文件(有超时,不写本地 refs)',
1049
+ /function probeRemote\(/.test(indexNew)
1050
+ && /function remoteFileCount\(/.test(indexNew)
1051
+ && /ls-remote --heads/.test(indexNew)
1052
+ && /'ls-tree', '-r', '--name-only', 'FETCH_HEAD'/.test(indexNew)
1053
+ && /timeout: 15000/.test(indexNew),
1054
+ 'probeRemote / remoteFileCount 缺失:判据退回分支数,「有分支但空树」又会被当成有内容')
1055
+ check('空目录的 advice 分「初始化推送」与「执行拉取」两支',
1056
+ /本机仓库\$\{where\},云端仓库也还没有任何内容/.test(indexNew) || /云端仓库也还没有任何内容/.test(indexNew),
1057
+ 'advice 没区分「两边都空」与「本机空但云端有内容」')
1058
+ check('advice 单独说明「云端只剩空分支(历史被删空)」',
1059
+ /云端仓库只有分支、里面一个文件都没有/.test(indexNew),
1060
+ '远端只剩空分支时没有专门说法:用户会以为「云端有内容」而反复点拉取')
1061
+ check('check 在非 ok 状态短路,不去撞空目录的 git',
1062
+ /if \(phase !== 'ok'\) \{[\s\S]{0,220}?autoState\.checking = false/.test(indexNew),
1063
+ 'check 仍会对空目录跑 fetch/drift:lastCheckError 会被填成「读不到远端」')
1064
+ check('push-now 在空目录先探云端:有文件拒绝,判不了或没文件放行',
1065
+ /mode === 'push' && repoPhase\(repo\) !== 'ok'/.test(indexNew)
1066
+ && /probe\.files === null/.test(indexNew)
1067
+ && /云端仓库已经有内容(\$\{probe\.files\} 个文件)/.test(indexNew),
1068
+ 'handleAuto 的 push-now 没按「云端文件数」分流(分支数会把空分支当有内容)')
1069
+ check('prepare 按云端文件数组合脚本(两边都空只生成推送 + 还原)',
1070
+ /action === 'push' && phase !== 'ok'/.test(indexNew)
1071
+ && /cloudEmptyForPrepare \? \['push', 'restore'\] : \['pull', 'restore'\]/.test(indexNew)
1072
+ && /initPush: phase !== 'ok' && cloudEmptyForPrepare/.test(indexNew),
1073
+ 'prepare 仍会为空目录生成拉取脚本,或没有 initPush 标记')
1074
+ check('sync.ps1 的 push 分支按「云端文件数」分流,并能覆盖空分支',
1075
+ /function Get-RemoteFileCount/.test(syncNew)
1076
+ && /function Initialize-EmptyRepo/.test(syncNew)
1077
+ && /云端仓库已经有内容(\$remoteFiles 个文件)/.test(syncNew)
1078
+ && /--force-with-lease/.test(syncNew)
1079
+ && /Initialize-EmptyRepo \$remoteUrlForPush/.test(syncNew),
1080
+ 'sync.ps1 push 仍按分支数拒绝,或空分支覆盖时没有 --force-with-lease(会被 non-fast-forward 拒)')
1081
+ check('初始化推送会写仓库骨架与版本契约',
1082
+ /apply\.ps1', 'capture\.ps1', 'sync\.ps1', 'restore\.ps1', 'post-exit\.ps1', 'dsh-sync-common\.ps1'/.test(syncNew)
1083
+ && /host-contract\.json/.test(syncNew),
1084
+ '初始化推送只推 settings,远端会变成「没有执行体」的半截仓库')
1085
+ check('面板:空目录不算「必须设置」,徽标不标红',
1086
+ /const missing = Boolean\(props\.data\) && !repo\.exists && !repo\.empty/.test(clientNew)
1087
+ && /if \(repo\.empty \|\| repo\.phase === 'missing'\) \{/.test(clientNew)
1088
+ && /const canPush = Boolean\(data && data\.repo && data\.repo\.pushAllowed === true\)/.test(clientNew),
1089
+ 'panel 仍把空目录当成未配置(强制编辑态 + 红色错误)')
1090
+ check('面板:推送/拉取按钮都吃后端门禁,「初始化推送」单独有说法',
1091
+ /const pushAllowed = repo\.pushAllowed === true/.test(clientNew)
1092
+ && /const canPullNow = repo\.pullAllowed === true/.test(clientNew)
1093
+ && /const initMode = repo\.mode === 'await-init'/.test(clientNew)
1094
+ && /初始化推送(会关闭 DSH)/.test(clientNew)
1095
+ && /const canPull = Boolean\(data && data\.repo && data\.repo\.pullAllowed === true\)/.test(clientNew),
1096
+ '面板的按钮门禁没跟后端对齐,或没有「初始化推送」文案')
1097
+ check('面板:待初始化徽标有独立文字与配色',
1098
+ /if \(kind === 'init'\) return M\('待初始化', 'To initialize'\)/.test(clientNew)
1099
+ && /init: 'var\(--dsw-alias-state-warn-tertiary\)'/.test(clientNew),
1100
+ 'kind=init 没有 chipLabel / chipStyle,徽标会掉进「未检测」')
1101
+ }
1102
+
1103
+ // 0.3.36:判据从「云端有几个分支」换成「分支树里有几个文件」,外加推送/拉取两条体检报告。
1104
+ // 这一段不依赖配置仓库内容,仓库是空目录也照跑。
1105
+ console.log('')
1106
+ console.log('== 0.3.36:空分支判据 / 根外路径清单 / 覆盖体检 ==')
1107
+ {
1108
+ const idx = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1109
+ const cli = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1110
+ const syn = existsSync(join(pluginRuntime, 'sync.ps1')) ? readFileSync(join(pluginRuntime, 'sync.ps1'), 'utf8') : ''
1111
+ const cap = existsSync(join(pluginRuntime, 'capture.ps1')) ? readFileSync(join(pluginRuntime, 'capture.ps1'), 'utf8') : ''
1112
+ const app = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
1113
+ check('remoteFileCount 用临时 bare 仓库浅取、只要树对象、探完就删',
1114
+ /function remoteFileCount\(/.test(idx)
1115
+ && /mkdtempSync|init --bare --quiet/.test(idx)
1116
+ && /'--filter=blob:none'/.test(idx)
1117
+ && /'ls-tree', '-r', '--name-only', 'FETCH_HEAD'/.test(idx)
1118
+ && /rmSync/.test(idx),
1119
+ 'remoteFileCount 没有走临时目录 / 浅取 / 清理,判定会拖慢面板或留下垃圾目录')
1120
+ check('sync.ps1 有 Get-RemoteFileCount,且「有分支但 0 文件」时用 --force-with-lease',
1121
+ /function Get-RemoteFileCount/.test(syn)
1122
+ && /\$remoteHadEmptyBranch/.test(syn)
1123
+ && /--force-with-lease/.test(syn)
1124
+ && /不丢数据/.test(syn),
1125
+ '空分支覆盖没有 force-with-lease(会被 non-fast-forward 拒),或没有「不丢数据」的说明')
1126
+ check('capture.ps1 推送后写根外绝对路径清单',
1127
+ /function Write-OutsideRootReport/.test(cap)
1128
+ && /config-sync-absolute-paths\.json/.test(cap)
1129
+ && /Write-OutsideRootReport/.test(cap.split('function Write-OutsideRootReport')[1] || ''),
1130
+ 'capture 没有根外路径体检:换机器拉取才发现路径是死的')
1131
+ check('apply.ps1 覆盖本机配置前比对并写覆盖清单',
1132
+ /\$overwriteItems/.test(app)
1133
+ && /config-sync-overwrite\.json/.test(app)
1134
+ && /本机改动已先备份/.test(app)
1135
+ && /先「推送」再「拉取」/.test(app),
1136
+ 'apply 整份覆盖前不比对:本机未推送的改动会被静默盖掉')
1137
+ check('roots 接口带回 absolutePaths 与 overwrite 两份报告',
1138
+ /absolutePathsPathOf/.test(idx) && /overwritePathOf/.test(idx)
1139
+ && /absolutePaths: \(/.test(idx) && /overwrite: \{/.test(idx),
1140
+ 'GET /config-sync/roots 没带体检报告,面板无从提示')
1141
+ check('面板在本机路径卡下渲染两条告警,并给「用探测值」回填',
1142
+ /data\.absolutePaths && data\.absolutePaths\.total/.test(cli)
1143
+ && /data\.overwrite && data\.overwrite\.total/.test(cli)
1144
+ && /用探测值/.test(cli)
1145
+ && /改动只影响之后的推送\/拉取/.test(cli),
1146
+ '面板没有渲染根外路径 / 覆盖告警,或没有「用探测值」回填按钮')
1147
+ }
1148
+
1149
+ // 任意 git 托管平台(0.3.27):远端地址只校验写法,认证自检提示按 origin 的真实主机名现算,
1150
+ // 不再写死 git@gitee.com —— 否则用 GitHub/GitLab 的人照着提示敲会连到错的主机。
1151
+ console.log('')
1152
+ console.log('== 任意 git 托管平台:提示不写死 gitee ==')
1153
+ {
1154
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1155
+ const commonNew = readFileSync(join(root, 'runtime', 'dsh-sync-common.ps1'), 'utf8')
1156
+ const syncNew = readFileSync(join(root, 'runtime', 'sync.ps1'), 'utf8')
1157
+ const clientNew = readFileSync(join(root, 'client.js'), 'utf8')
1158
+ check('common 提供 Get-RemoteHost(认 git@host / ssh:// / https://)',
1159
+ commonNew.includes('function Get-RemoteHost') && commonNew.includes('^ssh://(?:[^@/]+@)?([^/:]+)'),
1160
+ 'common 里没有主机名解析')
1161
+ check('common 提供 Get-RemoteAuthHint(https 给 ls-remote,ssh 给 ssh -T)',
1162
+ commonNew.includes('function Get-RemoteAuthHint') && commonNew.includes('ls-remote --heads origin') && commonNew.includes('ssh -T git@'),
1163
+ 'https 与 ssh 两种认证没有分开提示')
1164
+ check('sync.ps1 的自检提示不再写死 git@gitee.com',
1165
+ !syncNew.includes('ssh -T git@gitee.com') && (syncNew.match(/Get-RemoteAuthHint/g) || []).length >= 3,
1166
+ '仍有 gitee 硬编码或提示没接上')
1167
+ check('面板占位与说明不再只暗示 Gitee',
1168
+ clientNew.includes('git@<host>:you/dsh-config.git')
1169
+ && clientNew.includes('git@github.com:you/dsh-config.git')
1170
+ && clientNew.includes('自建 Gitea'),
1171
+ '面板还只提 Gitee')
1172
+ }
1173
+
1174
+ // 默认工作区校正(0.3.28):重启客户端之前把 workspace.json 的 defaultWorkspaceId 校正到
1175
+ // default-workspace,否则重启后新开的那条会话会落在「上次用的工作区」上。
1176
+ // 断言只盯结构与时机,不真写用户的 workspace.json。
1177
+ console.log('')
1178
+ console.log('== 默认工作区校正 ==')
1179
+ {
1180
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1181
+ const post = readFileSync(join(root, 'runtime', 'post-exit.ps1'), 'utf8')
1182
+ const host = readFileSync(join(root, 'index.js'), 'utf8')
1183
+ check('post-exit 提供 Set-DefaultWorkspace',
1184
+ post.includes('function Set-DefaultWorkspace'),
1185
+ '没有默认工作区校正函数')
1186
+ const callMatch = post.match(/^ {4}Set-DefaultWorkspace\r?\n/m)
1187
+ check('校正发生在重启之前(RestartClient 里、启动之前调用)',
1188
+ Boolean(callMatch) && callMatch.index < post.indexOf('$how = Start-Detached $exe'),
1189
+ '调用点不在 Start-Detached 之前')
1190
+ check('默认目标认 default-workspace(标题或路径)且可被设置覆盖或关闭',
1191
+ post.includes("$title -eq 'default-workspace'")
1192
+ && post.includes('deepseek-harness\\default-workspace')
1193
+ && post.includes("defaultWorkspace")
1194
+ && post.includes('off|none'),
1195
+ '目标匹配或 off 开关缺失')
1196
+ check('写前备份、写后回读校验(值 + 工作区条数)',
1197
+ post.includes(".bak-' + $stamp") && post.includes('countAfter -ne $countBefore'),
1198
+ '缺少备份或回读校验')
1199
+ check('设置字段 defaultWorkspace 进 read/write 与保存白名单',
1200
+ host.includes('defaultWorkspace: typeof raw.defaultWorkspace')
1201
+ && host.includes('defaultWorkspace: s.defaultWorkspace ||')
1202
+ && host.includes("has('defaultWorkspace')"),
1203
+ 'index.js 没带该字段')
1204
+ }
1205
+
1206
+ // 跨机路径占位符(0.3.30):仓库里不写死盘符,落地时按本机根展开;展开不掉的记 pending 让用户确认。
1207
+ // 只做只读断言(不写真实的 roots.json / 不提交仓库),写入路径留给手工验证。
1208
+ console.log('')
1209
+ console.log('== 跨机路径占位符与问题反馈 ==')
1210
+ {
1211
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1212
+ const common = readFileSync(join(root, 'runtime', 'dsh-sync-common.ps1'), 'utf8')
1213
+ const captureSrc = readFileSync(join(root, 'runtime', 'capture.ps1'), 'utf8')
1214
+ const applySrc = readFileSync(join(root, 'runtime', 'apply.ps1'), 'utf8')
1215
+ const host = readFileSync(join(root, 'index.js'), 'utf8')
1216
+ const cli = readFileSync(join(root, 'client.js'), 'utf8')
1217
+
1218
+ check('common 提供路径根读写与占位符双向转换',
1219
+ common.includes('function Get-SyncRoots') && common.includes('function Save-SyncRoots')
1220
+ && common.includes('function ConvertTo-TokenText') && common.includes('function Expand-TokenText')
1221
+ && common.includes('function Get-MissingTokens'),
1222
+ '缺占位符函数')
1223
+ check('common 覆盖四种路径写法(原样 / 双反斜杠 / 正斜杠 / 转义斜杠)',
1224
+ common.includes('function Get-PathVariants') && common.includes("$p.Replace($bs, '/')"),
1225
+ '变体列表不全')
1226
+ check('占位符按根长度降序替换(workspaceHome 在 appRoot 之下不会替换错位)',
1227
+ common.includes('Sort-Object { $_.Value.Length } -Descending'),
1228
+ '没有按长度排序')
1229
+ check('capture 写仓库前把本机根换成占位符',
1230
+ captureSrc.includes('ConvertTo-TokenText $txt $roots') && captureSrc.includes('Get-SyncRoots $DshHome $AppRoot $WorkspaceHome'),
1231
+ 'capture 没做归一')
1232
+ check('capture 首次自动落一份 config-sync-roots.json',
1233
+ captureSrc.includes('Save-SyncRoots $DshHome $roots'),
1234
+ '没写 roots 文件')
1235
+ const settingsCount = (captureSrc.match(/Repo = 'settings\\/g) || []).length
1236
+ const applyCount = (applySrc.match(/Repo = 'settings\\/g) || []).length
1237
+ check('capture 覆盖到各插件自己的配置(不止 4 个)', settingsCount >= 11, `实际 ${settingsCount} 项`)
1238
+ check('capture 与 apply 的 settings 清单一致', settingsCount === applyCount, `capture ${settingsCount} / apply ${applyCount}`)
1239
+ check('apply 展开占位符,缺值的跳过不写并记 pending',
1240
+ applySrc.includes('Expand-TokenText $txt $roots') && applySrc.includes('Write-PendingPaths $DshHome $pendingItems')
1241
+ && applySrc.includes('continue'),
1242
+ 'apply 没按缺失跳过')
1243
+ check('workspace.json(DSH 工作区登记)进了同步范围',
1244
+ captureSrc.includes("storages\\workspace.json") && applySrc.includes("storages\\workspace.json"),
1245
+ '工作区登记表没同步')
1246
+ check('面板有「本机路径」卡:只读展示 + 「修改」进编辑 + 保存',
1247
+ cli.includes("M('本机路径', 'Local paths')") && cli.includes("M('修改', 'Edit')")
1248
+ && cli.includes('callRoots') && cli.includes('setCustom') && cli.includes('addCustom'),
1249
+ 'client.js 缺本机路径卡的修改态')
1250
+ check('本机路径卡默认只读(值用等宽字展示,token 作灰字说明)',
1251
+ cli.includes('const isEditing = editing || forced') && cli.includes('{{ROOT:${k}}}'),
1252
+ '只读态/自选目录没渲染')
1253
+ check('面板会列出待确认项(token + 文件 + 说明)',
1254
+ cli.includes('data.missing') && cli.includes('m.token'),
1255
+ '待确认清单没渲染')
1256
+ check('面板有「问题反馈」卡:提交 + 列表 + 连接状态 + 令牌入口',
1257
+ cli.includes("M('问题反馈', 'Feedback')") && cli.includes('callFeedback')
1258
+ && cli.includes('st.connected') && cli.includes("query: { action: 'token' }")
1259
+ && cli.includes("query: { action: 'flush' }"),
1260
+ 'client.js 缺反馈卡')
1261
+ check('反馈走 GitHub Issue:建 issue + 列表 + 关单 + 离线队列',
1262
+ host.includes('GH_FEEDBACK_LABEL') && host.includes('/repos/${repo}/issues')
1263
+ && host.includes('labels: [GH_FEEDBACK_LABEL]')
1264
+ && host.includes('config-sync-feedback-outbox.json') && host.includes("action === 'flush'")
1265
+ && host.includes("method: 'PATCH'"),
1266
+ 'index.js 没走 Issue')
1267
+ check('令牌自动从本机 git 凭据取,落到本机私有文件',
1268
+ host.includes('tokenFromGitCredential') && host.includes('config-sync-gh.json')
1269
+ && host.includes('credential') && host.includes('fill'),
1270
+ '缺自动取令牌')
1271
+ check('反馈正文自动附环境块(版本/机器/时间)',
1272
+ host.includes('### 环境 / Environment') && host.includes('issueBodyOf'),
1273
+ '没附环境信息')
1274
+ check('读不需要令牌:带令牌失败自动退回匿名',
1275
+ host.includes("const attempts = g.token ? [g.token, ''] : ['']") && host.includes('readAnon'),
1276
+ '没有匿名降级')
1277
+ check('关单只有仓库所有者能点(服务端挡别人的令牌)',
1278
+ host.includes('ownerOf') && host.includes('onlyCloseByOwner'.replace('onlyCloseByOwner', 'canClose'))
1279
+ && host.includes("login.toLowerCase() !== owner.toLowerCase()"),
1280
+ '服务端没校验所有者')
1281
+ check('无令牌时提交不失败,给浏览器预填链接',
1282
+ host.includes('newIssueUrl') && host.includes('issues/new?') && host.includes('needToken'),
1283
+ '没有无令牌降级')
1284
+ check('面板按权限置灰关单按钮',
1285
+ cli.includes('!st.canClose') && cli.includes("M('仅所有者', 'Owner only')") && cli.includes('fallbackUrl'),
1286
+ '面板没做权限态')
1287
+ check('反馈列表可按状态筛选 + 关键词搜索',
1288
+ cli.includes("seg('open'") && cli.includes("seg('closed'") && cli.includes("seg('all'")
1289
+ && cli.includes('setKw') && cli.includes('st.counts'),
1290
+ '没有筛选/查询')
1291
+
1292
+ const rootsGet = await call('/config-sync/roots', { headers: { host: 'localhost:3080' } })
1293
+ const rootsBody = JSON.parse(rootsGet.body || '{}')
1294
+ check('GET /config-sync/roots 返回本机根 + 探测值 + 待确认清单',
1295
+ rootsBody.ok === true && rootsBody.roots && typeof rootsBody.roots.appRoot === 'string'
1296
+ && rootsBody.detected && Array.isArray(rootsBody.missing),
1297
+ '结构不全')
1298
+ check('roots 的待确认项带人话说明(不是只给 token)',
1299
+ rootsBody.missing.every((m) => typeof m.token === 'string' && typeof m.hint === 'string'),
1300
+ '缺 hint')
1301
+
1302
+ const fbGet = await call('/config-sync/feedback', { headers: { host: 'localhost:3080' } })
1303
+ const fbBody = JSON.parse(fbGet.body || '{}')
1304
+ check('GET /config-sync/feedback 返回连接状态 + Issue 列表 + 待发队列',
1305
+ fbBody.ok === true && Array.isArray(fbBody.items) && typeof fbBody.connected === 'boolean'
1306
+ && typeof fbBody.repo === 'string' && Array.isArray(fbBody.outbox) && typeof fbBody.ghFile === 'string'
1307
+ && typeof fbBody.canClose === 'boolean' && typeof fbBody.owner === 'string',
1308
+ JSON.stringify(fbBody).slice(0, 400))
1309
+ check('GET /config-sync/feedback 同时给出 open/closed/total 计数',
1310
+ fbBody.counts && typeof fbBody.counts.open === 'number' && typeof fbBody.counts.closed === 'number'
1311
+ && typeof fbBody.counts.total === 'number',
1312
+ JSON.stringify(fbBody.counts))
1313
+ check('跨站请求被拒(roots)', await (async () => {
1314
+ const r = await call('/config-sync/roots', {
1315
+ method: 'POST',
1316
+ headers: { host: 'localhost:3080', origin: 'https://evil.example.com', 'content-type': 'application/json' },
1317
+ body: '{}',
1318
+ })
1319
+ return r.statusCode === 403
1320
+ })(), '没拦住')
1321
+ }
1322
+
1323
+ // 0.3.37:本机路径区默认不进页面,入口只有一个标题行按钮
1324
+ console.log('')
1325
+ console.log('== 0.3.37:本机路径区默认不进页面 ==')
1326
+ {
1327
+ const index37 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1328
+ const client37 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1329
+ check('status 给出三个计数 + 告警数(面板据此决定按钮要不要变橙)',
1330
+ /localPaths: \(\(\) => \{/.test(index37)
1331
+ && /const total = pending \+ absolute \+ overwrite/.test(index37)
1332
+ && /alert: total, total/.test(index37),
1333
+ 'status 没给 localPaths 计数/告警数:面板只能把整张卡摊在页面上当提示')
1334
+ check('本机路径区只由标题行按钮控制(组件不再自己 return null)',
1335
+ /const rootsCard = showRoots \? h\(RootsCard, \{ onRootsSaved: refresh \}\) : null/.test(client37)
1336
+ && !/props\.forceShow/.test(client37),
1337
+ '显示条件不在父层:组件 return null 时 Section 仍会渲染空标题')
1338
+ const st37 = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
1339
+ check('status 运行时真的带 localPaths 计数与告警数(面板按钮靠它变橙)',
1340
+ Boolean(st37.localPaths) && typeof st37.localPaths.total === 'number'
1341
+ && typeof st37.localPaths.pending === 'number' && typeof st37.localPaths.alert === 'number',
1342
+ JSON.stringify(st37.localPaths))
1343
+ }
1344
+
1345
+ console.log('')
1346
+ console.log('== 0.3.41:status 提速(不再递归统计备份) ==')
1347
+ {
1348
+ const index41 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1349
+ const client41 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1350
+ check('备份列表不再递归数文件/体积(92 份快照 4.8 万文件曾要 7.7 秒)',
1351
+ /files: null, bytes: null, hasProfile, plugins, bundles/.test(index41)
1352
+ && !/bytes \+= statSync\(p\)\.size/.test(index41),
1353
+ 'inspectBackup 仍在逐个 statSync 统计每个快照')
1354
+ check('远端探测带预算 + 启动预热(status 不再等满一次 ls-remote)',
1355
+ /function probeRemoteQuick\(url, settings, budgetMs\)/.test(index41)
1356
+ && /function warmRemoteProbe\(config\)/.test(index41)
1357
+ && /await probeRemoteQuick\(remoteProbeUrl, settings, 2500\)/.test(index41),
1358
+ '缺 probeRemoteQuick / warmRemoteProbe / 调用处')
1359
+ check('远端探测缓存拉长到 5 分钟', /REMOTE_PROBE_TTL = 300000/.test(index41))
1360
+ check('前端 status 请求有超时与 3 次重试', /new AbortController\(\)/.test(client41)
1361
+ && /已自动重试 3 次/.test(client41))
1362
+ const t41 = Date.now()
1363
+ const st41 = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
1364
+ const ms41 = Date.now() - t41
1365
+ check('status 实测在 3 秒内答完(当天首次含一次远端探测预算)',
1366
+ st41.ok === true && ms41 < 3000, `${ms41}ms`)
1367
+ check('备份快照列表仍可用:给名字/时间/插件数,体积字段为空',
1368
+ Boolean(st41.backup) && (st41.backup.count === 0 || (Array.isArray(st41.backup.snapshots)
1369
+ && st41.backup.snapshots.every((s) => s.files === null && s.bytes === null))),
1370
+ JSON.stringify(st41.backup && { count: st41.backup.count, first: st41.backup.snapshots && st41.backup.snapshots[0] }))
1371
+ }
1372
+
1373
+ console.log('')
1374
+ console.log('== 0.3.43:根外路径清单只在「配置来自别的机器」时提示 ==')
1375
+ {
1376
+ const src43 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1377
+ const client43 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1378
+ const cap43 = existsSync(join(pluginRootSelf, 'runtime', 'capture.ps1')) ? readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8') : ''
1379
+ check('报告归属判定:记录机器名 + 只在别的机器写的清单才算告警',
1380
+ src43.includes('function localMachineName') && src43.includes('function sameMachine')
1381
+ && src43.includes('absFromOtherMachine') && src43.includes('const absolute = absFromOther'), 'index.js 的 localPaths 计数')
1382
+ check('推荐地址:先按对方根映射,再按同名目录兜底,都没有就说没有',
1383
+ src43.includes('function suggestLocalPathFor') && src43.includes("kind: 'root'")
1384
+ && src43.includes("kind: 'namesake'") && src43.includes("kind: 'none'")
1385
+ && src43.includes('function candidateParentDirs'), 'index.js 的推荐算法')
1386
+ check('清单只扫配置类文件(会话/工作区/记忆不参与)',
1387
+ Boolean(cap43) && cap43.includes('$confTop')
1388
+ && cap43.includes("'local-plugins'") && cap43.includes("$rel0 -notmatch 'node_modules'"),
1389
+ 'capture.ps1 的扫描范围')
1390
+ check('报告带 machine 与当时的根值,供本机映射用',
1391
+ Boolean(cap43) && cap43.includes('machine = $machine') && cap43.includes('roots = [ordered]@'),
1392
+ 'capture.ps1 的报告结构')
1393
+ check('协议头误匹配被过滤(s://1v3... 不再当成盘符)',
1394
+ Boolean(cap43) && cap43.includes("if ($p -match '://') { continue }"), 'capture.ps1')
1395
+ const client43x = client43
1396
+ check('面板:只在 fromOtherMachine 时渲染跨机清单,并给「采纳」按钮',
1397
+ client43x.includes('data.absolutePaths.fromOtherMachine') && client43x.includes('adoptAbsolute')
1398
+ && client43x.includes('adoptAbsolute(it)'), 'client.js')
1399
+ check('面板不再用旧文案「仓库里有 N 处绝对路径不在任何已确认根下」',
1400
+ !client43.includes('仓库里有 ${data.absolutePaths.total} 处绝对路径'), 'client.js')
1401
+ }
1402
+
1403
+ console.log('')
1404
+ console.log('== 0.3.44:工作区与会话的路径也按本机落点推断 ==')
1405
+ {
1406
+ const cap44 = readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8')
1407
+ const app44 = readFileSync(join(pluginRootSelf, 'runtime', 'apply.ps1'), 'utf8')
1408
+ const hel44 = readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'fix-session-cwd.mjs'), 'utf8')
1409
+ const cli44 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1410
+ const idx44 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1411
+ check('报告分两类:配置类 + 工作区/会话记录,各自限额',
1412
+ cap44.includes('$dataTop') && cap44.includes("'workspace', 'conversations'")
1413
+ && cap44.includes('totalData = $nData') && cap44.includes('$scope = if ($dataTop')
1414
+ && cap44.includes('$nData -ge 30') && cap44.includes('$nConf -ge 50'), 'capture.ps1 的扫描范围')
1415
+ check('清单项带 scope,面板才能分两组列',
1416
+ idx44.includes("scope: String(it.scope || 'config')"), 'index.js 的 items 结构')
1417
+ check('apply 用登记表的 sessionIds 反查本机工作区路径,并交给 helper 改写 projcache',
1418
+ app44.includes('$projMap') && app44.includes('foreach ($sid in @($w.sessionIds))')
1419
+ && app44.includes('projcache = $projMap') && app44.includes('$cwdMap.Count -gt 0 -or $projMap.Count -gt 0'),
1420
+ 'apply.ps1 没把 projcache 的 cwd 对齐')
1421
+ check('helper 只替换 identity.cwd 那一个字符串,且幂等',
1422
+ hel44.includes('spec.projcache') && hel44.includes('result.projFixed')
1423
+ && hel44.includes('record.identity.cwd !== target')
1424
+ && hel44.includes('if (cur === target) { result.projAlreadyOk++'),
1425
+ 'fix-session-cwd.mjs 的 projcache 处理')
1426
+ check('面板把配置与「工作区与会话记录」分两组显示',
1427
+ cli44.includes("it.scope === 'data'") && cli44.includes('工作区与会话记录里的路径'),
1428
+ 'client.js 没分组')
1429
+ }
1430
+
1431
+ console.log('')
1432
+ console.log('== 0.3.54:三处纯性能改动(行为不变) ==')
1433
+ {
1434
+ const cap54 = readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8')
1435
+ const sync54 = readFileSync(join(pluginRootSelf, 'runtime', 'sync.ps1'), 'utf8')
1436
+ check('capture 有 -DeepVerify,且深校验开关走 $script:CmpDeep',
1437
+ /\[switch\]\$DeepVerify/.test(cap54) && cap54.includes('$script:CmpDeep')
1438
+ && cap54.includes('function Test-TreeFileChanged'), 'capture.ps1 的深校验开关')
1439
+ check('快筛只比 Length / LastWriteTimeUtc,不一致才 Get-NormalizedHash',
1440
+ cap54.includes('$srcInfo.Length') && cap54.includes('$srcInfo.LastWriteTimeUtc')
1441
+ && cap54.includes('Get-NormalizedHash'), 'capture.ps1 的比较逻辑')
1442
+ check('批量 FileInfo + 字典比对,不再逐文件 Test-Path 父目录',
1443
+ cap54.includes('function Get-TreeCmpSummary') && cap54.includes('$dstRels')
1444
+ && cap54.includes('$madeDirs'), 'capture.ps1 的批量比对')
1445
+ check('sync 把 DeepVerify 透传给 capture', sync54.includes("$captureArgs['DeepVerify'] = $true"))
1446
+ check('历史扫描按提交缓存:commit 相同或是 HEAD 祖先就跳过',
1447
+ sync54.includes('sync-history-scan.json') && sync54.includes('$needHistoryScan')
1448
+ && sync54.includes('merge-base --is-ancestor'), 'sync.ps1 的历史扫描缓存')
1449
+ check('有 -ScanHistory 强制全量,推送被拒时也补一次全量',
1450
+ /\[switch\]\$ScanHistory/.test(sync54) && sync54.includes('$historyFullyScanned'),
1451
+ 'sync.ps1 的扫描强制/补扫')
1452
+ check('拉取改成 fetch + merge --ff-only(不再 git pull 的第二次往返)',
1453
+ sync54.includes("merge --ff-only origin/' + $branch") && sync54.includes('$fetchedThisRun')
1454
+ && !sync54.includes('" pull --ff-only'), 'sync.ps1 的拉取命令')
1455
+ check('空扫描结果不写成 `,$res`(否则空仓库误报 1 个超限文件 0.0 MB)',
1456
+ sync54.includes('function Get-OversizedHistory') && !/^\s*return ,\$res\b/m.test(sync54),
1457
+ 'Get-OversizedHistory 的返回值')
1458
+ }
1459
+
1460
+ console.log('')
1461
+ process.exit(failures === 0 ? 0 : 1)