dsh-config-sync-plugin 0.4.8 → 0.4.10

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,2045 @@
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 === 13 && routes.has('/config-sync/auto-exit') && 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.has('/config-sync/cache-guard') && routes.has('/config-sync/workspace-view'), `实际 ${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
+ // 0.3.64 起改成「展示 6 分钟后自动关窗」:远程桌面/无焦点时 ReadKey 会一直卡住,
617
+ // 用户要的是别让窗口永远挡在前面。所以断言改成盯 Start-Sleep 而不是 ReadKey。
618
+ check('推送/拉取完成后进度窗口保留一段时间再自动关闭(不再卡在 ReadKey)',
619
+ postExitSrc.includes("if ($Mode -eq 'pull' -or $Mode -eq 'push'") && /Start-Sleep -Seconds 360/.test(postExitSrc) && !postExitSrc.includes('RawUI.ReadKey'),
620
+ postExit || 'post-exit.ps1')
621
+ check('插件更新完成后窗口同样留着(不与同步窗口两套行为)',
622
+ /-eq 'pull'.*?-eq 'push'.*?-eq 'update'/.test(postExitSrc) && postExitSrc.includes('插件更新已完成'),
623
+ postExit || 'post-exit.ps1')
624
+ check('客户端在窗口开始等待之前就已拉起(关窗口不影响它)',
625
+ postExitSrc.indexOf('if ($Restart) { RestartClient }') > 0
626
+ && postExitSrc.indexOf('if ($Restart) { RestartClient }') < postExitSrc.lastIndexOf('Finish 0'),
627
+ postExit || 'post-exit.ps1')
628
+
629
+ // 执行体优先级:仓库里那份 sync.ps1 是随配置仓库同步来的副本,插件升级后可能还是旧版;
630
+ // 旧版没有冲突清单/exit 6,会把 pull 退回「直接 git pull + 失败回滚」——
631
+ // 真实故障:面板 18 项全选「用云端」,清单读都没读就被旧执行体覆盖回滚。
632
+ check('执行体选择:插件 runtime 优先、仓库副本兜底',
633
+ postExitSrc.includes('function Find-PluginScript')
634
+ && postExitSrc.indexOf('function Find-PluginScript') < postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'"),
635
+ postExit || 'post-exit.ps1')
636
+ check('仓库 sync.ps1 只作兜底(不得排在插件前面)',
637
+ postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'") > 0
638
+ && postExitSrc.indexOf("$sync = Find-PluginScript 'sync.ps1'") < postExitSrc.indexOf('if (-not $sync -and $RepoRoot)'),
639
+ postExit || 'post-exit.ps1')
640
+
641
+ // 更新源自检:raw.githubusercontent.com 在部分网络下直连不通,而 Node 的 fetch 不读系统代理,
642
+ // 超时一到就 abort(面板上那句 "This operation was aborted")。所以内置候选必须带实时反代排在前面。
643
+ // 不要用 jsDelivr 兜清单:它对 @main 这类分支别名缓存很久,发版后仍返回上一版清单(实测 + purge 也没立刻刷新)。
644
+ const indexSrc = readFileSync(join(pluginRoot, 'index.js'), 'utf8')
645
+ check('更新清单带实时反代候选(gh-proxy 排在最前,raw 兜底)',
646
+ indexSrc.includes('gh-proxy.com') && indexSrc.includes('ghfast.top') &&
647
+ indexSrc.includes('UPDATE_MANIFEST_MIRRORS') && !indexSrc.includes('cdn.jsdelivr.net/gh/QcWyGm'),
648
+ 'index.js')
649
+ check('清单按候选依次尝试并汇总失败原因', indexSrc.includes('async function fetchManifestAuto'), 'index.js')
650
+ check('清单超时放宽到 30 秒(raw 慢链路 10 秒会假失败)',
651
+ indexSrc.includes('UPDATE_FETCH_TIMEOUT = 30 * 1000'), 'index.js')
652
+ // 0.3.7:更新拆成「只下载」和「退出后安装」两段。
653
+ // 为什么:DSH 开着的时候覆盖插件目录,宿主会重新同步插件树、把「配置同步」面板卸载掉 ——
654
+ // 用户看到的就是"更新到一半页面自己跳走,还得点回来才能按重启"。所以覆盖必须留到退出之后。
655
+ check('宿主有「只下载」动作(prepare → update-staging,不碰插件目录)',
656
+ indexSrc.includes("action === 'prepare'") && indexSrc.includes('async function downloadPackage') &&
657
+ indexSrc.includes('update-staging'), 'index.js')
658
+ check('只下载会按候选地址逐个试并校验 sha256',
659
+ /function downloadPackage[\s\S]{0,1200}createHash\('sha256'\)/.test(indexSrc), 'index.js')
660
+ check('宿主有「装并重启」动作(install-restart,把本地包交给退出后的脚本)',
661
+ indexSrc.includes("action === 'install-restart'") &&
662
+ /action === 'install-restart'[\s\S]{0,900}-UpdateTgz/.test(indexSrc), 'index.js')
663
+ check('退出后的安装直接吃已下好的本地包(不重复下载)',
664
+ postExitSrc.includes('Test-Path -LiteralPath $UpdateTgz -PathType Leaf'),
665
+ postExit || 'post-exit.ps1')
666
+ check('运行中静默安装仍保留给 CLI/兼容(界面不用它)',
667
+ indexSrc.includes("action === 'install-live'") && indexSrc.includes('function runInstallPlugin'), 'index.js')
668
+ check('只重启走 relaunch(不碰仓库也不装插件)',
669
+ indexSrc.includes("mode: 'relaunch'") && postExitSrc.includes("'relaunch'"), postExit || 'post-exit.ps1')
670
+ const installer = [join(pluginRoot, 'runtime', 'install-plugin.ps1'), join(pluginRoot, 'install-plugin.ps1')].find((p) => existsSync(p)) || ''
671
+ const installerSrc = installer ? readFileSync(installer, 'utf8') : ''
672
+ check('安装器存在并自报结果(RESULT: 行)', Boolean(installer) && installerSrc.includes('RESULT:'), installer || 'runtime/install-plugin.ps1')
673
+ check('安装器覆盖前先备份、写坏能回滚',
674
+ installerSrc.includes('function Restore-Backup') && installerSrc.includes('plugin-{0}-{1}'),
675
+ installer || 'runtime/install-plugin.ps1')
676
+ check('安装器按候选地址逐个下载', installerSrc.includes("-split '\\|'"), installer || 'runtime/install-plugin.ps1')
677
+ const clientSrc = readFileSync(join(pluginRoot, 'client.js'), 'utf8')
678
+ check('面板按钮走「下载更新 → 重启并安装」,不再运行中安装',
679
+ clientSrc.includes("action: 'prepare'") && clientSrc.includes("action: 'install-restart'") &&
680
+ !clientSrc.includes("action: 'install-live'") &&
681
+ clientSrc.includes('重启并安装') && clientSrc.includes('Restart & install'), 'client.js')
682
+ check('面板会展示「已下载,待安装」这一态',
683
+ clientSrc.includes('preparedReady') && clientSrc.includes('已下载,待安装'), 'client.js')
684
+
685
+ // 0.3.8:同步内容勾选 —— 面板写 <DshHome>\config-sync-scope.json,capture/apply 读同一个文件。
686
+ // 关键契约:默认全勾、未勾选一律跳过、deleteCloud 默认关(关着时绝不删云端副本)。
687
+ const pickRuntime = (name) => [join(pluginRoot, 'runtime', name), join(pluginRoot, name)].find((p) => existsSync(p)) || ''
688
+ const commonSrc = pickRuntime('dsh-sync-common.ps1') ? readFileSync(pickRuntime('dsh-sync-common.ps1'), 'utf8') : ''
689
+ const captureSrc = pickRuntime('capture.ps1') ? readFileSync(pickRuntime('capture.ps1'), 'utf8') : ''
690
+ const applySrc = pickRuntime('apply.ps1') ? readFileSync(pickRuntime('apply.ps1'), 'utf8') : ''
691
+ const pickTool = (name) => [join(pluginRoot, 'runtime', 'tools', name), join(pluginRoot, 'tools', name)].find((p) => existsSync(p)) || ''
692
+ const helperSrc = pickTool('fix-session-cwd.mjs') ? readFileSync(pickTool('fix-session-cwd.mjs'), 'utf8') : ''
693
+ // 执行体没跑起来时 PowerShell 只喷红字、$LASTEXITCODE 还是上一条命令残留的 0,
694
+ // 整次同步就被当成成功(写 ok:true + 刷分水岭),本机改动静默滞留。三道锁缺一不可。
695
+ check('调用执行体前压哨兵值,且终止错误被捕获后一律判失败',
696
+ postExitSrc.includes('$LASTEXITCODE = -1')
697
+ && postExitSrc.includes('$invokeOk = $false')
698
+ && /catch \{[\s\S]{0,400}执行体调用异常/.test(postExitSrc)
699
+ && /if \(-not \$invokeOk\)[\s\S]{0,260}\$code = 1/.test(postExitSrc),
700
+ 'post-exit.ps1')
701
+ check('调用执行体前确认文件仍存在(安装覆盖到一半也能拦住)',
702
+ /\$sync = Find-PluginScript 'sync\.ps1'[\s\S]{0,1200}Test-Path -LiteralPath \$sync/.test(postExitSrc),
703
+ 'post-exit.ps1')
704
+ check('同步失败时不刷新同步分水岭(免得失败变成静默漏推)',
705
+ postExitSrc.includes('RestartClient -SkipWatermark:$failed')
706
+ && postExitSrc.includes('function RestartClient([switch]$SkipWatermark)')
707
+ && /if \(-not \$SkipWatermark\)/.test(postExitSrc),
708
+ 'post-exit.ps1')
709
+
710
+ const SCOPE_GROUPS = ['profile', 'prompt', 'skills', 'presets', 'storages-record', 'settings', 'mnemon', 'local-plugins', 'plugin-data', 'extra', 'workspace', 'conversations']
711
+ check('公共脚本提供 scope 读取与判断函数',
712
+ ['Get-SyncScope', 'Test-SyncGroupEnabled', 'Test-SyncItemEnabled', 'Test-SyncDeleteCloud', 'Skip-SyncGroup', 'Skip-SyncItem']
713
+ .every((n) => commonSrc.includes(`function ${n}`)), 'dsh-sync-common.ps1')
714
+ check('scope 文件不存在时按全勾处理(老机器行为不变)',
715
+ commonSrc.includes('config-sync-scope.json') && /function Get-SyncScope[\s\S]{0,700}Test-Path/.test(commonSrc),
716
+ 'dsh-sync-common.ps1')
717
+ check('capture 十组都按勾选判断',
718
+ SCOPE_GROUPS.every((g) => captureSrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)),
719
+ SCOPE_GROUPS.filter((g) => !captureSrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)).join(', ') || 'capture.ps1')
720
+ const EXCLUDABLE = ['skills', 'presets', 'settings', 'local-plugins', 'prompt', 'storages-record', 'plugin-data', 'extra', 'workspace', 'conversations']
721
+ check('capture 组内还能单独排除(skills / presets / settings / local-plugins / prompt / 台账 / 插件数据 / 额外路径 / 工作区 / 会话)',
722
+ EXCLUDABLE.every((g) => captureSrc.includes(`Test-SyncItemEnabled $Scope '${g}'`)),
723
+ EXCLUDABLE.filter((g) => !captureSrc.includes(`Test-SyncItemEnabled $Scope '${g}'`)).join(', ') || 'capture.ps1')
724
+ check('apply 十组都按勾选跳过(未勾选的不还原)',
725
+ SCOPE_GROUPS.every((g) => applySrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)),
726
+ SCOPE_GROUPS.filter((g) => !applySrc.includes(`Test-SyncGroupEnabled $Scope '${g}'`)).join(', ') || 'apply.ps1')
727
+ check('deleteCloud 默认关:关着时跳过就只是跳过,不删云端副本',
728
+ /function Skip-SyncGroup[\s\S]{0,400}Test-SyncDeleteCloud/.test(commonSrc)
729
+ && commonSrc.includes('if (-not (Test-SyncDeleteCloud $Scope)) { return }'), 'dsh-sync-common.ps1')
730
+ check('apply 的 -PruneSkills 不会删掉被排除的本机 Skill',
731
+ applySrc.includes("(Test-SyncItemEnabled $Scope 'skills' $_.Name)"), 'apply.ps1')
732
+ check('会话按工作区过滤,且未勾选的会话不会被铺回本机',
733
+ captureSrc.includes('$skipSessDirs') && applySrc.includes('$skipConvDirs'), 'capture/apply')
734
+
735
+ // 0.3.51:插件数据(自动枚举)与额外路径(用户自选),规则落在 config-sync-extra.json
736
+ check('两组 id 进了公共脚本、capture、apply 与面板',
737
+ commonSrc.includes("'plugin-data', 'extra'")
738
+ && captureSrc.includes("Test-SyncGroupEnabled $Scope 'plugin-data'")
739
+ && applySrc.includes("Test-SyncGroupEnabled $Scope 'plugin-data'")
740
+ && indexSrc.includes("id: 'plugin-data'") && indexSrc.includes("id: 'extra'"), 'all')
741
+ check('规则文件:config-sync-extra.json + 排除名单整份替换(空数组也要能生效)',
742
+ commonSrc.includes('config-sync-extra.json')
743
+ && commonSrc.includes("if ($j.pluginData.PSObject.Properties['exclude']) { $pd.exclude = @("), 'dsh-sync-common.ps1')
744
+ check('单文件上限卡在 GitHub 硬限 100MB(配置调大也压回来)',
745
+ commonSrc.includes('$SyncExtraHardMaxBytes = 104857600') && commonSrc.includes('[Math]::Min([int64]$v, [int64]$SyncExtraHardMaxBytes)'), 'dsh-sync-common.ps1')
746
+ check('插件数据按 dav 目录枚举,系统/已覆盖目录进默认 skipDirs',
747
+ commonSrc.includes('function Get-PluginDataSlots') && commonSrc.includes("'profiles', 'skills', '.agent-presets', 'storages'"), 'dsh-sync-common.ps1')
748
+ check('抓取写 manifest(路径占位符化,方便另一台展开)',
749
+ captureSrc.includes("Join-Path $pdDst 'manifest.json'") && captureSrc.includes("src = (ConvertTo-TokenText $slot.src $pdRoots)"), 'capture.ps1')
750
+ check('写回先展开占位符、再逐文件合并并留底',
751
+ /Copy-TreeInto \$slotSrc \$dst \$bk/.test(applySrc) && applySrc.includes('$miss = @(Get-MissingTokens $expanded)'), 'apply.ps1')
752
+ check('面板有 /config-sync/extra-config 接口与规则卡',
753
+ indexSrc.includes("const ROUTE_EXTRA_CONFIG = '/config-sync/extra-config'")
754
+ && indexSrc.includes('async function handleExtraConfig')
755
+ && clientSrc.includes("fetch('/config-sync/extra-config'") && clientSrc.includes('function ExtraCard'), 'index/client')
756
+ check('凭据文件默认不进仓库:*vault* 在名单里,且抓取前按内容嗅探再拦一道',
757
+ commonSrc.includes("'*vault*'") && indexSrc.includes("'*vault*'")
758
+ && commonSrc.includes('function Test-SyncExtraSecret') && commonSrc.includes('$SyncExtraSecretMarkers')
759
+ && captureSrc.includes('Get-SyncExtraSecretSkips'), 'common/index/capture')
760
+ check('符号链接/junction 不跟进(插件目录常把外部数据链进来)',
761
+ commonSrc.includes('[IO.FileAttributes]::ReparsePoint'), 'dsh-sync-common.ps1')
762
+ check('0.4.01:项目级技能 .dsh/skills/ 在工作区同步里放行(其余 .dsh 仍跳过)',
763
+ commonSrc.includes("$isProjectSkill = ($parts.Count -ge 3") && commonSrc.includes("$parts[1] -eq 'skills'")
764
+ && commonSrc.includes('if ($isProjectSkill -and ($seg -eq \'.dsh\' -or $seg -eq \'skills\')) { continue }'), 'dsh-sync-common.ps1 项目技能例外')
765
+ check('「插件数据与额外路径」卡先只读,点「修改」才能改、点「保存」才落盘',
766
+ clientSrc.includes('readOnly: !editing')
767
+ && clientSrc.includes('disabled: !editing')
768
+ && /const \[editing, setEditing\] = react\.useState\(false\)[\s\S]{0,1200}setEditing\(false\)/.test(clientSrc)
769
+ && clientSrc.includes('M(\'取消\', \'Cancel\')'), 'client.js')
770
+ const rmIdx = clientSrc.indexOf('() => removePath')
771
+ const rmBefore = rmIdx >= 0 ? clientSrc.slice(rmIdx - 180, rmIdx) : ''
772
+ check('额外路径的「移除」按钮只在编辑态出现(只读时整行只剩名字和路径)',
773
+ rmBefore.includes("editing ? h('button'") && !rmBefore.includes('disabled: !editing'), 'client.js')
774
+ check('工作区登记表也跟着过滤(不会「数据跳过了、登记表还写着」)',
775
+ captureSrc.includes("$entries = @($entries | Where-Object { Test-SyncItemEnabled $Scope 'workspace' $_.Id })")
776
+ && applySrc.includes("$plan = @($plan | Where-Object { Test-SyncItemEnabled $Scope 'workspace' $_.Id })"),
777
+ 'capture/apply')
778
+
779
+ // apply 的非零退出码等同于「拉取失败」,post-exit 会据此回滚;
780
+ // 所以「没有 pnpm」这种环境差异不能让整次拉取失败 —— 只要 node_modules 在,依赖就是好的。
781
+ check('依赖已就绪时 apply 不因缺少 pnpm 而失败退出',
782
+ applySrc.includes("Join-Path $ProfileDir 'node_modules'")
783
+ && applySrc.includes('$skipBecauseReady'), 'apply.ps1')
784
+ check('node_modules 不存在时仍然明确报错(不静默放过)',
785
+ /if \(Test-Path -LiteralPath \$nodeModules\)[\s\S]{0,300}exit 1/.test(applySrc), 'apply.ps1')
786
+
787
+ // 登记表:同一路径撞了两台机器各自建的 ID 时,必须保留当前机器在用的 ID,
788
+ // 否则 defaultWorkspaceId 悬空、整张表校验不过(工作区列表空、会话读不出)。
789
+ check('登记表同路径冲突时保留本机 ID(不是仓库 ID)',
790
+ applySrc.includes('$localIdSet')
791
+ && applySrc.indexOf('Where-Object { $localIdSet.ContainsKey($_) }')
792
+ < applySrc.indexOf('Where-Object { $mfIdSet.ContainsKey($_) }'),
793
+ 'apply.ps1')
794
+ check('defaultWorkspaceId 以本机为准(原值还在表里就不动)',
795
+ applySrc.includes('$localDefault')
796
+ && applySrc.includes('$ids -contains $localDefault')
797
+ && applySrc.includes("$localGlobal['defaultWorkspaceId'] = $ids[0]"),
798
+ 'apply.ps1')
799
+
800
+ // 会话还原的前提:能展开 {{APP_ROOT}} 占位符。做不到就别铺 —— 铺了 DSH 一个都不登记,
801
+ // 用户看到的就是「工作区还在、会话全没了」(真实事故)。
802
+ check('node 探测覆盖常见安装位置(不只有 PATH)',
803
+ commonSrc.includes("nodejs\\node.exe")
804
+ && commonSrc.includes('function Get-HostNodeExe'),
805
+ 'dsh-sync-common.ps1')
806
+ check('找不到 Node 时跳过会话还原而不是铺坏文件',
807
+ /if \(\$cwdMap\.Count -gt 0 -or \$projMap\.Count -gt 0\) \{[\s\S]{0,400}跳过会话还原[\s\S]{0,200}return/.test(applySrc),
808
+ 'apply.ps1')
809
+ check('会话还原用的是统一探测到的执行器(Node 或客户端 Electron)',
810
+ applySrc.includes('$nodeRunner = Get-HostNodeRunner $AppRoot')
811
+ && applySrc.includes('$nodeRunner.Electron')
812
+ && commonSrc.includes('function Get-HostNodeRunner'),
813
+ 'apply.ps1')
814
+ // 客户端 Electron 是 GUI 子系统,stdout 抓不到 —— 结果必须落文件,否则面板/日志永远报失败
815
+ check('会话头部修正的结果写成文件(Electron 跑时 stdout 抓不到)',
816
+ helperSrc.includes('const outPath = process.argv[3]')
817
+ && helperSrc.includes('emit(result)')
818
+ && applySrc.includes('$resultPath'),
819
+ 'fix-session-cwd.mjs')
820
+ check('面板有「同步内容」卡:逐组勾选 + 展开明细 + deleteCloud 开关',
821
+ clientSrc.includes('function ScopeCard') && clientSrc.includes('callScope(')
822
+ && clientSrc.includes('同步内容') && clientSrc.includes('Sync content')
823
+ && clientSrc.includes('取消勾选时顺手删掉云端副本'), 'client.js')
824
+ // 必需组(profile)三处钉死:脚本侧判断、宿主保存、面板复选框
825
+ check('必需组在脚本侧钉死(手改 JSON 关掉也按开启处理)',
826
+ commonSrc.includes('$SyncRequiredGroups')
827
+ && /function Test-SyncGroupEnabled[\s\S]{0,260}Test-SyncRequiredGroup/.test(commonSrc),
828
+ 'dsh-sync-common.ps1')
829
+ check('必需组在宿主侧钉死(保存时拒绝写入关闭状态)',
830
+ indexSrc.includes('SCOPE_REQUIRED_GROUPS')
831
+ && /for \(const \[id, g\] of Object\.entries\(groupsIn\)\)[\s\S]{0,260}scopeGroupRequired\(id\)\) continue/.test(indexSrc),
832
+ 'index.js')
833
+ check('必需组在面板上不可勾掉(复选框禁用 + 标注)',
834
+ clientSrc.includes('g.required === true') && clientSrc.includes('必需内容'), 'client.js')
835
+ // 只读优先:不做「勾一下就写盘」,要先点「修改」、再点「保存」
836
+ check('面板默认只读:勾选前必须先点「修改」',
837
+ clientSrc.includes('const [editing, setEditing]')
838
+ && clientSrc.includes("disabled: busy || !editing")
839
+ && clientSrc.includes("M('修改', 'Edit')")
840
+ && /onClick: \(\) => save\(state\)/.test(clientSrc), 'client.js')
841
+ // 展开/收起改成点整行,单独的「明细」按钮要消失
842
+ check('取消「明细」按钮:展开收起靠点当前行',
843
+ !clientSrc.includes("M('明细', 'Details')")
844
+ && clientSrc.includes('onClick: canExpand')
845
+ && clientSrc.includes("expanded ? '▾' : '▸'"), 'client.js')
846
+ check('同步内容卡与问题反馈卡挂在页面最下面(其后不再有别的 Section)', (() => {
847
+ // 顺序:概览 → 同步目标 → 自动化与插件更新 → 退出后执行 → 还原备份 → 同步内容 → 问题反馈;
848
+ // 判据是「顺序」而不是写死紧跟,中间还会插卡(本机路径就插在同步目标之前)。
849
+ const order = ["概览", "同步目标", "自动化与插件更新", "退出后执行", "还原备份", "同步内容", "问题反馈"]
850
+ .map((k) => ({ k, at: clientSrc.indexOf(`Section(M('${k}'`) }))
851
+ if (order.some((p) => p.at < 0)) return false
852
+ if (!order.every((p, i) => (i === 0 ? true : p.at > order[i - 1].at))) return false
853
+ // 问题反馈必须是最后一个 Section
854
+ const tail = clientSrc.slice(order[order.length - 1].at + 1)
855
+ return !/Section\(M\(/.test(tail)
856
+ })(), 'client.js')
857
+ // 「还原备份」卡:地址可改(留空=默认)、列出快照、点「立即还原」先出确认框再排队
858
+ check('控件:还原备份卡有备份目录、快照列表与立即还原',
859
+ clientSrc.includes('backupRoot') && clientSrc.includes('backup.snapshots')
860
+ && clientSrc.includes("M('立即还原', 'Restore now')") && clientSrc.includes("M('还原备份', 'Restore backup')"), 'client.js')
861
+ check('控件:还原先弹确认(差异预览)再排队,不是点了就动手',
862
+ clientSrc.includes("action: 'restore-preview'") && clientSrc.includes("action: 'restore-now'")
863
+ && clientSrc.includes('askRestore') && clientSrc.includes('doRestore')
864
+ && clientSrc.includes('pvRemovePlugins') && clientSrc.includes('pvRemoveFiles'), 'client.js')
865
+ check('控件:快照行显示相对时间、类型徽章与内容摘要',
866
+ clientSrc.includes('const rel = (at)') && clientSrc.includes('kindBadge') && clientSrc.includes('snapSummary'), 'client.js')
867
+ check('控件:三类备份各有还原入口,认不出类型的给手动还原指引(不留死路)',
868
+ clientSrc.includes("kindOf(s) === 'plugin' ? M('回滚插件'") && clientSrc.includes("M('还原会话', 'Restore sessions')")
869
+ && clientSrc.includes("M('手动还原', 'How to restore')") && clientSrc.includes('manualTargets'), 'client.js')
870
+
871
+ // 0.3.25 起「还原」与「立即拉取」共用一条流水线:面板排队 → 客户端退出 → 可见进度窗口执行 → 自动重启
872
+ const restoreScript = [join(pluginRoot, 'runtime', 'restore.ps1'), join(repoRoot, 'restore.ps1')].find((p) => existsSync(p)) || ''
873
+ const restoreSrc = restoreScript ? readFileSync(restoreScript, 'utf8') : ''
874
+ check('post-exit 有 restore 分支:执行体是 restore.ps1,profile 带 -RollbackToPoint、其它类型带 -SnapshotKind',
875
+ postExitSrc.includes("if ($Mode -eq 'restore')")
876
+ && postExitSrc.includes("Find-PluginScript 'restore.ps1'")
877
+ && postExitSrc.includes('RollbackToPoint')
878
+ && postExitSrc.includes("$rargs['SnapshotKind'] = $SnapshotKind"), postExit || 'post-exit.ps1')
879
+ check('post-exit 的 restore 分支沿用同一套返回码判据(哨兵 -1 + 没跑完即失败)',
880
+ /if \(\$Mode -eq 'restore'\)[\s\S]{0,3000}?\$LASTEXITCODE = -1/.test(postExitSrc)
881
+ && /if \(\$Mode -eq 'restore'\)[\s\S]{0,3500}?执行体没有正常跑完/.test(postExitSrc),
882
+ 'post-exit.ps1')
883
+ check('post-exit 的 restore 分支有专属收尾文案',
884
+ postExitSrc.includes('完成(已还原)') && postExitSrc.includes('还原失败'), 'post-exit.ps1')
885
+ check('restore.ps1 提供 -RollbackToPoint 时点回退',
886
+ restoreSrc.includes('[switch]$RollbackToPoint') && restoreSrc.includes('3.5 时点回退'), 'restore.ps1')
887
+ check('时点回退:撤走的插件只删 junction 链接(不穿进去删目标)',
888
+ /if \(\$item\.LinkType\)[\s\S]{0,220}\[IO\.Directory\]::Delete/.test(restoreSrc.replace(/\r/g, '')), 'restore.ps1')
889
+ check('时点回退:写 rollback-manifest.json(可再还原,不留糊涂账)',
890
+ restoreSrc.includes('rollback-manifest.json') && restoreSrc.includes('rollback\\files'), 'restore.ps1')
891
+ check('时点回退:相对路径基准先归一成完整路径(避免 8.3 短名算错)',
892
+ restoreSrc.includes('(Get-Item -LiteralPath $ProfileDir -Force).FullName'), 'restore.ps1')
893
+ check('备份列表带插件数(面板要显示 N 个插件)',
894
+ indexSrc.includes('plugins = Object.keys(pkg?.dependencies') && indexSrc.includes('plugins: x.plugins'), 'index.js')
895
+ check('技能市场台账的勾选项 id 用文件名,不是整个 {id,src} 对象(否则落盘成 [object Object])',
896
+ /items: ledger\.map\(\(f\) => \(\{ id: f\.id, label: f\.id \}\)\)/.test(indexSrc), 'index.js')
897
+ check('restore-now 复用 spawnWatcher,并把快照目录与类型带进执行体',
898
+ /action === 'restore-now'[\s\S]{0,1200}?spawnWatcher\(\{[\s\S]{0,240}?mode: 'restore'/.test(indexSrc)
899
+ && indexSrc.includes("const extraArgs = ['-BackupDir', snap.dir]")
900
+ && indexSrc.includes("extraArgs.push('-SnapshotKind', snap.kind)")
901
+ && indexSrc.includes("extraArgs.push('-PluginDir', PLUGIN_ROOT)"), 'index.js')
902
+ check('restore.ps1 支持 -SnapshotKind 三型(profile / plugin / session)',
903
+ restoreSrc.includes("ValidateSet('profile', 'plugin', 'session')")
904
+ && restoreSrc.includes("$SnapshotKind -eq 'plugin'")
905
+ && restoreSrc.includes("$SnapshotKind -eq 'session'")
906
+ && restoreSrc.includes('function Copy-Tree'), 'restore.ps1')
907
+ check('快照分类不能只看 package.json(profile 也带 dsh 字段)',
908
+ indexSrc.includes('function classifySnapshot') && indexSrc.includes('/^dsh-profile-/i.test(pkgName)')
909
+ && indexSrc.includes("pkgName === PACKAGE_ID"), 'index.js')
910
+ check('restore-preview 与 prepare 共用同一套快照校验(口径不漂移)',
911
+ indexSrc.includes('function resolveSnapshotDir')
912
+ && (indexSrc.match(/resolveSnapshotDir\(dshHome, body\.backupDir\)/g) || []).length >= 2, 'index.js')
913
+ check('还原不需要仓库也能排队(只动本机快照)',
914
+ /const isRestore = action === 'restore-now'/.test(indexSrc) && /if \(!repo && !isRestore\) throw/.test(indexSrc), 'index.js')
915
+ }
916
+
917
+ // 提交说明:面板里填的那句要进 push 脚本,时间由 sync.ps1 执行时追加
918
+ const noted = await call('/config-sync/prepare', {
919
+ method: 'POST',
920
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
921
+ body: JSON.stringify({ action: 'push', message: '修 侧栏入口 "和" 特殊字符' }),
922
+ })
923
+ const notedPayload = JSON.parse(noted.body || '{}')
924
+ if (repoReady) {
925
+ check('prepare(push) 接受提交说明', noted.statusCode === 200 && notedPayload.ok === true, noted.body.slice(0, 160))
926
+ check('提交说明进了脚本(-Message)', existsSync(notedPayload.path || '') && readFileSync(notedPayload.path, 'utf8').includes('-Message'))
927
+ check('提交说明里的双引号被清洗掉',
928
+ Boolean(notedPayload.message) && !notedPayload.message.includes('"'),
929
+ notedPayload.message || '(无)')
930
+ if (existsSync(notedPayload.path || '')) restoreCmd(notedPayload.path)
931
+ } else if (body.repo?.remoteEmpty === true) {
932
+ // 两边都空:这次带说明的 push 就是初始化推送,放行;说明字段照样要清洗
933
+ check('两边都空:带说明的 push 放行(走初始化推送)',
934
+ noted.statusCode === 200 && notedPayload.ok === true, noted.body.slice(0, 160))
935
+ check('提交说明里的双引号被清洗掉',
936
+ Boolean(notedPayload.message) && !notedPayload.message.includes('"'),
937
+ notedPayload.message || '(无)')
938
+ if (existsSync(notedPayload.path || '')) restoreCmd(notedPayload.path)
939
+ check('提交说明清洗在源码里(去双引号)',
940
+ /\$\{.*message.*\}/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8'))
941
+ || /replace\(\/\["\\r\\n\]/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8')),
942
+ 'index.js')
943
+ } else {
944
+ // 仓库还没内容、云端已有内容时,带说明的 push 同样该被拒;说明字段的清洗逻辑用静态断言兜住
945
+ check('本机无内容时:带说明的 push 仍被拒(不被说明字段绕过门禁)',
946
+ noted.statusCode === 400 && /云端仓库已经有内容/.test(notedPayload.error || ''),
947
+ noted.body.slice(0, 160))
948
+ check('提交说明清洗在源码里(去双引号)',
949
+ /\$\{.*message.*\}/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8'))
950
+ || /replace\(\/\["\\r\\n\]/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.js'), 'utf8')),
951
+ 'index.js')
952
+ }
953
+ const pullNote = await call('/config-sync/prepare', {
954
+ method: 'POST',
955
+ headers: { host: 'localhost:3080', 'content-type': 'application/json' },
956
+ body: JSON.stringify({ action: 'pull', message: '不该进拉取脚本' }),
957
+ })
958
+ const pullNotePayload = JSON.parse(pullNote.body || '{}')
959
+ if (pullNote.statusCode === 400) {
960
+ // 两边都空:拉取直接被拒(没有内容可拉),说明字段自然也进不了脚本
961
+ check('两边都空时带说明的拉取同样被拒(说明字段绕不过门禁)',
962
+ /没有内容可拉|连不上云端/.test(pullNotePayload.error || ''), pullNotePayload.error || '(无错误)')
963
+ } else {
964
+ check('拉取脚本不吃提交说明',
965
+ existsSync(pullNotePayload.path || '') && !readFileSync(pullNotePayload.path, 'utf8').includes('不该进拉取脚本'),
966
+ pullNotePayload.path || '(无)')
967
+ if (existsSync(pullNotePayload.path || '')) restoreCmd(pullNotePayload.path)
968
+ }
969
+
970
+ // 配置仓库根目录那 6 个执行体,是「插件还没装 / 正在升级」时的兜底副本。
971
+ // 它们一直靠人工同步,结果漂成半新半旧:sync/apply/common/post-exit 已升到 0.3.23,
972
+ // capture/restore 还停在两天前的旧版 —— 平时不显形,只有 pull 真正走进「仓库副本」
973
+ // 那条兜底路才会跑到旧逻辑。所以按字节比对,漂了就报,不再指望人记得。
974
+ console.log('')
975
+ console.log('== 配置仓库执行体副本一致性 ==')
976
+ const execNames = ['apply.ps1', 'capture.ps1', 'dsh-sync-common.ps1', 'post-exit.ps1', 'restore.ps1', 'sync.ps1']
977
+ // 两种布局都认:发布仓库(<root>\runtime)与配置仓库里的 plugin\ 镜像(<root>\runtime)
978
+ const hereSelf = dirname(fileURLToPath(import.meta.url))
979
+ const pluginRootSelf = existsSync(join(hereSelf, '..', 'package.json')) ? join(hereSelf, '..') : join(hereSelf, '..', '..')
980
+ const pluginRuntime = join(pluginRootSelf, 'runtime')
981
+ if (!existsSync(repoArg) || !existsSync(pluginRuntime) || !repoReady) {
982
+ console.log(` [SKIP] 没有配置仓库内容(${repoArg},mode=${body.repo?.mode || '?'})或没有插件 runtime,跳过逐字节比对`)
983
+ console.log(' (初始化推送会把这几份副本一起写进仓库,届时断言自动恢复)')
984
+ } else {
985
+ for (const name of execNames) {
986
+ const mirror = join(repoArg, name)
987
+ const source = join(pluginRuntime, name)
988
+ let same = false
989
+ let detail = ''
990
+ if (!existsSync(mirror)) detail = `配置仓库没有 ${name}`
991
+ else if (!existsSync(source)) detail = `插件 runtime 没有 ${name}`
992
+ else {
993
+ same = readFileSync(mirror).equals(readFileSync(source))
994
+ if (!same) detail = `副本 ${readFileSync(mirror).length}B / 正本 ${readFileSync(source).length}B,跑 tools/sync-plugin-mirror.ps1 重新同步`
995
+ }
996
+ check(`执行体副本与插件 runtime 逐字节一致:${name}`, same, detail)
997
+ }
998
+ // tools\fix-session-cwd.mjs 同样是随仓库同步的副本,改了插件忘了同步会静默跑旧逻辑
999
+ const mirrorTool = join(repoArg, 'tools', 'fix-session-cwd.mjs')
1000
+ const sourceTool = join(pluginRuntime, 'tools', 'fix-session-cwd.mjs')
1001
+ const toolSame = existsSync(mirrorTool) && existsSync(sourceTool) && readFileSync(mirrorTool).equals(readFileSync(sourceTool))
1002
+ check('执行体副本与插件 runtime 逐字节一致:tools/fix-session-cwd.mjs', toolSame,
1003
+ existsSync(mirrorTool) ? '内容已漂移,跑 tools/sync-plugin-mirror.ps1 重新同步' : '配置仓库没有 tools/fix-session-cwd.mjs')
1004
+ for (const tname of ['session-log-guard.mjs', 'session-log-lib.mjs', 'bili-state.mjs']) {
1005
+ const m = join(repoArg, 'tools', tname)
1006
+ const s = join(pluginRuntime, 'tools', tname)
1007
+ const ok = existsSync(m) && existsSync(s) && readFileSync(m).equals(readFileSync(s))
1008
+ check(`执行体副本与插件 runtime 逐字节一致:tools/${tname}`, ok,
1009
+ !existsSync(m) ? `配置仓库没有 tools/${tname}` : (existsSync(s) ? '内容已漂移,跑 tools/sync-plugin-mirror.ps1 重新同步' : `插件 runtime 没有 tools/${tname}`))
1010
+ }
1011
+ }
1012
+
1013
+ // 内置运行时链接修复(0.3.24):客户端升级会清空 resources\runtime,
1014
+ // 装卸插件的 pnpm 调用随即报 MODULE_NOT_FOUND(真正运行时在 ~\.dsh\dsh-runtimes 下)。
1015
+ // apply 每次落地幂等补回 junction,这 4 条断言盯住「函数在、被调用、不覆盖、探针对」。
1016
+ console.log('')
1017
+ console.log('== 内置运行时链接修复 ==')
1018
+ {
1019
+ const commonPath = join(pluginRuntime, 'dsh-sync-common.ps1')
1020
+ const applyPath = join(pluginRuntime, 'apply.ps1')
1021
+ const commonText = existsSync(commonPath) ? readFileSync(commonPath, 'utf8') : ''
1022
+ const applyText = existsSync(applyPath) ? readFileSync(applyPath, 'utf8') : ''
1023
+ check('common 提供 Repair-PrimaryRuntimeLink 函数',
1024
+ /function\s+Repair-PrimaryRuntimeLink\s*\(/.test(commonText),
1025
+ '插件 runtime 的 dsh-sync-common.ps1 里没有该函数')
1026
+ check('apply.ps1 落地时调用该函数(不靠人手补链接)',
1027
+ /Repair-PrimaryRuntimeLink\s+\$AppRoot\s+\$DshHome/.test(applyText),
1028
+ 'apply.ps1 里找不到调用点,升级后链接不会自动补回')
1029
+ check('已有真实运行时目录时绝不覆盖(只告警不重建)',
1030
+ /LinkType/.test(commonText) && /客户端自带运行时目录存在/.test(commonText) && /本次不动/.test(commonText),
1031
+ '缺少 LinkType 判据:可能把客户端自带的真实目录当成链接处理')
1032
+ check('探针落在 pnpm.mjs 本身,不是只看目录存在',
1033
+ /dependencies\\pnpm\\bin\\pnpm\.mjs/.test(commonText),
1034
+ '探针路径不是 pnpm.mjs,运行时缺文件时会被误判为已就绪')
1035
+ }
1036
+
1037
+ // 空白本机仓库 → 只允许拉取(0.3.26):新机器把路径指到一个空目录不是错误,
1038
+ // 而是「等着从云端拉」的正常状态。断言盯四件事:状态判定、不报异常、push 全线拦住、pull 放行。
1039
+ console.log('')
1040
+ console.log('== 空白本机仓库:只允许拉取 ==')
1041
+ {
1042
+ const indexNew = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1043
+ const clientNew = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1044
+ const syncNew = existsSync(join(pluginRuntime, 'sync.ps1')) ? readFileSync(join(pluginRuntime, 'sync.ps1'), 'utf8') : ''
1045
+ check('index.js 提供 repoPhase 四态判定(ok/empty/missing/unusable)',
1046
+ /function repoPhase\(dir\)/.test(indexNew) && /return others\.length === 0 \? 'empty' : 'unusable'/.test(indexNew),
1047
+ 'repoPhase 缺失或 empty 判据变了:空目录会被当成「不像仓库」继续报异常')
1048
+ check('只有插件自己生成的 同步-*.cmd 与隐藏项算「空」',
1049
+ /同步-\[\\s\\S\]\*\\?\.cmd/i.test(indexNew) || /同步-\[/i.test(indexNew),
1050
+ 'empty 判据没有排除 同步-*.cmd:生成过脚本之后就会被误判成 unusable')
1051
+ check('status 暴露 phase / remoteFiles / pushAllowed / pullAllowed',
1052
+ /phase,\s*\n\s*empty: phase === 'empty'/.test(indexNew)
1053
+ && /remoteFiles,/.test(indexNew) && /remoteEmpty: remoteFiles === 0/.test(indexNew)
1054
+ && /pushAllowed: phase === 'ok' \|\| \(phase === 'empty' && remoteFiles === 0\)/.test(indexNew)
1055
+ && /pullAllowed: phase === 'ok' \|\| \(\(phase === 'empty' \|\| phase === 'missing'\) && remoteFiles !== 0\)/.test(indexNew),
1056
+ 'status 没有暴露新门禁字段(remoteFiles / pushAllowed / pullAllowed),面板只能靠分支数猜')
1057
+ check('仓库三态 mode(ok / await-pull / await-init)按文件数算',
1058
+ /mode: phase === 'ok'[\s\S]{0,120}?remoteFiles === 0 \? 'await-init' : 'await-pull'/.test(indexNew),
1059
+ 'mode 还在看分支数:远端只剩空分支时会被判成 await-pull,拉取只能拉到空目录、死循环')
1060
+ check('远端探测先数分支、再数分支树里的文件(有超时,不写本地 refs)',
1061
+ /function probeRemote\(/.test(indexNew)
1062
+ && /function remoteFileCount\(/.test(indexNew)
1063
+ && /ls-remote --heads/.test(indexNew)
1064
+ && /'ls-tree', '-r', '--name-only', 'FETCH_HEAD'/.test(indexNew)
1065
+ && /timeout: 15000/.test(indexNew),
1066
+ 'probeRemote / remoteFileCount 缺失:判据退回分支数,「有分支但空树」又会被当成有内容')
1067
+ check('空目录的 advice 分「初始化推送」与「执行拉取」两支',
1068
+ /本机仓库\$\{where\},云端仓库也还没有任何内容/.test(indexNew) || /云端仓库也还没有任何内容/.test(indexNew),
1069
+ 'advice 没区分「两边都空」与「本机空但云端有内容」')
1070
+ check('advice 单独说明「云端只剩空分支(历史被删空)」',
1071
+ /云端仓库只有分支、里面一个文件都没有/.test(indexNew),
1072
+ '远端只剩空分支时没有专门说法:用户会以为「云端有内容」而反复点拉取')
1073
+ check('check 在非 ok 状态短路,不去撞空目录的 git',
1074
+ /if \(phase !== 'ok'\) \{[\s\S]{0,220}?autoState\.checking = false/.test(indexNew),
1075
+ 'check 仍会对空目录跑 fetch/drift:lastCheckError 会被填成「读不到远端」')
1076
+ check('push-now 在空目录先探云端:有文件拒绝,判不了或没文件放行',
1077
+ /mode === 'push' && repoPhase\(repo\) !== 'ok'/.test(indexNew)
1078
+ && /probe\.files === null/.test(indexNew)
1079
+ && /云端仓库已经有内容(\$\{probe\.files\} 个文件)/.test(indexNew),
1080
+ 'handleAuto 的 push-now 没按「云端文件数」分流(分支数会把空分支当有内容)')
1081
+ check('prepare 按云端文件数组合脚本(两边都空只生成推送 + 还原)',
1082
+ /action === 'push' && phase !== 'ok'/.test(indexNew)
1083
+ && /cloudEmptyForPrepare \? \['push', 'restore'\] : \['pull', 'restore'\]/.test(indexNew)
1084
+ && /initPush: phase !== 'ok' && cloudEmptyForPrepare/.test(indexNew),
1085
+ 'prepare 仍会为空目录生成拉取脚本,或没有 initPush 标记')
1086
+ check('sync.ps1 的 push 分支按「云端文件数」分流,并能覆盖空分支',
1087
+ /function Get-RemoteFileCount/.test(syncNew)
1088
+ && /function Initialize-EmptyRepo/.test(syncNew)
1089
+ && /云端仓库已经有内容(\$remoteFiles 个文件)/.test(syncNew)
1090
+ && /--force-with-lease/.test(syncNew)
1091
+ && /Initialize-EmptyRepo \$remoteUrlForPush/.test(syncNew),
1092
+ 'sync.ps1 push 仍按分支数拒绝,或空分支覆盖时没有 --force-with-lease(会被 non-fast-forward 拒)')
1093
+ check('初始化推送会写仓库骨架与版本契约',
1094
+ /apply\.ps1', 'capture\.ps1', 'sync\.ps1', 'restore\.ps1', 'post-exit\.ps1', 'dsh-sync-common\.ps1'/.test(syncNew)
1095
+ && /host-contract\.json/.test(syncNew),
1096
+ '初始化推送只推 settings,远端会变成「没有执行体」的半截仓库')
1097
+ check('面板:空目录不算「必须设置」,徽标不标红',
1098
+ /const missing = Boolean\(props\.data\) && !repo\.exists && !repo\.empty/.test(clientNew)
1099
+ && /if \(repo\.empty \|\| repo\.phase === 'missing'\) \{/.test(clientNew)
1100
+ && /const canPush = Boolean\(data && data\.repo && data\.repo\.pushAllowed === true\)/.test(clientNew),
1101
+ 'panel 仍把空目录当成未配置(强制编辑态 + 红色错误)')
1102
+ check('面板:推送/拉取按钮都吃后端门禁,「初始化推送」单独有说法',
1103
+ /const pushAllowed = repo\.pushAllowed === true/.test(clientNew)
1104
+ && /const canPullNow = repo\.pullAllowed === true/.test(clientNew)
1105
+ && /const initMode = repo\.mode === 'await-init'/.test(clientNew)
1106
+ && /初始化推送(会关闭 DSH)/.test(clientNew)
1107
+ && /const canPull = Boolean\(data && data\.repo && data\.repo\.pullAllowed === true\)/.test(clientNew),
1108
+ '面板的按钮门禁没跟后端对齐,或没有「初始化推送」文案')
1109
+ check('面板:待初始化徽标有独立文字与配色',
1110
+ /if \(kind === 'init'\) return M\('待初始化', 'To initialize'\)/.test(clientNew)
1111
+ && /init: 'var\(--dsw-alias-state-warn-tertiary\)'/.test(clientNew),
1112
+ 'kind=init 没有 chipLabel / chipStyle,徽标会掉进「未检测」')
1113
+ }
1114
+
1115
+ // 0.3.36:判据从「云端有几个分支」换成「分支树里有几个文件」,外加推送/拉取两条体检报告。
1116
+ // 这一段不依赖配置仓库内容,仓库是空目录也照跑。
1117
+ console.log('')
1118
+ console.log('== 0.3.36:空分支判据 / 根外路径清单 / 覆盖体检 ==')
1119
+ {
1120
+ const idx = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1121
+ const cli = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1122
+ const syn = existsSync(join(pluginRuntime, 'sync.ps1')) ? readFileSync(join(pluginRuntime, 'sync.ps1'), 'utf8') : ''
1123
+ const cap = existsSync(join(pluginRuntime, 'capture.ps1')) ? readFileSync(join(pluginRuntime, 'capture.ps1'), 'utf8') : ''
1124
+ const app = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
1125
+ check('remoteFileCount 用临时 bare 仓库浅取、只要树对象、探完就删',
1126
+ /function remoteFileCount\(/.test(idx)
1127
+ && /mkdtempSync|init --bare --quiet/.test(idx)
1128
+ && /'--filter=blob:none'/.test(idx)
1129
+ && /'ls-tree', '-r', '--name-only', 'FETCH_HEAD'/.test(idx)
1130
+ && /rmSync/.test(idx),
1131
+ 'remoteFileCount 没有走临时目录 / 浅取 / 清理,判定会拖慢面板或留下垃圾目录')
1132
+ check('sync.ps1 有 Get-RemoteFileCount,且「有分支但 0 文件」时用 --force-with-lease',
1133
+ /function Get-RemoteFileCount/.test(syn)
1134
+ && /\$remoteHadEmptyBranch/.test(syn)
1135
+ && /--force-with-lease/.test(syn)
1136
+ && /不丢数据/.test(syn),
1137
+ '空分支覆盖没有 force-with-lease(会被 non-fast-forward 拒),或没有「不丢数据」的说明')
1138
+ check('capture.ps1 推送后写根外绝对路径清单',
1139
+ /function Write-OutsideRootReport/.test(cap)
1140
+ && /config-sync-absolute-paths\.json/.test(cap)
1141
+ && /Write-OutsideRootReport/.test(cap.split('function Write-OutsideRootReport')[1] || ''),
1142
+ 'capture 没有根外路径体检:换机器拉取才发现路径是死的')
1143
+ check('apply.ps1 覆盖本机配置前比对并写覆盖清单',
1144
+ /\$overwriteItems/.test(app)
1145
+ && /config-sync-overwrite\.json/.test(app)
1146
+ && /本机改动已先备份/.test(app)
1147
+ && /先「推送」再「拉取」/.test(app),
1148
+ 'apply 整份覆盖前不比对:本机未推送的改动会被静默盖掉')
1149
+ check('roots 接口带回 absolutePaths 与 overwrite 两份报告',
1150
+ /absolutePathsPathOf/.test(idx) && /overwritePathOf/.test(idx)
1151
+ && /absolutePaths: \(/.test(idx) && /overwrite: \{/.test(idx),
1152
+ 'GET /config-sync/roots 没带体检报告,面板无从提示')
1153
+ check('面板在本机路径卡下渲染两条告警,并给「用探测值」回填',
1154
+ /data\.absolutePaths && data\.absolutePaths\.total/.test(cli)
1155
+ && /data\.overwrite && data\.overwrite\.total/.test(cli)
1156
+ && /用探测值/.test(cli)
1157
+ && /改动只影响之后的推送\/拉取/.test(cli),
1158
+ '面板没有渲染根外路径 / 覆盖告警,或没有「用探测值」回填按钮')
1159
+ }
1160
+
1161
+ // 任意 git 托管平台(0.3.27):远端地址只校验写法,认证自检提示按 origin 的真实主机名现算,
1162
+ // 不再写死 git@gitee.com —— 否则用 GitHub/GitLab 的人照着提示敲会连到错的主机。
1163
+ console.log('')
1164
+ console.log('== 任意 git 托管平台:提示不写死 gitee ==')
1165
+ {
1166
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1167
+ const commonNew = readFileSync(join(root, 'runtime', 'dsh-sync-common.ps1'), 'utf8')
1168
+ const syncNew = readFileSync(join(root, 'runtime', 'sync.ps1'), 'utf8')
1169
+ const clientNew = readFileSync(join(root, 'client.js'), 'utf8')
1170
+ check('common 提供 Get-RemoteHost(认 git@host / ssh:// / https://)',
1171
+ commonNew.includes('function Get-RemoteHost') && commonNew.includes('^ssh://(?:[^@/]+@)?([^/:]+)'),
1172
+ 'common 里没有主机名解析')
1173
+ check('common 提供 Get-RemoteAuthHint(https 给 ls-remote,ssh 给 ssh -T)',
1174
+ commonNew.includes('function Get-RemoteAuthHint') && commonNew.includes('ls-remote --heads origin') && commonNew.includes('ssh -T git@'),
1175
+ 'https 与 ssh 两种认证没有分开提示')
1176
+ check('sync.ps1 的自检提示不再写死 git@gitee.com',
1177
+ !syncNew.includes('ssh -T git@gitee.com') && (syncNew.match(/Get-RemoteAuthHint/g) || []).length >= 3,
1178
+ '仍有 gitee 硬编码或提示没接上')
1179
+ check('面板占位与说明不再只暗示 Gitee',
1180
+ clientNew.includes('git@<host>:you/dsh-config.git')
1181
+ && clientNew.includes('git@github.com:you/dsh-config.git')
1182
+ && clientNew.includes('自建 Gitea'),
1183
+ '面板还只提 Gitee')
1184
+ }
1185
+
1186
+ // 默认工作区校正(0.3.28):重启客户端之前把 workspace.json 的 defaultWorkspaceId 校正到
1187
+ // default-workspace,否则重启后新开的那条会话会落在「上次用的工作区」上。
1188
+ // 断言只盯结构与时机,不真写用户的 workspace.json。
1189
+ console.log('')
1190
+ console.log('== 默认工作区校正 ==')
1191
+ {
1192
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1193
+ const post = readFileSync(join(root, 'runtime', 'post-exit.ps1'), 'utf8')
1194
+ const host = readFileSync(join(root, 'index.js'), 'utf8')
1195
+ check('post-exit 提供 Set-DefaultWorkspace',
1196
+ post.includes('function Set-DefaultWorkspace'),
1197
+ '没有默认工作区校正函数')
1198
+ const callMatch = post.match(/^ {4}Set-DefaultWorkspace\r?\n/m)
1199
+ check('校正发生在重启之前(RestartClient 里、启动之前调用)',
1200
+ Boolean(callMatch) && callMatch.index < post.indexOf('$how = Start-Detached $exe'),
1201
+ '调用点不在 Start-Detached 之前')
1202
+ check('默认目标认 default-workspace(标题或路径)且可被设置覆盖或关闭',
1203
+ post.includes("$title -eq 'default-workspace'")
1204
+ && post.includes('deepseek-harness\\default-workspace')
1205
+ && post.includes("defaultWorkspace")
1206
+ && post.includes('off|none'),
1207
+ '目标匹配或 off 开关缺失')
1208
+ check('写前备份、写后回读校验(值 + 工作区条数)',
1209
+ post.includes(".bak-' + $stamp") && post.includes('countAfter -ne $countBefore'),
1210
+ '缺少备份或回读校验')
1211
+ check('设置字段 defaultWorkspace 进 read/write 与保存白名单',
1212
+ host.includes('defaultWorkspace: typeof raw.defaultWorkspace')
1213
+ && host.includes('defaultWorkspace: s.defaultWorkspace ||')
1214
+ && host.includes("has('defaultWorkspace')"),
1215
+ 'index.js 没带该字段')
1216
+ }
1217
+
1218
+ // 跨机路径占位符(0.3.30):仓库里不写死盘符,落地时按本机根展开;展开不掉的记 pending 让用户确认。
1219
+ // 只做只读断言(不写真实的 roots.json / 不提交仓库),写入路径留给手工验证。
1220
+ console.log('')
1221
+ console.log('== 跨机路径占位符与问题反馈 ==')
1222
+ {
1223
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
1224
+ const common = readFileSync(join(root, 'runtime', 'dsh-sync-common.ps1'), 'utf8')
1225
+ const captureSrc = readFileSync(join(root, 'runtime', 'capture.ps1'), 'utf8')
1226
+ const applySrc = readFileSync(join(root, 'runtime', 'apply.ps1'), 'utf8')
1227
+ const host = readFileSync(join(root, 'index.js'), 'utf8')
1228
+ const cli = readFileSync(join(root, 'client.js'), 'utf8')
1229
+
1230
+ check('common 提供路径根读写与占位符双向转换',
1231
+ common.includes('function Get-SyncRoots') && common.includes('function Save-SyncRoots')
1232
+ && common.includes('function ConvertTo-TokenText') && common.includes('function Expand-TokenText')
1233
+ && common.includes('function Get-MissingTokens'),
1234
+ '缺占位符函数')
1235
+ check('common 覆盖四种路径写法(原样 / 双反斜杠 / 正斜杠 / 转义斜杠)',
1236
+ common.includes('function Get-PathVariants') && common.includes("$p.Replace($bs, '/')"),
1237
+ '变体列表不全')
1238
+ check('占位符按根长度降序替换(workspaceHome 在 appRoot 之下不会替换错位)',
1239
+ common.includes('Sort-Object { $_.Value.Length } -Descending'),
1240
+ '没有按长度排序')
1241
+ check('capture 写仓库前把本机根换成占位符',
1242
+ captureSrc.includes('ConvertTo-TokenText $txt $roots') && captureSrc.includes('Get-SyncRoots $DshHome $AppRoot $WorkspaceHome'),
1243
+ 'capture 没做归一')
1244
+ check('capture 首次自动落一份 config-sync-roots.json',
1245
+ captureSrc.includes('Save-SyncRoots $DshHome $roots'),
1246
+ '没写 roots 文件')
1247
+ const settingsCount = (captureSrc.match(/Repo = 'settings\\/g) || []).length
1248
+ const applyCount = (applySrc.match(/Repo = 'settings\\/g) || []).length
1249
+ check('capture 覆盖到各插件自己的配置(不止 4 个)', settingsCount >= 11, `实际 ${settingsCount} 项`)
1250
+ check('capture 与 apply 的 settings 清单一致', settingsCount === applyCount, `capture ${settingsCount} / apply ${applyCount}`)
1251
+ check('apply 展开占位符,缺值的跳过不写并记 pending',
1252
+ applySrc.includes('Expand-TokenText $txt $roots') && applySrc.includes('Write-PendingPaths $DshHome $pendingItems')
1253
+ && applySrc.includes('continue'),
1254
+ 'apply 没按缺失跳过')
1255
+ check('workspace.json(DSH 工作区登记)进了同步范围',
1256
+ captureSrc.includes("storages\\workspace.json") && applySrc.includes("storages\\workspace.json"),
1257
+ '工作区登记表没同步')
1258
+ check('workspace-archives.v1.json(工作区隐藏/归档状态)进了同步范围',
1259
+ captureSrc.includes('settings\\workspace-archives.json') && captureSrc.includes('dsh-session-manager\\workspace-archives.v1.json')
1260
+ && applySrc.includes('settings\\workspace-archives.json') && applySrc.includes('dsh-session-manager\\workspace-archives.v1.json'),
1261
+ '工作区隐藏状态没纳入 settingsMap(A 机隐藏的工作区会带到 B 机显示)')
1262
+ check('面板有「本机路径」卡:只读展示 + 「修改」进编辑 + 保存',
1263
+ cli.includes("M('本机路径', 'Local paths')") && cli.includes("M('修改', 'Edit')")
1264
+ && cli.includes('callRoots') && cli.includes('setCustom') && cli.includes('addCustom'),
1265
+ 'client.js 缺本机路径卡的修改态')
1266
+ check('本机路径卡默认只读(值用等宽字展示,token 作灰字说明)',
1267
+ cli.includes('const isEditing = editing || forced') && cli.includes('{{ROOT:${k}}}'),
1268
+ '只读态/自选目录没渲染')
1269
+ check('面板会列出待确认项(token + 文件 + 说明)',
1270
+ cli.includes('data.missing') && cli.includes('m.token'),
1271
+ '待确认清单没渲染')
1272
+ check('面板有「问题反馈」卡:提交 + 列表 + 连接状态 + 令牌入口',
1273
+ cli.includes("M('问题反馈', 'Feedback')") && cli.includes('callFeedback')
1274
+ && cli.includes('st.connected') && cli.includes("query: { action: 'token' }")
1275
+ && cli.includes("query: { action: 'flush' }"),
1276
+ 'client.js 缺反馈卡')
1277
+ check('反馈走 GitHub Issue:建 issue + 列表 + 关单 + 离线队列',
1278
+ host.includes('GH_FEEDBACK_LABEL') && host.includes('/repos/${repo}/issues')
1279
+ && host.includes('labels: [GH_FEEDBACK_LABEL]')
1280
+ && host.includes('config-sync-feedback-outbox.json') && host.includes("action === 'flush'")
1281
+ && host.includes("method: 'PATCH'"),
1282
+ 'index.js 没走 Issue')
1283
+ check('令牌自动从本机 git 凭据取,落到本机私有文件',
1284
+ host.includes('tokenFromGitCredential') && host.includes('config-sync-gh.json')
1285
+ && host.includes('credential') && host.includes('fill'),
1286
+ '缺自动取令牌')
1287
+ check('反馈正文自动附环境块(版本/机器/时间)',
1288
+ host.includes('### 环境 / Environment') && host.includes('issueBodyOf'),
1289
+ '没附环境信息')
1290
+ check('读不需要令牌:带令牌失败自动退回匿名',
1291
+ host.includes("const attempts = g.token ? [g.token, ''] : ['']") && host.includes('readAnon'),
1292
+ '没有匿名降级')
1293
+ check('关单只有仓库所有者能点(服务端挡别人的令牌)',
1294
+ host.includes('ownerOf') && host.includes('onlyCloseByOwner'.replace('onlyCloseByOwner', 'canClose'))
1295
+ && host.includes("login.toLowerCase() !== owner.toLowerCase()"),
1296
+ '服务端没校验所有者')
1297
+ check('无令牌时提交不失败,给浏览器预填链接',
1298
+ host.includes('newIssueUrl') && host.includes('issues/new?') && host.includes('needToken'),
1299
+ '没有无令牌降级')
1300
+ check('面板按权限置灰关单按钮',
1301
+ cli.includes('!st.canClose') && cli.includes("M('仅所有者', 'Owner only')") && cli.includes('fallbackUrl'),
1302
+ '面板没做权限态')
1303
+ check('反馈列表可按状态筛选 + 关键词搜索',
1304
+ cli.includes("seg('open'") && cli.includes("seg('closed'") && cli.includes("seg('all'")
1305
+ && cli.includes('setKw') && cli.includes('st.counts'),
1306
+ '没有筛选/查询')
1307
+
1308
+ const rootsGet = await call('/config-sync/roots', { headers: { host: 'localhost:3080' } })
1309
+ const rootsBody = JSON.parse(rootsGet.body || '{}')
1310
+ check('GET /config-sync/roots 返回本机根 + 探测值 + 待确认清单',
1311
+ rootsBody.ok === true && rootsBody.roots && typeof rootsBody.roots.appRoot === 'string'
1312
+ && rootsBody.detected && Array.isArray(rootsBody.missing),
1313
+ '结构不全')
1314
+ check('roots 的待确认项带人话说明(不是只给 token)',
1315
+ rootsBody.missing.every((m) => typeof m.token === 'string' && typeof m.hint === 'string'),
1316
+ '缺 hint')
1317
+
1318
+ const fbGet = await call('/config-sync/feedback', { headers: { host: 'localhost:3080' } })
1319
+ const fbBody = JSON.parse(fbGet.body || '{}')
1320
+ check('GET /config-sync/feedback 返回连接状态 + Issue 列表 + 待发队列',
1321
+ fbBody.ok === true && Array.isArray(fbBody.items) && typeof fbBody.connected === 'boolean'
1322
+ && typeof fbBody.repo === 'string' && Array.isArray(fbBody.outbox) && typeof fbBody.ghFile === 'string'
1323
+ && typeof fbBody.canClose === 'boolean' && typeof fbBody.owner === 'string',
1324
+ JSON.stringify(fbBody).slice(0, 400))
1325
+ check('GET /config-sync/feedback 同时给出 open/closed/total 计数',
1326
+ fbBody.counts && typeof fbBody.counts.open === 'number' && typeof fbBody.counts.closed === 'number'
1327
+ && typeof fbBody.counts.total === 'number',
1328
+ JSON.stringify(fbBody.counts))
1329
+ check('跨站请求被拒(roots)', await (async () => {
1330
+ const r = await call('/config-sync/roots', {
1331
+ method: 'POST',
1332
+ headers: { host: 'localhost:3080', origin: 'https://evil.example.com', 'content-type': 'application/json' },
1333
+ body: '{}',
1334
+ })
1335
+ return r.statusCode === 403
1336
+ })(), '没拦住')
1337
+ }
1338
+
1339
+ // 0.3.37:本机路径区默认不进页面,入口只有一个标题行按钮
1340
+ console.log('')
1341
+ console.log('== 0.3.37:本机路径区默认不进页面 ==')
1342
+ {
1343
+ const index37 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1344
+ const client37 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1345
+ check('status 给出三个计数 + 告警数(面板据此决定按钮要不要变橙)',
1346
+ /localPaths: \(\(\) => \{/.test(index37)
1347
+ && /const total = pending \+ absolute \+ overwrite/.test(index37)
1348
+ && /alert: total, total/.test(index37),
1349
+ 'status 没给 localPaths 计数/告警数:面板只能把整张卡摊在页面上当提示')
1350
+ check('本机路径区只由标题行按钮控制(组件不再自己 return null)',
1351
+ /const rootsCard = showRoots \? h\(RootsCard, \{ onRootsSaved: refresh \}\) : null/.test(client37)
1352
+ && !/props\.forceShow/.test(client37),
1353
+ '显示条件不在父层:组件 return null 时 Section 仍会渲染空标题')
1354
+ const st37 = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
1355
+ check('status 运行时真的带 localPaths 计数与告警数(面板按钮靠它变橙)',
1356
+ Boolean(st37.localPaths) && typeof st37.localPaths.total === 'number'
1357
+ && typeof st37.localPaths.pending === 'number' && typeof st37.localPaths.alert === 'number',
1358
+ JSON.stringify(st37.localPaths))
1359
+ }
1360
+
1361
+ console.log('')
1362
+ console.log('== 0.3.41:status 提速(不再递归统计备份) ==')
1363
+ {
1364
+ const index41 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1365
+ const client41 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1366
+ check('备份列表不再递归数文件/体积(92 份快照 4.8 万文件曾要 7.7 秒)',
1367
+ /files: null, bytes: null, hasProfile, plugins, bundles/.test(index41)
1368
+ && !/bytes \+= statSync\(p\)\.size/.test(index41),
1369
+ 'inspectBackup 仍在逐个 statSync 统计每个快照')
1370
+ check('远端探测带预算 + 启动预热(status 不再等满一次 ls-remote)',
1371
+ /function probeRemoteQuick\(url, settings, budgetMs\)/.test(index41)
1372
+ && /function warmRemoteProbe\(config\)/.test(index41)
1373
+ && /await probeRemoteQuick\(remoteProbeUrl, settings, 2500\)/.test(index41),
1374
+ '缺 probeRemoteQuick / warmRemoteProbe / 调用处')
1375
+ check('远端探测缓存拉长到 5 分钟', /REMOTE_PROBE_TTL = 300000/.test(index41))
1376
+ check('前端 status 请求有超时与 3 次重试', /new AbortController\(\)/.test(client41)
1377
+ && /已自动重试 3 次/.test(client41))
1378
+ const t41 = Date.now()
1379
+ const st41 = JSON.parse((await call('/config-sync/status', { headers: { host: 'localhost:3080' } })).body || '{}')
1380
+ const ms41 = Date.now() - t41
1381
+ check('status 实测在 3 秒内答完(当天首次含一次远端探测预算)',
1382
+ st41.ok === true && ms41 < 3000, `${ms41}ms`)
1383
+ check('备份快照列表仍可用:给名字/时间/插件数,体积字段为空',
1384
+ Boolean(st41.backup) && (st41.backup.count === 0 || (Array.isArray(st41.backup.snapshots)
1385
+ && st41.backup.snapshots.every((s) => s.files === null && s.bytes === null))),
1386
+ JSON.stringify(st41.backup && { count: st41.backup.count, first: st41.backup.snapshots && st41.backup.snapshots[0] }))
1387
+ }
1388
+
1389
+ console.log('')
1390
+ console.log('== 0.3.43:根外路径清单只在「配置来自别的机器」时提示 ==')
1391
+ {
1392
+ const src43 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1393
+ const client43 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1394
+ const cap43 = existsSync(join(pluginRootSelf, 'runtime', 'capture.ps1')) ? readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8') : ''
1395
+ check('报告归属判定:记录机器名 + 只在别的机器写的清单才算告警',
1396
+ src43.includes('function localMachineName') && src43.includes('function sameMachine')
1397
+ && src43.includes('absFromOtherMachine') && src43.includes('const absolute = absFromOther'), 'index.js 的 localPaths 计数')
1398
+ check('推荐地址:先按对方根映射,再按同名目录兜底,都没有就说没有',
1399
+ src43.includes('function suggestLocalPathFor') && src43.includes("kind: 'root'")
1400
+ && src43.includes("kind: 'namesake'") && src43.includes("kind: 'none'")
1401
+ && src43.includes('function candidateParentDirs'), 'index.js 的推荐算法')
1402
+ check('清单只扫配置类文件(会话/工作区/记忆不参与)',
1403
+ Boolean(cap43) && cap43.includes('$confTop')
1404
+ && cap43.includes("'local-plugins'") && cap43.includes("$rel0 -notmatch 'node_modules'"),
1405
+ 'capture.ps1 的扫描范围')
1406
+ check('报告带 machine 与当时的根值,供本机映射用',
1407
+ Boolean(cap43) && cap43.includes('machine = $machine') && cap43.includes('roots = [ordered]@'),
1408
+ 'capture.ps1 的报告结构')
1409
+ check('协议头误匹配被过滤(s://1v3... 不再当成盘符)',
1410
+ Boolean(cap43) && cap43.includes("if ($p -match '://') { continue }"), 'capture.ps1')
1411
+ const client43x = client43
1412
+ check('面板:只在 fromOtherMachine 时渲染跨机清单,并给「采纳」按钮',
1413
+ client43x.includes('data.absolutePaths.fromOtherMachine') && client43x.includes('adoptAbsolute')
1414
+ && client43x.includes('adoptAbsolute(it)'), 'client.js')
1415
+ check('面板不再用旧文案「仓库里有 N 处绝对路径不在任何已确认根下」',
1416
+ !client43.includes('仓库里有 ${data.absolutePaths.total} 处绝对路径'), 'client.js')
1417
+ }
1418
+
1419
+ console.log('')
1420
+ console.log('== 0.3.44:工作区与会话的路径也按本机落点推断 ==')
1421
+ {
1422
+ const cap44 = readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8')
1423
+ const app44 = readFileSync(join(pluginRootSelf, 'runtime', 'apply.ps1'), 'utf8')
1424
+ const hel44 = readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'fix-session-cwd.mjs'), 'utf8')
1425
+ const cli44 = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1426
+ const idx44 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1427
+ check('报告分两类:配置类 + 工作区/会话记录,各自限额',
1428
+ cap44.includes('$dataTop') && cap44.includes("'workspace', 'conversations'")
1429
+ && cap44.includes('totalData = $nData') && cap44.includes('$scope = if ($dataTop')
1430
+ && cap44.includes('$nData -ge 30') && cap44.includes('$nConf -ge 50'), 'capture.ps1 的扫描范围')
1431
+ check('清单项带 scope,面板才能分两组列',
1432
+ idx44.includes("scope: String(it.scope || 'config')"), 'index.js 的 items 结构')
1433
+ check('apply 用登记表的 sessionIds 反查本机工作区路径,并交给 helper 改写 projcache',
1434
+ app44.includes('$projMap') && app44.includes('foreach ($sid in @($w.sessionIds))')
1435
+ && app44.includes('projcache = $projMap') && app44.includes('$cwdMap.Count -gt 0 -or $projMap.Count -gt 0'),
1436
+ 'apply.ps1 没把 projcache 的 cwd 对齐')
1437
+ check('helper 只替换 identity.cwd 那一个字符串,且幂等',
1438
+ hel44.includes('spec.projcache') && hel44.includes('result.projFixed')
1439
+ && hel44.includes('record.identity.cwd !== target')
1440
+ && hel44.includes('if (cur === target) { result.projAlreadyOk++'),
1441
+ 'fix-session-cwd.mjs 的 projcache 处理')
1442
+ check('面板把配置与「工作区与会话记录」分两组显示',
1443
+ cli44.includes("it.scope === 'data'") && cli44.includes('工作区与会话记录里的路径'),
1444
+ 'client.js 没分组')
1445
+ }
1446
+
1447
+ console.log('')
1448
+ console.log('== 0.3.54:三处纯性能改动(行为不变) ==')
1449
+ {
1450
+ const cap54 = readFileSync(join(pluginRootSelf, 'runtime', 'capture.ps1'), 'utf8')
1451
+ const sync54 = readFileSync(join(pluginRootSelf, 'runtime', 'sync.ps1'), 'utf8')
1452
+ check('capture 有 -DeepVerify,且深校验开关走 $script:CmpDeep',
1453
+ /\[switch\]\$DeepVerify/.test(cap54) && cap54.includes('$script:CmpDeep')
1454
+ && cap54.includes('function Test-TreeFileChanged'), 'capture.ps1 的深校验开关')
1455
+ check('快筛只比 Length / LastWriteTimeUtc,不一致才 Get-NormalizedHash',
1456
+ cap54.includes('$srcInfo.Length') && cap54.includes('$srcInfo.LastWriteTimeUtc')
1457
+ && cap54.includes('Get-NormalizedHash'), 'capture.ps1 的比较逻辑')
1458
+ check('批量 FileInfo + 字典比对,不再逐文件 Test-Path 父目录',
1459
+ cap54.includes('function Get-TreeCmpSummary') && cap54.includes('$dstRels')
1460
+ && cap54.includes('$madeDirs'), 'capture.ps1 的批量比对')
1461
+ check('sync 把 DeepVerify 透传给 capture', sync54.includes("$captureArgs['DeepVerify'] = $true"))
1462
+ check('历史扫描按提交缓存:commit 相同或是 HEAD 祖先就跳过',
1463
+ sync54.includes('sync-history-scan.json') && sync54.includes('$needHistoryScan')
1464
+ && sync54.includes('merge-base --is-ancestor'), 'sync.ps1 的历史扫描缓存')
1465
+ check('有 -ScanHistory 强制全量,推送被拒时也补一次全量',
1466
+ /\[switch\]\$ScanHistory/.test(sync54) && sync54.includes('$historyFullyScanned'),
1467
+ 'sync.ps1 的扫描强制/补扫')
1468
+ check('拉取改成 fetch + merge --ff-only(不再 git pull 的第二次往返)',
1469
+ sync54.includes("merge --ff-only origin/' + $branch") && sync54.includes('$fetchedThisRun')
1470
+ && !sync54.includes('" pull --ff-only'), 'sync.ps1 的拉取命令')
1471
+ check('空扫描结果不写成 `,$res`(否则空仓库误报 1 个超限文件 0.0 MB)',
1472
+ sync54.includes('function Get-OversizedHistory') && !/^\s*return ,\$res\b/m.test(sync54),
1473
+ 'Get-OversizedHistory 的返回值')
1474
+ }
1475
+
1476
+ console.log('== 0.3.68:会话投影缓存守卫(agent-busy 自动清缓存) ==')
1477
+ {
1478
+ const guardSrc = readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'session-cache-guard.mjs'), 'utf8')
1479
+ const indexSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1480
+ const clientSrc = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1481
+
1482
+ check('守卫库导出 runGuard / clearSessionCaches / appendGuardLog / scanSessionCaches',
1483
+ /export function runGuard/.test(guardSrc) && /export function clearSessionCaches/.test(guardSrc)
1484
+ && /export function appendGuardLog/.test(guardSrc) && /export function scanSessionCaches/.test(guardSrc))
1485
+ check('判定同时要求:缓存标空 + 日志里有对话 + 日志比缓存新',
1486
+ guardSrc.includes('if (rec.blank !== true) continue')
1487
+ && guardSrc.includes('const progressed = head.hasTurn || head.hasUser')
1488
+ && guardSrc.includes('head.tailSeq <= rec.maxSeq'), '守卫的三重判据')
1489
+ check('清理只挪走不改内容:写备份目录、全程不 unlink',
1490
+ guardSrc.includes("'session-cache-guard-backup'") && guardSrc.includes('renameSync')
1491
+ && !guardSrc.includes('unlinkSync'), '只 rename 到备份目录')
1492
+ check('宿主导入守卫库并注册 /config-sync/cache-guard',
1493
+ indexSrc.includes("from './runtime/tools/session-cache-guard.mjs'")
1494
+ && indexSrc.includes("const ROUTE_CACHE_GUARD = '/config-sync/cache-guard'")
1495
+ && indexSrc.includes('handleCacheGuard'), 'index.js 的接线')
1496
+ check('设置里有 cacheGuard 开关(默认开:raw.cacheGuard !== false)',
1497
+ indexSrc.includes('cacheGuard: raw.cacheGuard !== false')
1498
+ && indexSrc.includes('cacheGuard: s.cacheGuard !== false'), 'readSettings / writeSettings')
1499
+ check('启动后挂定时扫描,且受开关控制',
1500
+ indexSrc.includes('function scheduleCacheGuard(config)')
1501
+ && indexSrc.includes('scheduleCacheGuard(config)')
1502
+ && indexSrc.includes("readSettings(dshHomeOf(config)).cacheGuard === false"), 'scheduleCacheGuard')
1503
+ check('status 里带 cacheGuard 状态快照',
1504
+ indexSrc.includes('cacheGuard: cacheGuardSnapshot(config)'), 'inspect() 的返回体')
1505
+ check('四种 action:scan / sweep / clear / busy',
1506
+ indexSrc.includes("action === 'scan'") && indexSrc.includes("action === 'sweep'")
1507
+ && indexSrc.includes("action === 'clear'") && indexSrc.includes("action === 'busy'"), 'handleCacheGuard 的分支')
1508
+ check('客户端包了 sessions.create,撞 agent-busy 才介入',
1509
+ clientSrc.includes('function guardSessionCreate(sessions)')
1510
+ && clientSrc.includes('sessions.create = async function patchedCreate')
1511
+ && clientSrc.includes("const BUSY_RE = /session\\/agent-busy"), 'client.js 的守卫')
1512
+ check('重试前去掉旧 sessionId(否则会再撞同一堵墙)',
1513
+ clientSrc.includes('delete retry.sessionId'), 'patchedCreate 的重试参数')
1514
+ check('客户端把 sessionId 上报给宿主',
1515
+ clientSrc.includes("action: 'busy', sessionId: sessionId || ''"), 'reportAgentBusy')
1516
+
1517
+ const gGet = await call('/config-sync/cache-guard', { headers: { host: 'localhost:3080' } })
1518
+ const gBody = JSON.parse(gGet.body || '{}')
1519
+ check('GET /config-sync/cache-guard 返回 200 且只读',
1520
+ gGet.statusCode === 200 && gBody.ok === true && typeof gBody.scanned === 'number'
1521
+ && Array.isArray(gBody.stale) && typeof gBody.staleCount === 'number', gGet.body.slice(0, 200))
1522
+ check('GET 不动手:applied=false 且 removed 为空',
1523
+ gBody.applied === false && Array.isArray(gBody.removed) && gBody.removed.length === 0, gGet.body.slice(0, 200))
1524
+ const gCross = await call('/config-sync/cache-guard', {
1525
+ method: 'POST',
1526
+ headers: { host: 'localhost:3080', 'sec-fetch-site': 'cross-site' },
1527
+ body: JSON.stringify({ action: 'sweep' }),
1528
+ })
1529
+ check('跨站 POST 被 403 挡住', gCross.statusCode === 403, String(gCross.statusCode))
1530
+ const gClear = await call('/config-sync/cache-guard', {
1531
+ method: 'POST',
1532
+ headers: { host: 'localhost:3080' },
1533
+ body: JSON.stringify({ action: 'clear', ids: [] }),
1534
+ })
1535
+ const gClearBody = JSON.parse(gClear.body || '{}')
1536
+ check('clear 不给 ids 时 400 且 ok=false',
1537
+ gClear.statusCode === 400 && gClearBody.ok === false, gClear.body.slice(0, 160))
1538
+ }
1539
+
1540
+ console.log('')
1541
+ console.log('== billion-context 压缩状态跨机搬运 ==')
1542
+ {
1543
+ // DSH 原生 compaction 被 bili 接管后,真正的压缩记录在 bili 自己的 SQLite 里;
1544
+ // 只带会话日志会让另一台机器把未压缩的全量 surface 发出去并报 CONTEXT_WINDOW_EXCEEDED。
1545
+ const toolPath = join(pluginRootSelf, 'tools', 'bili-state.mjs')
1546
+ const toolRuntime = join(pluginRuntime, 'tools', 'bili-state.mjs')
1547
+ check('提供 tools/bili-state.mjs', existsSync(toolPath), toolPath)
1548
+ check('runtime/tools 下也有同一份(tgz 只打 runtime 时也在包里)',
1549
+ existsSync(toolRuntime) && existsSync(toolPath) && readFileSync(toolRuntime).equals(readFileSync(toolPath)))
1550
+ const biliSrc = existsSync(toolPath) ? readFileSync(toolPath, 'utf8') : ''
1551
+ check('支持 export / import / sync / probe 四个子命令',
1552
+ ["'export'", "'import'", "'sync'", "'probe'"].every((k) => biliSrc.includes(`cmd === ${k}`)))
1553
+ check('导出默认不带 messages 正文(体积可控)',
1554
+ biliSrc.includes("omitted: ['messages'") || biliSrc.includes('omitted: [\'messages\''), 'export 的 omitted 字段')
1555
+ check('导出不写 metadata_json(2.4MB 级缓存,且 NOT NULL 会炸)',
1556
+ biliSrc.includes('delete row.metadata_json'))
1557
+ check('本机没有 bili 时静默跳过(noBili 而不是报错)',
1558
+ biliSrc.includes('noBili'))
1559
+ check('BILI_DATA_DIR 指到哪就用哪,不回头猜用户主目录',
1560
+ biliSrc.includes('显式指定即视为权威') || biliSrc.includes('return null\r\n }'))
1561
+
1562
+ const commonText2 = existsSync(join(pluginRuntime, 'dsh-sync-common.ps1')) ? readFileSync(join(pluginRuntime, 'dsh-sync-common.ps1'), 'utf8') : ''
1563
+ const captureText2 = existsSync(join(pluginRuntime, 'capture.ps1')) ? readFileSync(join(pluginRuntime, 'capture.ps1'), 'utf8') : ''
1564
+ const applyText2 = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
1565
+ check('common 提供 Invoke-BiliStateSync / Write-BiliStateSyncReport',
1566
+ /function\s+Invoke-BiliStateSync\s*\{/.test(commonText2) && /function\s+Write-BiliStateSyncReport\s*\(/.test(commonText2))
1567
+ check('capture 推送时导出压缩状态(否则 B 机拿不到)',
1568
+ /Invoke-BiliStateSync\s+-Mode\s+'export'/.test(captureText2))
1569
+ check('apply 拉取时导入压缩状态',
1570
+ /Invoke-BiliStateSync\s+-Mode\s+'import'/.test(applyText2))
1571
+ check('apply 只在仓库里有该目录时才导入(首次导出前为空属正常)',
1572
+ /Test-Path\s+-LiteralPath\s+\$biliRepo/.test(applyText2))
1573
+ check('压缩状态按会话导出,不是整库拷贝',
1574
+ captureText2.includes('$touchedSids') && captureText2.includes(`'billion_context'`))
1575
+ }
1576
+
1577
+ console.log('')
1578
+ console.log('== 同步清单的两类新提示 ==')
1579
+ {
1580
+ const commonText3 = existsSync(join(pluginRuntime, 'dsh-sync-common.ps1')) ? readFileSync(join(pluginRuntime, 'dsh-sync-common.ps1'), 'utf8') : ''
1581
+ const applyText3 = existsSync(join(pluginRuntime, 'apply.ps1')) ? readFileSync(join(pluginRuntime, 'apply.ps1'), 'utf8') : ''
1582
+ const postText3 = existsSync(join(pluginRuntime, 'post-exit.ps1')) ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
1583
+ const indexText3 = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1584
+ const clientText3 = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1585
+ check('common 的 byKind 收 plugin-missing / context-state',
1586
+ commonText3.includes("'plugin-missing'") && commonText3.includes("'context-state'"))
1587
+ check('apply 记 plugin-missing(插件没装好要能看见)',
1588
+ /Add-SyncNotice\s+-Kind\s+'plugin-missing'/.test(applyText3))
1589
+ check('压缩状态缺失记 context-state(压缩状态没跟过来要能看见)',
1590
+ /Add-SyncNotice\s+-Kind\s+'context-state'/.test(commonText3))
1591
+ check('post-exit 汇总里带这两类标题',
1592
+ postText3.includes('plugin-missing') && postText3.includes('context-state'))
1593
+ check('index.js 白名单含这两类(否则会被降级成 skipped)',
1594
+ indexText3.includes("'plugin-missing'") && indexText3.includes("'context-state'"))
1595
+ check('client.js 给这两类中文文案',
1596
+ clientText3.includes("'plugin-missing'") && clientText3.includes("'context-state'"))
1597
+ }
1598
+
1599
+ console.log('')
1600
+
1601
+ console.log('')
1602
+ console.log('== 工作区显示状态卡片 ==')
1603
+ {
1604
+ const wvTool = join(pluginRootSelf, 'runtime', 'tools', 'workspace-view.mjs')
1605
+ const wvSrc = existsSync(wvTool) ? readFileSync(wvTool, 'utf8') : ''
1606
+ check('workspace-view 工具模块存在且导出三函数',
1607
+ wvSrc.includes('export function readView') && wvSrc.includes('export function setWorkspaceState') && wvSrc.includes('export function setSessionState'), 'runtime/tools/workspace-view.mjs')
1608
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1609
+ check('宿主导入 workspace-view 并注册 /config-sync/workspace-view',
1610
+ idxSrc.includes("from './runtime/tools/workspace-view.mjs'")
1611
+ && idxSrc.includes("const ROUTE_WORKSPACE_VIEW = '/config-sync/workspace-view'")
1612
+ && idxSrc.includes('handleWorkspaceView'), 'index.js 的接线')
1613
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1614
+ check('客户端有 WorkspaceViewCard 且三态与会话独立操作都接到路由',
1615
+ cliSrc.includes('function WorkspaceViewCard()')
1616
+ && cliSrc.includes("fetch('/config-sync/workspace-view'")
1617
+ && cliSrc.includes("action: 'workspace'") && cliSrc.includes("action: 'session'")
1618
+ && cliSrc.includes("M('归档工作区', 'Archive workspace')") && cliSrc.includes("M('隐藏会话', 'Sessions hidden')")
1619
+ && cliSrc.includes('workspaceViewCard'), 'client.js 的卡片')
1620
+ check('面板新增「工作区显示」分区', cliSrc.includes("Section(M('工作区显示', 'Workspace visibility')"), '分区装配')
1621
+ }
1622
+
1623
+ console.log('')
1624
+ console.log('== 0.3.82:工作区显示卡片折叠智能体 + 隐藏/显示即时生效 ==')
1625
+ {
1626
+ const wvSrc = existsSync(join(pluginRootSelf, 'runtime', 'tools', 'workspace-view.mjs')) ? readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'workspace-view.mjs'), 'utf8') : ''
1627
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1628
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1629
+
1630
+ // 1) 智能体折叠:标题提取同时给出 origin,readView 支持 includeAgents 过滤
1631
+ check('智能体折叠:titleFromFile 同时返回 origin',
1632
+ wvSrc.includes("let result = { title: '', origin: '', blank: false }")
1633
+ && wvSrc.includes('if (!origin && ev.type === \'session\')')
1634
+ && wvSrc.includes('origin,'), 'workspace-view.mjs 的头事件解析')
1635
+ check('智能体折叠:readView 默认过滤 origin=subagent 并回报 agentHidden',
1636
+ wvSrc.includes('const includeAgents = options.includeAgents === true')
1637
+ && wvSrc.includes("agent: meta.origin === 'subagent'")
1638
+ && wvSrc.includes('let sessions = includeAgents ? all : all.filter((s) => !s.agent)')
1639
+ && wvSrc.includes('agentHidden: totalAgents'), 'workspace-view.mjs 的 readView')
1640
+ check('智能体折叠:卡片默认不显示、可勾选「显示智能体」',
1641
+ cliSrc.includes('const [showAgents, setShowAgents] = react.useState(false)')
1642
+ && cliSrc.includes("M('显示智能体', 'Show agents')")
1643
+ && cliSrc.includes("q.push('agents=1')"), 'client.js 的勾选框')
1644
+
1645
+ // 2) 即时生效:走 workspaceRegistry 而不是直接改文件
1646
+ check('即时生效:workspace-view 导出实时通道两函数',
1647
+ wvSrc.includes('export async function setWorkspaceStateLive')
1648
+ && wvSrc.includes('export async function setSessionStateLive')
1649
+ && wvSrc.includes('registry.archiveSession(sessionId, { stopActivity: false })')
1650
+ && wvSrc.includes('registry.unarchiveSession(sessionId)'), 'workspace-view.mjs 的实时通道')
1651
+ check('即时生效:宿主惰性取 workspaceRegistry',
1652
+ idxSrc.includes('let ctxRef = null')
1653
+ && idxSrc.includes('function workspaceRegistryOf()')
1654
+ && idxSrc.includes("ctx.get('workspaceRegistry')")
1655
+ && idxSrc.includes('ctxRef = ctx || null'), 'index.js 的 registry 取用')
1656
+ check('即时生效:路由改用 Live 版本并透传 registry',
1657
+ idxSrc.includes("import { setWorkspaceStateLive, setSessionStateLive } from './runtime/tools/workspace-view.mjs'")
1658
+ && idxSrc.includes('await setWorkspaceStateLive(') && idxSrc.includes('await setSessionStateLive(')
1659
+ && idxSrc.includes('{ registry, includeAgents: withAgents, includeBlank: withBlank }'), 'index.js 的 handleWorkspaceView')
1660
+ check('即时生效:registry 拿不到时退回文件写法并标记 live:false',
1661
+ wvSrc.includes('return { ...setWorkspaceState(dshHome, workspaceId, state), live: false }')
1662
+ && wvSrc.includes("live: false, fallbackFrom: 'registry'"), 'workspace-view.mjs 的降级')
1663
+ check('即时生效:卡片按 live 给不同提示(不再说「重启后生效」)',
1664
+ cliSrc.includes("d.live === true") && cliSrc.includes("M('已更新,会话列表已同步', 'Updated — the session list is in sync')")
1665
+ && !cliSrc.includes('重启或刷新会话列表后生效'), 'client.js 的提示措辞')
1666
+ }
1667
+
1668
+ console.log('')
1669
+ console.log('== 配置同步页面 5 点调整 ==')
1670
+ {
1671
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1672
+ const wvSrc = existsSync(join(pluginRootSelf, 'runtime', 'tools', 'workspace-view.mjs')) ? readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'workspace-view.mjs'), 'utf8') : ''
1673
+ // 1) 会话名称:工具侧读 session/title 并在 readView 里带 title 字段;卡片侧显示 s.title
1674
+ check('会话名称:工具从 session 日志提取 title 并随 readView 返回',
1675
+ wvSrc.includes('zstdDecompressSync') && wvSrc.includes('buildSessionLogIndex')
1676
+ && wvSrc.includes("'session/title'") && wvSrc.includes('title: rec.title || wsId')
1677
+ && wvSrc.includes("const meta = log ? titleFromFile(log) : { title: '', origin: '', blank: false }"), 'workspace-view.mjs 的标题提取')
1678
+ check('会话名称:与 DSH 面板一致——优先 provider 正式标题,不再取第一条 fallback',
1679
+ wvSrc.includes('providerTitle') && wvSrc.includes("kind === 'provider'")
1680
+ && wvSrc.includes('cleanTitle(providerTitle) || cleanTitle(fallbackTitle)')
1681
+ && !wvSrc.includes('if (lastTitle) break'), '标题演进:provider > fallback > 无来源 > 首条消息')
1682
+ check('会话名称:卡片显示 s.title || s.id', cliSrc.includes('s.title || s.id'), 'client.js 卡片')
1683
+ // 2) 修改按钮:全卡片只有一个「修改」,进入编辑态后三态 select 与每行的隐藏/显示按钮一起出现
1684
+ check('修改按钮:整卡一个「修改」,编辑态才显示三态 select 与会话隐藏按钮',
1685
+ cliSrc.includes('// 整张卡片只有一个「修改」按钮')
1686
+ && cliSrc.includes("M('修改', 'Edit')") && cliSrc.includes("M('完成', 'Done')")
1687
+ // 工作区行不再各带一个编辑按钮
1688
+ && !cliSrc.includes('const edit = !!editing[w.workspaceId]')
1689
+ && !cliSrc.includes('setEditing(v => ({ ...v, [w.workspaceId]: !edit }))')
1690
+ // 编辑态由整卡开关控制,且行内下拉与行内按钮都存在
1691
+ && cliSrc.includes('onClick: () => setEditing(v => !v)')
1692
+ && cliSrc.includes('changeWorkspace(w.workspaceId, e.target.value)')
1693
+ && cliSrc.includes('changeSession(s.id, !s.hidden)')
1694
+ // 编辑态只靠顶部按钮本身表达状态,不再额外插入强调色说明条
1695
+ && !cliSrc.includes('editBanner') && !cliSrc.includes("M('编辑中', 'Editing')"), 'client.js 编辑态')
1696
+ // 3) 点工作区整行即展开,不再单独展开按钮
1697
+ check('点工作区即展开(整行 onClick,无独立展开按钮)',
1698
+ cliSrc.includes("onClick: () => setExpanded(e => ({ ...e, [w.workspaceId]: !open }))")
1699
+ && !cliSrc.includes("open ? '▾' : '▸', 'Expand sessions'"), 'client.js 展开交互')
1700
+ // 4) 工作区显示卡片排在问题反馈前
1701
+ const wvPos = cliSrc.indexOf("Section(M('工作区显示', 'Workspace visibility')")
1702
+ const fbPos = cliSrc.indexOf("Section(M('问题反馈', 'Feedback')")
1703
+ check('工作区显示卡片移到问题反馈前', wvPos > 0 && fbPos > 0 && wvPos < fbPos, '分区顺序')
1704
+ // 5) 标题固定 + 快速跳转 tab:Section 支持 id 锚点、页头在滚动区之外、tab 点击 scrollIntoView
1705
+ check('标题固定:页头在滚动区之外(两段式布局,不再 sticky)',
1706
+ cliSrc.includes('pageHeaderWrap:') && cliSrc.includes('pageBody:')
1707
+ && !cliSrc.includes("position: 'sticky'"), 'pageHeader 两段式')
1708
+ check('快速跳转 tab:Section 带锚点 id', cliSrc.includes('function Section(title, hint, cards, id)') && cliSrc.includes("sync-section-' + id"), 'Section id')
1709
+ check('快速跳转 tab:点击后平滑滚动到对应卡片',
1710
+ cliSrc.includes("getElementById('sync-section-' + sid)")
1711
+ && cliSrc.includes("scrollIntoView({ behavior: 'smooth', block: 'start' })")
1712
+ && cliSrc.includes("['feedback', M('问题反馈', 'Feedback')]"), 'tab 跳转')
1713
+ // 6) tab 顺序 = 卡片渲染顺序:workspace 在 extra 之后、feedback 之前(不再是第 2 位)
1714
+ const tabBlock = cliSrc.slice(cliSrc.indexOf("['overview', M('概览', 'Overview')]"), cliSrc.indexOf('.map((pair) =>'))
1715
+ const tabOrder = ['overview', 'workspace', 'targets', 'automation', 'actions', 'restore', 'scope', 'extra', 'feedback']
1716
+ .filter((k) => k !== 'workspace' && k !== 'feedback') // 下面单独校验位置
1717
+ const tabIdx = (s) => tabBlock.indexOf("['" + s + "',")
1718
+ check('快速跳转 tab 顺序与卡片顺序一致:workspace 在 extra 后、feedback 前',
1719
+ tabIdx('extra') > 0 && tabIdx('feedback') > tabIdx('extra')
1720
+ && tabBlock.indexOf("['workspace',") > tabIdx('extra')
1721
+ && tabBlock.indexOf("['workspace',") < tabIdx('feedback'), 'tab 顺序')
1722
+ // 7) 条件区(同步冲突/本机路径)按卡片是否存在动态出现在 tab
1723
+ check('快速跳转 tab:条件区 conflict/roots 动态过滤',
1724
+ cliSrc.includes('...(conflictCard ?') && cliSrc.includes('...(showRoots ?'), 'tab 条件区')
1725
+ // 8) 滚动区从标题下方开始:页头不滚动、内容区独立 overflow 且落点是固定 8px
1726
+ check('滚动落点在标题下方:内容区独立滚动 + 固定 scrollMarginTop',
1727
+ /pageBody:\s*\{[^}]*overflowY: 'auto'/.test(cliSrc)
1728
+ && /pageBody:\s*\{[^}]*minHeight: 0/.test(cliSrc)
1729
+ && cliSrc.includes("scrollMarginTop: '8px'")
1730
+ && !cliSrc.includes('headerRef.current ? headerRef.current.offsetHeight'), '滚动遮挡')
1731
+ }
1732
+ console.log('')
1733
+ console.log('== 0.3.86:本机数据挪进待办 + 会话显示会话名 + 按同步内容分组 ==')
1734
+ {
1735
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1736
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1737
+ // 1) 宿主:按同步内容分组归类 + 从投影缓存取会话标题
1738
+ check('本机数据按同步内容分组归类(pendingGroupOf + PENDING_GROUP_LABEL)',
1739
+ idxSrc.includes('const PENDING_GROUP_LABEL = {')
1740
+ && idxSrc.includes('conversations: [\'会话记录\', \'Conversations\']')
1741
+ && idxSrc.includes('function pendingGroupOf(')
1742
+ && idxSrc.includes('const gid = pendingGroupOf(')
1743
+ && idxSrc.includes('groupCount.set(gid, (groupCount.get(gid) || 0) + 1)'), 'index.js 分组统计')
1744
+ check('本机数据样本里会话显示会话标题(sessionTitleOf)',
1745
+ idxSrc.includes('function sessionTitleOf(')
1746
+ && idxSrc.includes('record.rows.title.val')
1747
+ && idxSrc.includes("if (gid === 'conversations')")
1748
+ && idxSrc.includes('if (title) label = title')
1749
+ && idxSrc.includes('if (sample.length < 3) sample.push(label)'), 'index.js 会话标题')
1750
+ check('localPending 返回 groups(zh/en/count)',
1751
+ idxSrc.includes('const groups = [...groupCount.entries()]')
1752
+ && idxSrc.includes('zh: PENDING_GROUP_LABEL[id]?.[0]')
1753
+ && idxSrc.includes('groups,')
1754
+ && idxSrc.includes('sample: [], groups: []'), 'index.js localPending 返回值')
1755
+ // 2) 客户端:待办去掉「本机数据」字眼,按分组可展开看具体名称
1756
+ const localDataHits = cliSrc.split("M('本机数据', 'Local data')").length - 1
1757
+ check('待办去掉「本机数据」字眼(0.3.90)',
1758
+ localDataHits === 0, 'client.js 无 Local data 文案')
1759
+ check('待办装配:localBlock 挂到待办卡',
1760
+ cliSrc.includes('const localBlock = data && data.local && data.local.known')
1761
+ && cliSrc.includes('pendingDetailOpen ? localBlock'), 'client.js 待办装配')
1762
+ check('待办按同步内容分组、点分组展开具体名称(会话名/profile 文件)',
1763
+ cliSrc.includes('langIsZh() ? g.zh : g.en')
1764
+ && cliSrc.includes('g.count')
1765
+ && cliSrc.includes('const items = Array.isArray(g.items) ? g.items : []')
1766
+ && cliSrc.includes('setPendingOpen')
1767
+ && cliSrc.includes('还有 ${g.count - items.length} 项未列出'), 'client.js 分组展开')
1768
+ check('待办卡有展开/收起总开关(默认展开)',
1769
+ cliSrc.includes('const [pendingDetailOpen, setPendingDetailOpen] = react.useState(true)')
1770
+ && cliSrc.includes('pendingDetailOpen ? localBlock'), 'client.js 待办总开关')
1771
+ check('顶部跳转按钮跟随当前分区高亮(0.3.90)',
1772
+ cliSrc.includes('const [activeSection, setActiveSection] = react.useState')
1773
+ && cliSrc.includes('const active = activeSection === sid')
1774
+ && cliSrc.includes("querySelectorAll('[id^=\"sync-section-\"]')")
1775
+ && cliSrc.includes('ref: bodyRef'), 'client.js 跳转高亮')
1776
+ check('分组标签与同步内容一致(会话记录/技能/插件数据/记忆数据)',
1777
+ idxSrc.includes("conversations: ['会话记录', 'Conversations']")
1778
+ && idxSrc.includes("skills: ['Skills', 'Skills']")
1779
+ && idxSrc.includes("'plugin-data': ['插件数据', 'Plugin data']")
1780
+ && idxSrc.includes("mnemon: ['记忆数据', 'Memory data']"), '分组口径')
1781
+ }
1782
+ console.log('')
1783
+ console.log('== 0.3.93:点 × 关闭时判一次并排队自动拉取/推送 ==')
1784
+ {
1785
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1786
+ // 1) 新增退出前排队函数:读开关 / 复用在途 watcher / 空仓只拉 / 拉取优先 / 判据同 scheduleAutoStart
1787
+ check('退出前排队函数存在且读 autoPull/autoPush 开关',
1788
+ /async function triggerAutoSyncOnClose\(config, options = \{\}\)/.test(idxSrc)
1789
+ && /if \(!settings\.autoPull && !settings\.autoPush\) return/.test(idxSrc), 'index.js triggerAutoSyncOnClose')
1790
+ check('已有在途 watcher 时复用、不重复拉起',
1791
+ /autoState\.pending[\s\S]{0,200}isProcessAlive\(autoState\.pending\.watcherPid\)[\s\S]{0,120}reused: true/.test(idxSrc), 'index.js 复用守卫')
1792
+ check('本机仓库为空时仅 autoPull 可排队初始化',
1793
+ /phase !== 'ok'[\s\S]{0,320}settings\.autoPull && phase === 'empty'/.test(idxSrc), 'index.js 空仓分支')
1794
+ check('退出前拉取优先:云端领先就排 pull(且不弹确认框)',
1795
+ /settings\.autoPull && drift\.behind > 0[\s\S]{0,420}mode: 'pull'/.test(idxSrc)
1796
+ && /退出前检查:云端领先/.test(idxSrc), 'index.js 拉取优先')
1797
+ check('退出前 push 判据与 scheduleAutoStart 一致(领先/未提交/本机待同步)',
1798
+ /const shouldPush = drift\.ahead > 0 \|\| dirty > 0 \|\| \(lp\.known && lp\.pending > 0\)/.test(idxSrc)
1799
+ && /if \(shouldPush\)/.test(idxSrc), 'index.js push 判据')
1800
+ check('退出前排队的 restart 语义统一为 autoRestart !== false',
1801
+ /function triggerAutoSyncOnClose[\s\S]{0,2600}settings\.autoRestart !== false/.test(idxSrc)
1802
+ && !/function triggerAutoSyncOnClose[\s\S]{0,2600}settings\.autoRestart === true/.test(idxSrc), 'index.js autoRestart')
1803
+ // 2) 关闭钩子:接 config、quit 之前 await 排队、再 quit;apply 内传 config
1804
+ check('关闭钩子接住 config(installQuitWhenAllWindowsClosed(ctx, config))',
1805
+ /function installQuitWhenAllWindowsClosed\(ctx, config\)/.test(idxSrc)
1806
+ && /installQuitWhenAllWindowsClosed\(ctx, config\)/.test(idxSrc), 'index.js 钩子签名与调用点')
1807
+ check('点 × 无可见窗口时先 await 退出前排队、再 app.quit()',
1808
+ /await triggerAutoSyncOnClose\(config\)[\s\S]{0,600}el\.app\.quit\(\)/.test(idxSrc), 'index.js 排队先于 quit')
1809
+ check('排队成功写日志:退出后立即执行',
1810
+ /退出前已排队 \$\{r\.mode\}(自动同步)/.test(idxSrc), 'index.js 排队日志')
1811
+ }
1812
+ console.log('')
1813
+ console.log('== 0.3.94:清理跨重启僵死 watcher,锁不再被旧实例占死 ==')
1814
+ {
1815
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1816
+ const postSrc = existsSync(join(pluginRuntime, 'post-exit.ps1')) ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
1817
+ check('锁文件写入 watchPid=当前 DSH pid',
1818
+ /JSON\.stringify\(\{ pid, mode, watchPid: process\.pid, at: Date\.now\(\) \}\)/.test(idxSrc), 'index.js 写锁')
1819
+ check('复用前先判定锁是否僵死:读取 lockWatchPid',
1820
+ /"watchPid"\\s\*:\\s\*\(\\d\+\)/.test(idxSrc)
1821
+ || idxSrc.includes('const lockWatchPid = Number('), 'index.js 读 watchPid')
1822
+ check('僵死判定:watchPid 缺失或其进程已退出',
1823
+ idxSrc.includes('const stale = !lockWatchPid || !watcherOwnerAlive')
1824
+ && /process\.kill\(lockWatchPid, 0\)/.test(idxSrc), 'index.js stale 判定')
1825
+ check('只在锁未僵死时才复用同 mode 的 watcher',
1826
+ /if \(alive && !stale\)[\s\S]{0,300}?if \(lockMode === mode\) return/.test(idxSrc), 'index.js 复用守卫')
1827
+ check('僵死锁会被杀掉并记日志,不再复用',
1828
+ /else if \(alive && stale\)/.test(idxSrc)
1829
+ && idxSrc.includes('清理僵死 watcher'), 'index.js 清僵死')
1830
+ check('post-exit wait:WatchPid 已死但进程名有新实例时判定过期 watcher',
1831
+ postSrc.includes('-not $byPid -and $byName.Count -gt 0')
1832
+ && postSrc.includes('判定为过期 watcher'), 'post-exit.ps1 过期判定')
1833
+ check('0.4.04:过期判定改为看有无遗留前台窗口,不被无窗口孤儿进程卡死',
1834
+ postSrc.includes('$visibleOld = @($byName | Where-Object { $_.MainWindowHandle -ne 0')
1835
+ && postSrc.includes('$visibleOld.Count -eq 0')
1836
+ && postSrc.includes('无遗留前台窗口'), 'post-exit.ps1 孤儿进程让位')
1837
+ check('post-exit wait:过期 watcher 清自己的锁并 exit 3 让位',
1838
+ /\$lock\.pid -eq \$PID/.test(postSrc) && /\bexit 3\b/.test(postSrc), 'post-exit.ps1 让位')
1839
+ }
1840
+ console.log('')
1841
+ console.log('== 0.3.95:所有 runtime/*.ps1 必须带 UTF-8 BOM(PS5.1 中文脚本防乱码崩溃)==')
1842
+ {
1843
+ // 决定性教训:0.3.94 编辑 post-exit.ps1 时写入工具丢了 BOM,PS5.1 按 GBK 解码,
1844
+ // 中文全角括号被解成引号 → 55 处语法错 → 脚本启动即崩 → 所有排队同步(含点 ×)全部失效。
1845
+ // 所有含中文的 .ps1 必须带 UTF-8 BOM,否则在 Windows PowerShell 5.1 下必崩。
1846
+ const ps1Names = ['apply.ps1', 'capture.ps1', 'dsh-sync-common.ps1', 'install-plugin.ps1',
1847
+ 'post-exit.ps1', 'restore.ps1', 'sync.ps1']
1848
+ for (const name of ps1Names) {
1849
+ const p = join(pluginRuntime, name)
1850
+ if (!existsSync(p)) continue
1851
+ const bytes = readFileSync(p)
1852
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF
1853
+ const hex = [...bytes.slice(0, 3)].map((b) => b.toString(16).padStart(2, '0')).join(' ')
1854
+ check(`${name} 带 UTF-8 BOM(PS5.1 不会按 GBK 解成乱码)`, hasBom, `前3字节 ${hex}`)
1855
+ }
1856
+ // post-exit.ps1 是排队同步(含点 × 触发)的唯一执行体,崩了就全盘不动,单独强调
1857
+ const postPath = join(pluginRuntime, 'post-exit.ps1')
1858
+ if (existsSync(postPath)) {
1859
+ const b = readFileSync(postPath)
1860
+ check('post-exit.ps1 执行体非零字节且带 BOM',
1861
+ b.length > 1000 && b[0] === 0xEF && b[1] === 0xBB && b[2] === 0xBF, `bytes=${b.length}`)
1862
+ }
1863
+ }
1864
+ console.log('')
1865
+ console.log('== 0.3.96:页面卸载信标(sendBeacon)绕开 Electron 关窗钩子死结 ==')
1866
+ {
1867
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1868
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1869
+ // 后端:新路由 + handler + fast 判据
1870
+ check('新增 auto-exit 路由常量',
1871
+ /const ROUTE_AUTO_EXIT = '\/config-sync\/auto-exit'/.test(idxSrc), 'index.js ROUTE_AUTO_EXIT')
1872
+ check('auto-exit 路由已注册(withLang(handleAutoExit))',
1873
+ /path: ROUTE_AUTO_EXIT[\s\S]{0,80}handler: withLang\(handleAutoExit\)/.test(idxSrc), 'index.js 路由注册')
1874
+ check('handleAutoExit 存在且走 triggerAutoSyncOnClose fast 模式',
1875
+ /async function handleAutoExit\(req, res, config\)/.test(idxSrc)
1876
+ && /triggerAutoSyncOnClose\(config, \{ fast: true \}\)/.test(idxSrc), 'index.js handleAutoExit')
1877
+ check('triggerAutoSyncOnClose 接 options 并在 fast 时用 checkDriftFast',
1878
+ /async function triggerAutoSyncOnClose\(config, options = \{\}\)/.test(idxSrc)
1879
+ && /options\.fast \? await checkDriftFast\(repo\) : await checkDrift\(repo\)/.test(idxSrc), 'index.js fast 分支')
1880
+ check('checkDriftFast 只读本地 tracking ref,绝不 git fetch',
1881
+ /async function checkDriftFast\(repo\)/.test(idxSrc)
1882
+ && /rev-list', '--left-right', '--count'/.test(idxSrc)
1883
+ && !/async function checkDriftFast[\s\S]{0,700}?git\(repo, \['fetch'/.test(idxSrc), 'index.js checkDriftFast')
1884
+ // 前端:pagehide/beforeunload → sendBeacon,且全程 typeof 守卫(clientcheck 无 document/navigator)
1885
+ check('client.js 安装 pagehide + beforeunload 卸载监听',
1886
+ /window\.addEventListener\('pagehide', fire\)/.test(cliSrc)
1887
+ && /window\.addEventListener\('beforeunload', fire\)/.test(cliSrc), 'client.js 卸载监听')
1888
+ check('卸载时向 /config-sync/auto-exit 发 navigator.sendBeacon',
1889
+ /navigator\.sendBeacon\('\/config-sync\/auto-exit'/.test(cliSrc), 'client.js sendBeacon')
1890
+ check('pagehide 信标全程 typeof 守卫(无 document/navigator 环境不崩)',
1891
+ /if \(typeof navigator === 'undefined' \|\| typeof navigator\.sendBeacon !== 'function'\) return noop/.test(cliSrc)
1892
+ && /if \(typeof window === 'undefined' \|\| typeof window\.addEventListener !== 'function'\) return noop/.test(cliSrc), 'client.js 守卫')
1893
+ check('apply() 内安装信标并用 ctx.effect 回收',
1894
+ /var offBeacon = installExitBeacon\(\)/.test(cliSrc)
1895
+ && /ctx\.effect\(function \(\) \{ return function \(\) \{ try \{ offBeacon\(\) \}/.test(cliSrc), 'client.js apply 安装')
1896
+ }
1897
+ console.log('')
1898
+ console.log('== 0.3.97:检测到待拉取/待推送就主动强制退出 DSH,watcher 立刻执行 ==')
1899
+ {
1900
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1901
+ check('新增 forceCloseDshDetached 独立进程强制退出函数',
1902
+ /function forceCloseDshDetached\(config\)/.test(idxSrc), 'index.js forceCloseDshDetached')
1903
+ check('强制退出用 detached + unref 独立进程(强杀不会带走插件自己)',
1904
+ /spawn\(cmd, \['\/c', script\][\s\S]{0,120}?detached: true/.test(idxSrc)
1905
+ && /child\.unref\?\.\(\)/.test(idxSrc), 'index.js detached 强杀')
1906
+ check('taskkill /IM /F 整族强杀 DeepSeek Harness',
1907
+ /taskkill[\s\S]{0,80}?\/IM[\s\S]{0,80}?\/F/.test(idxSrc)
1908
+ || /"\/IM"[\s\S]{0,120}?"\/F"/.test(idxSrc), 'index.js taskkill /F')
1909
+ check('auto-exit 排队成功后调用 forceCloseDshDetached',
1910
+ /if \(result && result\.queued\) forceCloseDshDetached\(config\)/.test(idxSrc), 'index.js 排队后主动退出')
1911
+ check('只在 queued 时才强制退出(无待同步不误杀 DSH)',
1912
+ /result && result\.queued[\s\S]{0,60}?forceCloseDshDetached/.test(idxSrc), 'index.js queued 守卫')
1913
+ }
1914
+ console.log('')
1915
+ console.log('== 0.3.99:开关变更即时触发自动同步判断(不等 2 分钟周期)==')
1916
+ {
1917
+ const idxSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1918
+ check('新增 checkAndQueueAutoSync 核心判断函数',
1919
+ /async function checkAndQueueAutoSync\(/.test(idxSrc), 'index.js checkAndQueueAutoSync')
1920
+ check('scheduleAutoStart 复用 checkAndQueueAutoSync',
1921
+ /await checkAndQueueAutoSync\(/.test(idxSrc), 'index.js scheduleAutoStart 复用')
1922
+ check('handleSettings 保存 autoPull/autoPush 后立即调用 checkAndQueueAutoSync',
1923
+ /changed\.autoPull \|\| changed\.autoPush/.test(idxSrc)
1924
+ && /await checkAndQueueAutoSync\(/.test(idxSrc), 'index.js 即时触发')
1925
+ check('checkAndQueueAutoSync 支持 isManualTrigger 跳过确认框',
1926
+ /isManualTrigger/.test(idxSrc) && /skipConfirm/.test(idxSrc), 'index.js 手动触发模式')
1927
+ check('checkAndQueueAutoSync 返回 queued/mode/reason 供上层判断',
1928
+ /return \{ queued: true, mode:/.test(idxSrc)
1929
+ && /return \{ queued: false, reason:/.test(idxSrc), 'index.js 返回结构')
1930
+ }
1931
+ console.log('')
1932
+ console.log('== 0.3.98:默认工作区会话同步(稳定名 --default-workspace--,资料仍不同步)==')
1933
+ {
1934
+ const capPath = join(pluginRuntime, 'capture.ps1')
1935
+ const appPath = join(pluginRuntime, 'apply.ps1')
1936
+ const cap = existsSync(capPath) ? readFileSync(capPath, 'utf8') : ''
1937
+ const app = existsSync(appPath) ? readFileSync(appPath, 'utf8') : ''
1938
+ // capture:默认工作区会话用稳定名入库(不再跳过)
1939
+ check('capture Get-RepoSessionDirName 支持 default → --default-workspace--',
1940
+ /if \(\$kind -eq 'default'\) \{ return '--default-workspace--' \}/.test(cap), 'capture.ps1 default 稳定名')
1941
+ check('capture 默认工作区会话纳入映射(special=default,不再跳过)',
1942
+ /special = 'default'/.test(cap) && /默认工作区会话纳入同步/.test(cap), 'capture.ps1 顶层映射')
1943
+ check('capture 从本机 defaultWorkspaceId 反查默认工作区路径',
1944
+ /defaultWorkspaceId/.test(cap) && /\$defaultWsPath = \$wsPathById\[\$defId\]/.test(cap), 'capture.ps1 默认路径反查')
1945
+ check('capture 默认工作区 cwd 归一到 {{WORKSPACE_HOME}}/default-workspace',
1946
+ /\$cwdToken\[\$defaultRepoDirName\] = \(ConvertTo-WorkspaceToken \$defaultWsPath\)/.test(cap), 'capture.ps1 cwd 归一')
1947
+ check('capture 资料按 defaultWorkspaceId 跳过默认工作区(资料不同步、登记保留)',
1948
+ /if \(\$e\.Id -eq \$gDefault\) \{ continue \}/.test(cap), 'capture.ps1 资料跳过')
1949
+ check('capture 会话镜像不再无条件跳过默认工作区目录',
1950
+ /\(Test-DefaultWorkspaceDir \$parts\[0\]\)/.test(cap) && /-not \$b\.Remap/.test(cap), 'capture.ps1 镜像')
1951
+ // apply:按本机默认工作区路径重编码 + 注册会话到默认工作区
1952
+ check('apply 从本机 workspace.json 读 defaultWorkspaceId 反查默认工作区路径',
1953
+ /\$localDefaultWsPath/.test(app) && /\$lreg\.global\.defaultWorkspaceId/.test(app), 'apply.ps1 本机默认路径')
1954
+ check('apply special=default 分支按本机路径重编码目录与 cwd',
1955
+ /\$e\.special -eq 'default'/.test(app) && /\$newDir = Get-SessionDirName \$localDefaultWsPath/.test(app), 'apply.ps1 重编码')
1956
+ check('apply 2b 兜底与 projcache 都处理 --default-workspace--',
1957
+ /\$d\.Name -eq '--default-workspace--'/.test(app) && /\$wd\.Name -eq '--default-workspace--'/.test(app), 'apply.ps1 兜底+projcache')
1958
+ check('apply 默认工作区会话 id 并入本机默认工作区登记(sessionIds)',
1959
+ /\$localTable\[\$dwId\]\['sessionIds'\]/.test(app) && /\$defaultSids/.test(app), 'apply.ps1 sessionIds 合并')
1960
+ }
1961
+ console.log('')
1962
+ console.log('== 0.4.02:npm tarball 版本按 semver 规范化(0.4.01 → 0.4.1)==')
1963
+ {
1964
+ const idxSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1965
+ check('npmTgzUrls 对版本号做 semver 规范化(数字段去前导零)',
1966
+ /const semver = raw\.replace\(\/\^\\\(\\d\+\\\)/.test(idxSrc)
1967
+ || /\$\{Number\(a\)\}\.\$\{Number\(b\)\}\.\$\{Number\(c\)\}/.test(idxSrc), 'index.js semver 规范化')
1968
+ check('npmTgzUrls 保留预发布/构建后缀清洗',
1969
+ idxSrc.includes("semver.replace(/[^0-9A-Za-z.+\\-]/g, '')"), 'index.js 版本清洗')
1970
+ }
1971
+ console.log('')
1972
+ console.log('== 0.4.05:定时复查预排 watcher,不依赖前端信标 ==')
1973
+ {
1974
+ const idxSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1975
+ check('scheduleAutoStart 的 run 调用 checkAndQueueAutoSync 预排 watcher',
1976
+ /await checkAndQueueAutoSync\(dshHome, config, settings, repo, appRoot, \{ shouldCloseDsh: false, isPeriodic: true \}\)/.test(idxSrc), 'index.js 定时预排')
1977
+ check('checkAndQueueAutoSync 支持 isPeriodic 参数',
1978
+ /isPeriodic = false/.test(idxSrc) && /isManualTrigger/.test(idxSrc), 'index.js isPeriodic 参数')
1979
+ check('定时复查无人值守不弹确认框',
1980
+ /!skipConfirm && !isManualTrigger && !isPeriodic/.test(idxSrc), 'index.js 定时免确认')
1981
+ check('已排队守卫检查 watcher 存活(超时后可重排)',
1982
+ /autoState\.pending && isProcessAlive\(autoState\.pending\.watcherPid\)/.test(idxSrc), 'index.js 存活守卫')
1983
+ }
1984
+ console.log('')
1985
+ console.log('== 0.4.06:点 × 由后端窗口监视触发(不依赖前端信标),watcher 窗口一消失就开工 ==')
1986
+ {
1987
+ const idxSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1988
+ const postSrc = existsSync(join(pluginRuntime, 'post-exit.ps1'))
1989
+ ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
1990
+ check('新增 startWindowWatcher:常驻采样可见窗口数',
1991
+ /function startWindowWatcher\(config\)/.test(idxSrc)
1992
+ && idxSrc.includes("Get-Process -Name 'DeepSeek Harness'")
1993
+ && idxSrc.includes('MainWindowHandle -ne 0'), 'index.js 窗口监视')
1994
+ check('窗口监视 apply 时启动、卸载时回收',
1995
+ /startWindowWatcher\(config\)/.test(idxSrc)
1996
+ && /autoState\.windowTimer = null/.test(idxSrc), 'index.js 生命周期')
1997
+ check('关闭判据:曾经有窗口 + 连续 4 拍归零(最小化不算)',
1998
+ /autoState\.windowHadVisible = true/.test(idxSrc)
1999
+ && /autoState\.windowZeroTicks < 4/.test(idxSrc), 'index.js 归零判据')
2000
+ check('采样进程自带退出条件(DSH 全消失 / 宿主消失 / 时限)',
2001
+ idxSrc.includes('if ($all.Count -eq 0) { break }')
2002
+ && idxSrc.includes('(Get-Date) -gt $deadline'), 'index.js 采样进程退出条件')
2003
+ check('采样进程不得 detached(实测 detached 时 stdout 全丢,心跳为 0 行)',
2004
+ /detached: true/.test(idxSrc.split('function startWindowWatcher')[1]?.split('async function onWindowClosedSync')[0] || '')
2005
+ ? false : true, 'index.js 采样进程非 detached')
2006
+ check('父进程判死必须先见过父进程(首拍查不到不能自杀)',
2007
+ idxSrc.includes('$parentSeen = $false') && idxSrc.includes('elseif ($parentSeen) { break }'), 'index.js 父进程判死')
2008
+ check('命中后先判一次同步再强杀,且只在有待同步时才强杀',
2009
+ /async function onWindowClosedSync/.test(idxSrc)
2010
+ && /result\.queued \|\| result\.reused/.test(idxSrc)
2011
+ && /没有待拉取\/待推送/.test(idxSrc), 'index.js 按需强杀')
2012
+ check('没有可见窗口出现过(CLI/无窗口启动)永不触发',
2013
+ /if \(!autoState\.windowHadVisible\) return/.test(idxSrc), 'index.js 无窗口不触发')
2014
+ check('post-exit wait:可见窗口归零即收拾进程族,不再等 60 秒批次年龄',
2015
+ postSrc.includes('$hadVisible = $false')
2016
+ && postSrc.includes('$visZeroTicks -ge 3')
2017
+ && postSrc.includes('可见窗口已全部关闭'), 'post-exit.ps1 wait 判据')
2018
+ check('过期 watcher 让位收紧:必须等待超过 5 分钟且没见过窗口',
2019
+ postSrc.includes('$waited -gt 300')
2020
+ && postSrc.includes('-and -not $hadVisible'), 'post-exit.ps1 让位收紧')
2021
+ }
2022
+
2023
+ console.log('')
2024
+ console.log('== 0.4.09:本地提交导致分叉,冲突检测展示处理方式 ==')
2025
+ {
2026
+ const syncSrc = readFileSync(join(pluginRootSelf, 'runtime', 'sync.ps1'), 'utf8')
2027
+ const idxSrc2 = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
2028
+ const cliSrc = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
2029
+ check('sync.ps1 新增 Get-DivergenceInfo 检测本地提交分叉',
2030
+ syncSrc.includes('function Get-DivergenceInfo') && syncSrc.includes('merge-base --is-ancestor HEAD '), 'sync.ps1 分叉检测')
2031
+ check('sync.ps1 pull 冲突检测阶段调用分叉判断并写入清单',
2032
+ /\$div = Get-DivergenceInfo \$remoteRef/.test(syncSrc) && syncSrc.includes('divergence = $div'), 'sync.ps1 分叉清单')
2033
+ check('sync.ps1 处理方式含保留(rebase)/丢弃(reset)与双机根因',
2034
+ syncSrc.includes('rebase origin/') && syncSrc.includes('reset --hard origin/') && syncSrc.includes('双机同时 push'), 'sync.ps1 处理方式')
2035
+ check('sync.ps1 diff 失败分类把 not possible to fast-forward 单独处理',
2036
+ /not possible to fast-forward\|Not possible to fast-forward\|Diverging branches/.test(syncSrc), 'sync.ps1 分叉分类')
2037
+ check('sync.ps1 备份 README 里展示分叉处理',
2038
+ syncSrc.includes('分支分叉 / Diverged branches') && syncSrc.includes('$Report.divergence'), 'sync.ps1 README 分叉')
2039
+ check('index.js 冲突接口透传 divergence 字段',
2040
+ idxSrc2.includes('divergence: obj.divergence') && idxSrc2.includes('localAhead: Number'), 'index.js divergence 透传')
2041
+ check('client.js 冲突卡展示分叉处理方式',
2042
+ cliSrc.includes('state.divergence ? h(') && cliSrc.includes('本地有提交导致分支分叉'), 'client.js 分叉展示')
2043
+ }
2044
+ process.exit(failures === 0 ? 0 : 1)
2045
+