@alequet/dsh-patchkeeper 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.mjs ADDED
@@ -0,0 +1,905 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-patchkeeper CLI — 影子副本(shadow mount)架构。
4
+ *
5
+ * 核心思想:永不修改原版插件。
6
+ * apply = 复制原版 → 补丁打进副本 → node_modules 条目换名挂载到副本
7
+ * revert = 摘挂载、销毁副本、原版归位(崩溃没执行也不要紧)
8
+ * 启动时 = 先按 state.json 保底清除上次残留,再做版本匹配挂载
9
+ *
10
+ * 用法:
11
+ * node cli.mjs extract [--pkg <name>] 从 npm 原版 diff 出补丁,写入 patches/
12
+ * node cli.mjs apply [--force] [--pkg] 版本匹配则挂载补丁副本
13
+ * node cli.mjs revert [--pkg] 摘挂载、销毁副本、恢复原版
14
+ * node cli.mjs status 只看状态不改文件
15
+ * node cli.mjs list 列出补丁清单
16
+ * node cli.mjs doctor [--fix] 检查/修复插件在 profile 里的注册
17
+ *
18
+ * 通用: --json 输出 JSON;DSH_PROFILE 覆盖 profile 路径。
19
+ */
20
+ import { spawnSync } from 'node:child_process'
21
+ import fs from 'node:fs'
22
+ import os from 'node:os'
23
+ import path from 'node:path'
24
+ import { fileURLToPath } from 'node:url'
25
+
26
+ // 代码与数据分离:包可以被升级/重装/公开分发,补丁数据独立于包存在
27
+ const TOOL_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
28
+ const DATA_DIR = process.env.DSH_PATCHKEEPER_HOME || path.join(os.homedir(), '.dsh', 'patch-manager')
29
+ const PATCHES_DIR = path.join(DATA_DIR, 'patches')
30
+ const BIN_DIR = path.join(PATCHES_DIR, 'bin') // 二进制改动整文件存放
31
+ const REJECTS_DIR = path.join(DATA_DIR, 'rejects')
32
+ const STATE_FILE = path.join(DATA_DIR, 'state.json')
33
+
34
+ function resolveProfile() {
35
+ const env = process.env.DSH_PROFILE
36
+ if (!env) return path.join(os.homedir(), '.dsh', 'profiles', 'desktop')
37
+ if (path.isAbsolute(env)) return env
38
+ return path.join(os.homedir(), '.dsh', 'profiles', env)
39
+ }
40
+ const PROFILE = resolveProfile()
41
+ const NM = path.join(PROFILE, 'node_modules')
42
+ // 影子副本必须放在 profile 的 node_modules 树内:依赖解析沿目录向上走,能摸到平铺的兄弟依赖
43
+ // ≤0.2.0 曾放在 node_modules/.patchkeeper-shadows,被 pnpm reconcile 当游离目录剪掉过(实测)
44
+ const LEGACY_SHADOWS = path.join(NM, '.patchkeeper-shadows')
45
+ // 副本放数据目录,pnpm 管不着;副本内补 node_modules 软链指回 profile 解决依赖解析
46
+ const SHADOWS = path.join(DATA_DIR, 'shadows')
47
+ const shadowDir = (slug) => path.join(SHADOWS, slug)
48
+ const origDir = (slug) => path.join(SHADOWS, 'orig', slug)
49
+
50
+ // 挂载时写进副本 package.json 的生效标记(extract 前会摘掉,不污染补丁)
51
+ const MOUNT_MARKER = '🩹 补丁生效中(patchkeeper)'
52
+
53
+ // diff 时排除的东西:运行时缓存、日志、本地备份等
54
+ const EXCLUDES = [
55
+ 'node_modules', '.git', '.svn', '.DS_Store', 'Thumbs.db',
56
+ '*.log', 'logs', 'tmp', '.cache', 'Cache', '__pycache__',
57
+ '.pnpm-store', '*.tsbuildinfo', '*.rej', '*.orig', '*.bak', '*.bak-*', 'pnpm-lock.yaml',
58
+ ]
59
+
60
+ // 不进补丁管理的包(我们自己 / 本地包)
61
+ const SKIP_PKGS = new Set(['@alequet/dsh-patchkeeper', 'dsh-patchkeeper'])
62
+
63
+ // ---------- 小工具 ----------
64
+
65
+ const slugOf = (name) => name.replace('/', '+') // @scope/name -> @scope+name
66
+ const nameOf = (slug) => (slug.startsWith('@') ? slug.replace('+', '/') : slug)
67
+
68
+ function parsePatchFile(file) {
69
+ const m = /^(?<slug>.+)__(?<version>.+)\.patch$/.exec(file)
70
+ if (!m) return null
71
+ return { file, slug: m.groups.slug, name: nameOf(m.groups.slug), version: m.groups.version }
72
+ }
73
+
74
+ function listPatchFiles() {
75
+ if (!fs.existsSync(PATCHES_DIR)) return []
76
+ return fs.readdirSync(PATCHES_DIR).map(parsePatchFile).filter(Boolean)
77
+ }
78
+
79
+ function readJson(p) {
80
+ return JSON.parse(fs.readFileSync(p, 'utf8'))
81
+ }
82
+
83
+ function readState() {
84
+ try {
85
+ return readJson(STATE_FILE)
86
+ } catch {
87
+ return {}
88
+ }
89
+ }
90
+
91
+ function writeState(patch) {
92
+ const state = { ...readState(), ...patch }
93
+ fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2))
94
+ }
95
+
96
+ // 已装版本一律读 node_modules 条目本身:挂载时软链指向副本(版本与原版一致),
97
+ // 未挂载时就是真实安装;orig 备份可能是过时的,不看它。
98
+ function installedVersion(name) {
99
+ try {
100
+ return readJson(path.join(NM, name, 'package.json')).version || null
101
+ } catch {
102
+ return null
103
+ }
104
+ }
105
+
106
+ // 当前是否挂载着影子副本(node_modules 条目是指向我们副本的软链)
107
+ function isMounted(name, slug) {
108
+ const entry = path.join(NM, name)
109
+ try {
110
+ const lst = fs.lstatSync(entry)
111
+ if (!lst.isSymbolicLink()) return false
112
+ return fs.realpathSync(entry) === fs.realpathSync(shadowDir(slug))
113
+ } catch {
114
+ return false
115
+ }
116
+ }
117
+
118
+ function run(cmd, args, opts = {}) {
119
+ return spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, ...opts })
120
+ }
121
+
122
+ // patch 检测:返回 'not-applied' | 'applied' | 'conflict'
123
+ function probePatch(dir, patchFile) {
124
+ const base = ['--dry-run', '-p1', '-N', '-E', '-d', dir, '-i', patchFile]
125
+ const fwd = run('patch', base)
126
+ if (fwd.status === 0) return 'not-applied'
127
+ const rev = run('patch', [...base, '-R'])
128
+ if (rev.status === 0) return 'applied'
129
+ return 'conflict'
130
+ }
131
+
132
+ function binFilesOf(slug) {
133
+ const binBase = path.join(BIN_DIR, slug)
134
+ if (!fs.existsSync(binBase)) return { binBase, files: [] }
135
+ return {
136
+ binBase,
137
+ files: fs.readdirSync(binBase, { recursive: true }).filter((f) => fs.statSync(path.join(binBase, f)).isFile()),
138
+ }
139
+ }
140
+
141
+ // ---------- 保底清除(每次启动 apply 前必跑) ----------
142
+
143
+ // 把挂载状态恢复成原版归位、副本销毁。崩溃残留、孤儿副本都在这里清。
144
+ function ensureCleanMount({ only } = {}) {
145
+ const repaired = []
146
+ cleanLegacyMounts()
147
+ const state = readState()
148
+ const swaps = state.swaps || {}
149
+ for (const [name] of Object.entries(swaps)) {
150
+ if (only && name !== only) continue
151
+ const p = { name, slug: slugOf(name) }
152
+ // 健康挂载(软链在、副本在、备份在)原地不动:启动时拆装了重挂,会跟冻结快照抢同一扇窗
153
+ if (isMounted(p.name, p.slug) && fs.existsSync(origDir(p.slug))) continue
154
+ if (dismount(p)) repaired.push(name)
155
+ }
156
+ // 孤儿副本清扫:state 里没登记但 shadows 里躺着的(比如 state.json 丢了)
157
+ if (fs.existsSync(SHADOWS)) {
158
+ for (const dirent of fs.readdirSync(SHADOWS, { withFileTypes: true })) {
159
+ if (dirent.name === 'orig') continue
160
+ const name = nameOf(dirent.name)
161
+ if (swaps[name]) continue
162
+ // 没登记的副本:如果 orig/ 里有对应原版且 node_modules 条目还指过来,也一并恢复
163
+ const p = { name, slug: dirent.name }
164
+ if (isMounted(name, dirent.name)) dismount(p)
165
+ else fs.rmSync(shadowDir(dirent.name), { recursive: true, force: true })
166
+ }
167
+ }
168
+ return repaired
169
+ }
170
+
171
+ // 旧版(≤0.2.0)挂载遗址清理:条目是指向 node_modules/.patchkeeper-shadows 的软链,
172
+ // 原版备份在其 orig/ 下。恢复原位后整个旧目录删除。
173
+ function cleanLegacyMounts() {
174
+ if (!fs.existsSync(LEGACY_SHADOWS)) return
175
+ for (const dirent of fs.readdirSync(LEGACY_SHADOWS, { withFileTypes: true })) {
176
+ if (dirent.name === 'orig') continue
177
+ const slug = dirent.name
178
+ const name = nameOf(slug)
179
+ const entry = path.join(NM, name)
180
+ try {
181
+ if (fs.lstatSync(entry).isSymbolicLink() && fs.realpathSync(entry) === fs.realpathSync(path.join(LEGACY_SHADOWS, slug))) {
182
+ fs.rmSync(entry, { force: true })
183
+ }
184
+ } catch {}
185
+ const legacyOrig = path.join(LEGACY_SHADOWS, 'orig', slug)
186
+ if (fs.existsSync(legacyOrig) && !fs.existsSync(entry) && profileLists(name)) {
187
+ fs.mkdirSync(path.dirname(entry), { recursive: true })
188
+ fs.renameSync(legacyOrig, entry)
189
+ }
190
+ }
191
+ fs.rmSync(LEGACY_SHADOWS, { recursive: true, force: true })
192
+ }
193
+
194
+ // 插件是否仍在 profile 依赖清单里(不在 = 用户已卸载,原版备份不能复活它)
195
+ function profileLists(name) {
196
+ try {
197
+ const pkg = readJson(path.join(PROFILE, 'package.json'))
198
+ return Object.hasOwn(pkg.dependencies ?? {}, name)
199
+ } catch {
200
+ return true // 读不到清单时保守处理:恢复原版
201
+ }
202
+ }
203
+
204
+ // ---------- 补丁配置(启用开关 + 效果说明,随 patches/ 入 git) ----------
205
+
206
+ const CONFIG_FILE = path.join(PATCHES_DIR, 'config.json')
207
+
208
+ function readConfig() {
209
+ try {
210
+ return readJson(CONFIG_FILE)
211
+ } catch {
212
+ return {}
213
+ }
214
+ }
215
+
216
+ function writeConfig(cfg) {
217
+ fs.mkdirSync(PATCHES_DIR, { recursive: true })
218
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n')
219
+ }
220
+
221
+ const isEnabled = (name) => readConfig()[name]?.enabled !== false
222
+
223
+ // 从补丁文件解析被覆盖的文件清单(供 UI 展示)
224
+ function patchFileList(p) {
225
+ const files = []
226
+ const patchPath = path.join(PATCHES_DIR, p.file)
227
+ if (fs.existsSync(patchPath)) {
228
+ const text = fs.readFileSync(patchPath, 'utf8')
229
+ for (const m of text.matchAll(/^diff -ruN a\/(?<f>.+?) b\/.+$/gm)) files.push(m.groups.f)
230
+ }
231
+ files.push(...binFilesOf(p.slug).files.map((f) => f + ' (binary)'))
232
+ return files
233
+ }
234
+
235
+ // 摘一个挂载:删我们的软链 → 原版归位 → 销毁副本。返回是否有实际清理动作。
236
+ // 竞态防护:若条目已被外部(升级器)换成新安装,原版备份已过时——丢弃备份,保留新装。
237
+ function dismount(p) {
238
+ const entry = path.join(NM, p.name)
239
+ const shadow = shadowDir(p.slug)
240
+ const orig = origDir(p.slug)
241
+ const hadWork = isMounted(p.name, p.slug) || fs.existsSync(orig) || fs.existsSync(shadow)
242
+ if (isMounted(p.name, p.slug)) fs.rmSync(entry, { force: true })
243
+ if (fs.existsSync(orig)) {
244
+ if (!fs.existsSync(entry) && profileLists(p.name)) {
245
+ fs.mkdirSync(path.dirname(entry), { recursive: true })
246
+ fs.renameSync(orig, entry) // 同分区 rename,原子
247
+ } else {
248
+ // 条目已被在线更新替换成新版,或插件已被卸载:备份已过时,丢弃不复活
249
+ fs.rmSync(orig, { recursive: true, force: true })
250
+ }
251
+ }
252
+ fs.rmSync(shadow, { recursive: true, force: true })
253
+ // 顺手清掉空壳目录(orig/ 与 shadows 本身,空了才删得掉)
254
+ try { fs.rmdirSync(path.join(SHADOWS, 'orig')) } catch {}
255
+ try { fs.rmdirSync(SHADOWS) } catch {}
256
+ const state = readState()
257
+ if (state.swaps && state.swaps[p.name]) {
258
+ delete state.swaps[p.name]
259
+ writeState({ swaps: state.swaps })
260
+ }
261
+ return hadWork
262
+ }
263
+
264
+ // ---------- extract ----------
265
+
266
+ function extractOne(name, spec, { log }) {
267
+ const result = { name, ok: false }
268
+ const slug = slugOf(name)
269
+ const mounted = isMounted(name, slug)
270
+ // 挂载中:entry 软链指向副本——从副本提补丁,这正是「在副本上实验 → 入库」的调试循环
271
+ const dir = path.join(NM, name)
272
+ if (!fs.existsSync(dir)) {
273
+ result.error = 'not-installed'
274
+ return result
275
+ }
276
+ if (/^file:|^link:/.test(spec)) {
277
+ result.error = 'local-package-skipped'
278
+ return result
279
+ }
280
+ const version = installedVersion(name)
281
+ result.version = version
282
+
283
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'patchkeeper-'))
284
+ let markedDesc = null // 生效标记的原文(finally 里恢复)
285
+ const entryPkg = path.join(dir, 'package.json') // 提升作用域:finally 要用
286
+ try {
287
+ const packSpec = /^https?:/.test(spec) ? spec : `${name}@${version}`
288
+ const pack = run('npm', ['pack', packSpec, '--pack-destination', tmp, '--silent'], { cwd: tmp })
289
+ if (pack.status !== 0) {
290
+ result.error = `npm pack failed: ${(pack.stderr || '').slice(0, 300)}`
291
+ return result
292
+ }
293
+ const tarball = (pack.stdout || '').trim().split('\n').pop().trim()
294
+ const aDir = path.join(tmp, 'a')
295
+ fs.mkdirSync(aDir)
296
+ const untar = run('tar', ['-xzf', path.join(tmp, tarball), '-C', aDir, '--strip-components=1'])
297
+ if (untar.status !== 0) {
298
+ result.error = `tar failed: ${(untar.stderr || '').slice(0, 300)}`
299
+ return result
300
+ }
301
+ // 副本 package.json 上的生效标记不属于用户改动:临时摘掉,diff 完恢复
302
+ try {
303
+ const epkg = readJson(entryPkg)
304
+ if (String(epkg.description || '').includes(MOUNT_MARKER)) {
305
+ markedDesc = epkg.description
306
+ epkg.description = markedDesc.replace(MOUNT_MARKER, '').trim()
307
+ fs.writeFileSync(entryPkg, JSON.stringify(epkg, null, 2) + '\n')
308
+ }
309
+ } catch {}
310
+ fs.symlinkSync(dir, path.join(tmp, 'b'))
311
+ const exclFile = path.join(tmp, 'excludes.txt')
312
+ fs.writeFileSync(exclFile, EXCLUDES.join('\n') + '\n')
313
+
314
+ const diff = run('diff', ['-ruN', '-X', exclFile, 'a', 'b'], { cwd: tmp })
315
+ if (diff.status === 0) {
316
+ result.ok = true
317
+ result.changed = []
318
+ return result // 与原版一致,无补丁
319
+ }
320
+ if (diff.status !== 1) {
321
+ result.error = `diff error: ${(diff.stderr || '').slice(0, 300)}`
322
+ return result
323
+ }
324
+
325
+ // 摘出二进制差异:整文件另存,不进文本补丁
326
+ const binFiles = []
327
+ const keptLines = []
328
+ for (const line of diff.stdout.match(/.*(\n|$)/g).filter((l) => l.length)) {
329
+ const bm = /^Binary files a\/(?<p>.+) and b\/.+ differ$/.exec(line)
330
+ if (bm) {
331
+ binFiles.push(bm.groups.p)
332
+ continue
333
+ }
334
+ keptLines.push(line)
335
+ }
336
+ if (binFiles.length) {
337
+ const destBase = path.join(BIN_DIR, slug)
338
+ fs.mkdirSync(destBase, { recursive: true })
339
+ for (const rel of binFiles) {
340
+ const dest = path.join(destBase, rel)
341
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
342
+ fs.copyFileSync(path.join(dir, rel), dest)
343
+ }
344
+ } else {
345
+ fs.rmSync(path.join(BIN_DIR, slug), { recursive: true, force: true })
346
+ }
347
+
348
+ // diff 头部会带上 -X 参数与临时路径,统一规范化成 `diff -ruN a/x b/x`
349
+ const body = keptLines.join('').replace(/^diff -ruN.*? (?=a\/)/gm, 'diff -ruN ')
350
+ const changed = [...body.matchAll(/^diff -ruN a\/(?<p>.+?) b\/.+$/gm)].map((m) => m.groups.p)
351
+ result.changed = [...changed, ...binFiles.map((p) => p + ' (binary)')]
352
+
353
+ fs.mkdirSync(PATCHES_DIR, { recursive: true })
354
+ const target = path.join(PATCHES_DIR, `${slug}__${version}.patch`)
355
+ if (body.trim()) {
356
+ const header =
357
+ `# dsh-patchkeeper patch\n` +
358
+ `# package: ${name}\n# version: ${version}\n` +
359
+ `# extracted: ${new Date().toISOString()}\n`
360
+ fs.writeFileSync(target, header + body)
361
+ } else {
362
+ fs.rmSync(target, { force: true })
363
+ }
364
+ // 清掉同包旧版本补丁
365
+ for (const p of listPatchFiles()) {
366
+ if (p.slug === slug && p.version !== version) {
367
+ fs.rmSync(path.join(PATCHES_DIR, p.file), { force: true })
368
+ log?.(` 清理旧版本补丁: ${p.file}`)
369
+ }
370
+ }
371
+ // 未挂载时有人直接改了原版:改动已收进补丁,顺手把原版恢复纯净(保住「原版永远干净」)
372
+ if (!mounted && result.changed?.length) {
373
+ let restored = 0
374
+ for (const rawRel of result.changed) {
375
+ const rel = rawRel.replace(/ \(binary\)$/, '')
376
+ const pristine = path.join(aDir, rel)
377
+ const target = path.join(dir, rel)
378
+ if (fs.existsSync(pristine)) fs.copyFileSync(pristine, target)
379
+ else fs.rmSync(target, { force: true }) // pristine 没有 = 新增文件,从原版删掉
380
+ restored++
381
+ }
382
+ if (restored) log?.(` 已把原版恢复纯净(${restored} 个文件的改动已在补丁里)`)
383
+ }
384
+ result.ok = true
385
+ return result
386
+ } finally {
387
+ // 恢复生效标记(finally 兜住所有提前 return 路径)
388
+ if (markedDesc !== null) {
389
+ try {
390
+ const epkg = readJson(entryPkg)
391
+ epkg.description = markedDesc
392
+ fs.writeFileSync(entryPkg, JSON.stringify(epkg, null, 2) + '\n')
393
+ } catch {}
394
+ }
395
+ fs.rmSync(tmp, { recursive: true, force: true })
396
+ }
397
+ }
398
+
399
+ // ---------- AI 适配(版本失配后的自动合并) ----------
400
+
401
+ const ADAPT_DIR = () => path.join(DATA_DIR, 'adapt')
402
+
403
+ // 补丁文本 → 按文件拆段(每段带 diff 头 + ---/+++ + hunks)
404
+ function splitPatchByFile(text) {
405
+ const sections = []
406
+ const marks = [...text.matchAll(/^diff -ruN(?: \S+)* a\/(?<f>.+?) b\/.+$/gm)]
407
+ for (let i = 0; i < marks.length; i++) {
408
+ const start = marks[i].index
409
+ const end = i + 1 < marks.length ? marks[i + 1].index : text.length
410
+ sections.push({ file: marks[i].groups.f, text: text.slice(start, end) })
411
+ }
412
+ return sections
413
+ }
414
+
415
+ // 机械合:旧补丁逐文件 fuzz 打到新版原版上;全干净 → 直接产出新版补丁;有冲突 → 逐文件打包 AI 上下文
416
+ function cmdAdaptAuto({ name, toVersion, log }) {
417
+ const p = listPatchFiles().find((x) => x.name === name)
418
+ if (!p) return { command: 'adapt-auto', name, outcome: 'no-patch' }
419
+ const installed = installedVersion(name)
420
+ const target = toVersion || installed
421
+ if (!target) return { command: 'adapt-auto', name, outcome: 'no-target-version' }
422
+
423
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'patchkeeper-adapt-'))
424
+ try {
425
+ const pack = run('npm', ['pack', `${name}@${target}`, '--pack-destination', tmp, '--silent'], { cwd: tmp })
426
+ if (pack.status !== 0) return { command: 'adapt-auto', name, outcome: 'pack-failed', error: (pack.stderr || '').slice(0, 300) }
427
+ const tarball = (pack.stdout || '').trim().split('\n').pop().trim()
428
+ const fresh = path.join(tmp, 'fresh')
429
+ fs.mkdirSync(fresh)
430
+ run('tar', ['-xzf', path.join(tmp, tarball), '-C', fresh, '--strip-components=1'])
431
+
432
+ // 逐文件打:干净文件留在 fresh 上,失败的进 AI 上下文(AI 只需管坏文件)
433
+ const patchText = fs.readFileSync(path.join(PATCHES_DIR, p.file), 'utf8')
434
+ const sections = splitPatchByFile(patchText)
435
+ const rejected = []
436
+ for (const sec of sections) {
437
+ const secFile = path.join(tmp, 'sec.patch')
438
+ fs.writeFileSync(secFile, sec.text)
439
+ const rejFile = path.join(tmp, 'sec.rej')
440
+ fs.rmSync(rejFile, { force: true })
441
+ const ap = run('patch', ['-p1', '-N', '-E', '-f', '--fuzz=3', '-d', fresh, '-i', secFile, '-r', rejFile])
442
+ if (ap.status !== 0) {
443
+ rejected.push({
444
+ file: sec.file,
445
+ rej: fs.existsSync(rejFile) ? fs.readFileSync(rejFile, 'utf8') : '(整个文件段失败)',
446
+ newContent: fs.existsSync(path.join(fresh, sec.file)) ? fs.readFileSync(path.join(fresh, sec.file), 'utf8') : null,
447
+ })
448
+ }
449
+ }
450
+ if (!rejected.length) {
451
+ const out = finalizeAdapt(name, p, target, fresh, tmp, log)
452
+ return { command: 'adapt-auto', name, outcome: out.ok ? 'auto-merged' : 'auto-failed', ...out }
453
+ }
454
+ const dir = path.join(ADAPT_DIR(), p.slug)
455
+ fs.rmSync(dir, { recursive: true, force: true })
456
+ fs.mkdirSync(dir, { recursive: true })
457
+ const pack2 = { name, fromVersion: p.version, toVersion: target, files: {} }
458
+ for (const r of rejected) pack2.files[r.file] = { rej: r.rej, newContent: r.newContent }
459
+ fs.writeFileSync(path.join(dir, 'context.json'), JSON.stringify(pack2, null, 2))
460
+ fs.cpSync(fresh, path.join(dir, 'fresh'), { recursive: true })
461
+ return { command: 'adapt-auto', name, outcome: 'needs-ai', contextDir: dir, rejectedFiles: rejected.map((r) => r.file) }
462
+ } finally {
463
+ fs.rmSync(tmp, { recursive: true, force: true })
464
+ }
465
+ }
466
+
467
+ // 合并成功后的收口:从合并结果重新生成补丁、替换旧补丁文件、登记状态
468
+ function finalizeAdapt(name, oldPatch, toVersion, mergedDir, tmp, log) {
469
+ return writeAdaptedPatch(name, oldPatch, toVersion, mergedDir, tmp, log)
470
+ }
471
+
472
+ function pristineDir(tmp, tarball) {
473
+ const d = path.join(tmp, 'pristine')
474
+ if (!fs.existsSync(d)) {
475
+ fs.mkdirSync(d, { recursive: true })
476
+ if (tarball) run('tar', ['-xzf', path.join(tmp, tarball), '-C', d, '--strip-components=1'])
477
+ }
478
+ return d
479
+ }
480
+
481
+ function writeAdaptedPatch(name, oldPatch, toVersion, mergedDir, tmp, log) {
482
+ const tarball = fs.readdirSync(tmp).find((f) => f.endsWith('.tgz'))
483
+ const pristine = pristineDir(tmp, tarball)
484
+ const aLink = path.join(tmp, 'a')
485
+ const bLink = path.join(tmp, 'b')
486
+ fs.rmSync(aLink, { force: true }); fs.rmSync(bLink, { force: true })
487
+ fs.symlinkSync(pristine, aLink)
488
+ fs.symlinkSync(mergedDir, bLink)
489
+ const exclFile = path.join(tmp, 'excludes.txt')
490
+ fs.writeFileSync(exclFile, EXCLUDES.join('\n') + '\n')
491
+ const diff = run('diff', ['-ruN', '-X', exclFile, 'a', 'b'], { cwd: tmp })
492
+ if (diff.status !== 1) return { ok: false, error: 'adapt produced no diff or diff failed' }
493
+ const body = diff.stdout.replace(/^diff -ruN.*? (?=a\/)/gm, 'diff -ruN ')
494
+ const slug = oldPatch.slug
495
+ const target = path.join(PATCHES_DIR, `${slug}__${toVersion}.patch`)
496
+ const header = `# dsh-patchkeeper patch\n# package: ${name}\n# version: ${toVersion}\n# adapted-from: ${oldPatch.version}(自动合并)\n# extracted: ${new Date().toISOString()}\n`
497
+ fs.writeFileSync(target, header + body)
498
+ // 同名(同版本再适配)时别把自己删了
499
+ if (path.basename(target) !== oldPatch.file) fs.rmSync(path.join(PATCHES_DIR, oldPatch.file), { force: true })
500
+ log?.(` 补丁已适配:${name} ${oldPatch.version} → ${toVersion}`)
501
+ return { ok: true, patch: target }
502
+ }
503
+
504
+ // AI 补完后的落盘验证:把 AI 补丁打到留存的 fresh 副本上,验证通过才收口
505
+ function cmdAdaptApply({ name, toVersion, log }) {
506
+ const slug = slugOf(name)
507
+ const dir = path.join(ADAPT_DIR(), slug)
508
+ const aiPatch = path.join(dir, 'ai.patch')
509
+ const fresh = path.join(dir, 'fresh')
510
+ if (!fs.existsSync(aiPatch) || !fs.existsSync(fresh)) return { command: 'adapt-apply', name, outcome: 'no-context' }
511
+ const oldPatch = listPatchFiles().find((x) => x.name === name)
512
+ if (!oldPatch) return { command: 'adapt-apply', name, outcome: 'no-patch' }
513
+
514
+ const rej = path.join(dir, 'ai.rej')
515
+ fs.rmSync(rej, { force: true })
516
+ const ap = run('patch', ['-p1', '-N', '-E', '-f', '-d', fresh, '-i', aiPatch, '-r', rej])
517
+ if (ap.status !== 0) return { command: 'adapt-apply', name, outcome: 'ai-patch-rejected', rejectFile: rej }
518
+
519
+ // JS 语法门:改过的文件都要过 node --check
520
+ const aiText = fs.readFileSync(aiPatch, 'utf8')
521
+ const jsFiles = [...aiText.matchAll(/^diff \S+ b\/(.*\.(?:js|mjs|cjs))$/gm)].map((m) => m[1])
522
+ for (const f of jsFiles) {
523
+ const chk = run('node', ['--check', path.join(fresh, f)])
524
+ if (chk.status !== 0) return { command: 'adapt-apply', name, outcome: 'syntax-failed', file: f, error: (chk.stderr || '').slice(0, 300) }
525
+ }
526
+
527
+ // 用 fresh(已完成合并)与全新 pristine 出最终补丁
528
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'patchkeeper-finalize-'))
529
+ try {
530
+ const pack = run('npm', ['pack', `${name}@${toVersion}`, '--pack-destination', tmp, '--silent'], { cwd: tmp })
531
+ if (pack.status !== 0) return { command: 'adapt-apply', name, outcome: 'pack-failed' }
532
+ fs.renameSync(path.join(tmp, (pack.stdout || '').trim().split('\n').pop().trim()), path.join(tmp, 'pkg.tgz'))
533
+ // writeAdaptedPatch 期望 tmp 里有 .tgz
534
+ const out = writeAdaptedPatch(name, oldPatch, toVersion, fresh, tmp, log)
535
+ if (!out.ok) return { command: 'adapt-apply', name, outcome: 'diff-failed', error: out.error }
536
+ fs.rmSync(dir, { recursive: true, force: true })
537
+ return { command: 'adapt-apply', name, outcome: 'adapted', patch: out.patch }
538
+ } finally {
539
+ fs.rmSync(tmp, { recursive: true, force: true })
540
+ }
541
+ }
542
+
543
+ function cmdExtract({ only, log }) {
544
+ const pkgFile = readJson(path.join(PROFILE, 'package.json'))
545
+ const deps = Object.entries(pkgFile.dependencies || {})
546
+ const results = []
547
+ for (const [name, spec] of deps) {
548
+ if (SKIP_PKGS.has(name)) continue
549
+ if (only && name !== only) continue
550
+ log?.(`diff ${name} …`)
551
+ const r = extractOne(name, spec, { log })
552
+ if (r.error) log?.(` ✗ ${r.error}`)
553
+ else if (r.changed?.length) log?.(` ✓ ${r.changed.length} 个文件有改动`)
554
+ else log?.(` - 与原版一致`)
555
+ results.push(r)
556
+ }
557
+ return { command: 'extract', results }
558
+ }
559
+
560
+ // ---------- apply / revert / status(影子副本) ----------
561
+
562
+ // 把补丁打进指定目录(shadow 副本),失败返回 false
563
+ function patchInto(dir, p) {
564
+ const patchPath = path.join(PATCHES_DIR, p.file)
565
+ const hasTextPatch = fs.existsSync(patchPath)
566
+ const { binBase, files: binFiles } = binFilesOf(p.slug)
567
+ if (hasTextPatch) {
568
+ fs.mkdirSync(REJECTS_DIR, { recursive: true })
569
+ const rej = path.join(REJECTS_DIR, `${p.slug}.rej`)
570
+ fs.rmSync(rej, { force: true })
571
+ const ap = run('patch', ['-p1', '-N', '-E', '-f', '-d', dir, '-i', patchPath, '-r', rej])
572
+ if (ap.status !== 0) return false
573
+ if (probePatch(dir, patchPath) !== 'applied') return false
574
+ }
575
+ for (const rel of binFiles) {
576
+ const dest = path.join(dir, rel)
577
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
578
+ fs.copyFileSync(path.join(binBase, rel), dest)
579
+ if (!fs.readFileSync(dest).equals(fs.readFileSync(path.join(binBase, rel)))) return false
580
+ }
581
+ return hasTextPatch || binFiles.length > 0
582
+ }
583
+
584
+ function mount(p) {
585
+ const entry = path.join(NM, p.name)
586
+ const shadow = shadowDir(p.slug)
587
+ const orig = origDir(p.slug)
588
+ fs.rmSync(shadow, { recursive: true, force: true })
589
+ fs.mkdirSync(SHADOWS, { recursive: true })
590
+ // 克隆原版(APFS clonefile,近乎零成本;失败退回普通复制)
591
+ let cp = run('cp', ['-Rc', entry + '/', shadow])
592
+ if (cp.status !== 0) cp = run('cp', ['-R', entry + '/', shadow])
593
+ if (cp.status !== 0) {
594
+ fs.rmSync(shadow, { recursive: true, force: true })
595
+ return { ok: false, error: `copy failed: ${(cp.stderr || '').slice(0, 200)}` }
596
+ }
597
+ // 副本在 profile 树外:补 node_modules 软链指回 profile,平铺依赖沿此可达
598
+ const shadowNm = path.join(shadow, 'node_modules')
599
+ if (!fs.existsSync(shadowNm)) fs.symlinkSync(NM, shadowNm)
600
+ if (!patchInto(shadow, p)) {
601
+ fs.rmSync(shadow, { recursive: true, force: true })
602
+ return { ok: false, error: 'patch failed on shadow' }
603
+ }
604
+ // 正向确认标记:挂载期间插件管理页的描述里可见「🩹 补丁生效中」;看不到 = 补丁没生效
605
+ try {
606
+ const sp = path.join(shadow, 'package.json')
607
+ const spkg = readJson(sp)
608
+ if (!String(spkg.description || '').includes(MOUNT_MARKER)) {
609
+ spkg.description = `${spkg.description || ''} ${MOUNT_MARKER}`.trim()
610
+ fs.writeFileSync(sp, JSON.stringify(spkg, null, 2) + '\n')
611
+ }
612
+ } catch {}
613
+ // 换挂载:原版挪进 orig/,条目换成指向副本的软链
614
+ fs.mkdirSync(path.dirname(orig), { recursive: true })
615
+ fs.rmSync(orig, { recursive: true, force: true })
616
+ fs.renameSync(entry, orig)
617
+ fs.symlinkSync(shadow, entry)
618
+ const state = readState()
619
+ writeState({ swaps: { ...(state.swaps || {}), [p.name]: { shadow, orig, at: new Date().toISOString() } } })
620
+ return { ok: true }
621
+ }
622
+
623
+ function applyOne(p, { dryRun, force }) {
624
+ const r = { name: p.name, patchVersion: p.version }
625
+ const entry = path.join(NM, p.name)
626
+ if (!fs.existsSync(entry) && !fs.existsSync(origDir(p.slug))) {
627
+ r.status = 'missing-target'
628
+ return r
629
+ }
630
+ r.enabled = isEnabled(p.name)
631
+ r.mounted = isMounted(p.name, p.slug)
632
+ r.installedVersion = installedVersion(p.name)
633
+ r.versionMatch = r.installedVersion === p.version
634
+ if (!r.enabled) {
635
+ if (r.mounted && !dryRun) dismount(p) // 禁用 = 恢复原插件 + 清副本
636
+ r.mounted = false
637
+ r.status = 'disabled'
638
+ return r
639
+ }
640
+ if (r.versionMatch === false && !force) {
641
+ // 版本不匹配:确保没挂着旧副本(保底清除已处理,这里只是保险)
642
+ if (r.mounted && !dryRun) dismount(p)
643
+ r.mounted = false
644
+ r.status = 'version-mismatch'
645
+ return r
646
+ }
647
+ if (r.mounted && !(force && !dryRun)) {
648
+ // 新鲜度校验:补丁文件改过了就重建副本(probe 是 dry-run,只读不写)
649
+ const patchPath = path.join(PATCHES_DIR, p.file)
650
+ if (fs.existsSync(patchPath) && probePatch(shadowDir(p.slug), patchPath) !== 'applied') {
651
+ if (!dryRun) {
652
+ dismount(p)
653
+ const m = mount(p)
654
+ r.status = m.ok ? 'applied-now' : 'apply-failed'
655
+ if (!m.ok) r.error = m.error
656
+ return r
657
+ }
658
+ }
659
+ r.status = 'applied'
660
+ return r
661
+ }
662
+ if (dryRun) {
663
+ r.status = 'not-applied'
664
+ return r
665
+ }
666
+ // force 时即使已挂载也重建副本(补丁文件可能刚被编辑过)
667
+ if (r.mounted) dismount(p)
668
+ const m = mount(p)
669
+ if (!m.ok) {
670
+ r.status = 'apply-failed'
671
+ r.error = m.error
672
+ return r
673
+ }
674
+ r.mounted = true
675
+ r.status = 'applied-now'
676
+ return r
677
+ }
678
+
679
+ function revertOne(p) {
680
+ const r = { name: p.name, patchVersion: p.version }
681
+ r.installedVersion = installedVersion(p.name)
682
+ r.status = dismount(p) ? 'reverted' : 'not-applied'
683
+ return r
684
+ }
685
+
686
+ function collectStatus({ dryRun, force, only }) {
687
+ const results = listPatchFiles()
688
+ .filter((p) => !only || p.name === only)
689
+ .map((p) => applyOne(p, { dryRun, force }))
690
+ const out = { command: dryRun ? 'status' : 'apply', profile: PROFILE, results }
691
+ // 失明检测:看门狗自己没上岗时,status 必须大声说出来(今天的教训)
692
+ if (results.length) {
693
+ const pkg = readJson(path.join(PROFILE, 'package.json'))
694
+ const enabled = (pkg.dsh?.profile?.bundles || []).includes('@alequet/dsh-patchkeeper')
695
+ const noneMounted = results.every((r) => !r.mounted)
696
+ if (!enabled) {
697
+ out.alarm = '🚨 patchkeeper 未启用(不在 bundles 列表):所有补丁正在静默失效!运行 doctor --fix 并重启 DSH'
698
+ } else if (dryRun && noneMounted && results.some((r) => r.versionMatch)) {
699
+ out.alarm = '🚨 有匹配补丁但一个都没挂载——若已重启过 DSH,patchkeeper 可能加载失败,请查日志'
700
+ }
701
+ }
702
+ return out
703
+ }
704
+
705
+ function cmdRevert({ only } = {}) {
706
+ const results = listPatchFiles()
707
+ .filter((p) => !only || p.name === only)
708
+ .map(revertOne)
709
+ return { command: 'revert', profile: PROFILE, results }
710
+ }
711
+
712
+ // ---------- doctor ----------
713
+
714
+ function cmdDoctor({ fix, log }) {
715
+ const issues = []
716
+ const linkPath = path.join(NM, '@alequet/dsh-patchkeeper')
717
+ const pkgFile = path.join(PROFILE, 'package.json')
718
+ const pkg = readJson(pkgFile)
719
+
720
+ if (!fs.existsSync(linkPath)) {
721
+ issues.push('node_modules/@alequet/dsh-patchkeeper 缺失——请通过插件管理页(安装第三方插件)重新安装')
722
+ }
723
+ if (!pkg.dependencies?.['@alequet/dsh-patchkeeper']) {
724
+ issues.push('profile package.json 缺少 @alequet/dsh-patchkeeper 依赖——请通过插件管理页安装')
725
+ }
726
+ const bundles = pkg.dsh?.profile?.bundles || []
727
+ if (!bundles.includes('@alequet/dsh-patchkeeper')) {
728
+ issues.push('profile bundles 列表缺少 @alequet/dsh-patchkeeper')
729
+ if (fix) {
730
+ pkg.dsh.profile.bundles = ['@alequet/dsh-patchkeeper', ...bundles]
731
+ fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n')
732
+ log?.('已把 @alequet/dsh-patchkeeper 加回 bundles 首位')
733
+ }
734
+ }
735
+ return { command: 'doctor', fixed: !!fix, issues }
736
+ }
737
+
738
+ // ---------- 入口 ----------
739
+
740
+ const args = process.argv.slice(2)
741
+ const command = args.find((a) => !a.startsWith('-')) || 'help'
742
+ const flags = {
743
+ json: args.includes('--json'),
744
+ dryRun: args.includes('--dry-run'),
745
+ fix: args.includes('--fix'),
746
+ force: args.includes('--force'),
747
+ only: args.includes('--pkg') ? args[args.indexOf('--pkg') + 1] : null,
748
+ to: args.includes('--to') ? args[args.indexOf('--to') + 1] : null,
749
+ }
750
+ const log = flags.json ? null : (s) => console.log(s)
751
+
752
+ let out
753
+ switch (command) {
754
+ case 'extract': out = cmdExtract({ only: flags.only, log }); break
755
+ case 'apply': {
756
+ const repaired = ensureCleanMount({ only: flags.only }) // 启动保底清除
757
+ out = collectStatus({ dryRun: false, force: flags.force, only: flags.only })
758
+ if (repaired.length) out.repaired = repaired
759
+ break
760
+ }
761
+ case 'revert': out = cmdRevert({ only: flags.only }); break
762
+ case 'remount': {
763
+ // 调试循环快捷键:摘旧副本 → 按当前补丁重建并挂载
764
+ cmdRevert({ only: flags.only })
765
+ out = collectStatus({ dryRun: false, force: true, only: flags.only })
766
+ break
767
+ }
768
+ case 'status': out = collectStatus({ dryRun: true, force: flags.force, only: flags.only }); break
769
+ case 'list': {
770
+ const cfg = readConfig()
771
+ const state = readState()
772
+ const lastApply = state.lastApply || []
773
+ const swaps = state.swaps || {}
774
+ out = {
775
+ command: 'list',
776
+ patches: listPatchFiles().map((p) => {
777
+ const probe = applyOne(p, { dryRun: true })
778
+ const last = lastApply.find((r) => r.name === p.name)
779
+ return {
780
+ name: p.name,
781
+ version: p.version,
782
+ enabled: cfg[p.name]?.enabled !== false,
783
+ note: cfg[p.name]?.note || '',
784
+ risk: cfg[p.name]?.risk || '',
785
+ files: patchFileList(p),
786
+ installedVersion: probe.installedVersion,
787
+ status: probe.status,
788
+ mounted: !!probe.mounted,
789
+ mountedAt: swaps[p.name]?.at || null,
790
+ adapt: (state.adapt || {})[`${p.name}@${probe.installedVersion}`] || null,
791
+ // 上次真实挂载留下的错误(probe 是 dry-run,探不到这些)
792
+ lastError: (lastApply && ['apply-failed', 'conflict'].includes(lastApply.status) && (lastApply.error || lastApply.status)) || null,
793
+ }
794
+ }),
795
+ }
796
+ if (out.patches.length) {
797
+ const pkgj = readJson(path.join(PROFILE, 'package.json'))
798
+ if (!(pkgj.dsh?.profile?.bundles || []).includes('@alequet/dsh-patchkeeper')) {
799
+ out.alarm = '🚨 patchkeeper 未启用(不在 bundles 列表):所有补丁正在静默失效!运行 doctor --fix 并重启 DSH'
800
+ } else if (out.patches.every((r) => !r.mounted) && out.patches.some((r) => r.enabled !== false && r.installedVersion === r.version)) {
801
+ out.alarm = '🚨 有匹配补丁但一个都没挂载——若已重启过 DSH,patchkeeper 可能加载失败,请查日志'
802
+ }
803
+ }
804
+ break
805
+ }
806
+ case 'enable':
807
+ case 'disable': {
808
+ const target = flags.only
809
+ if (!target) {
810
+ console.error('用法: ' + command + ' --pkg <包名>')
811
+ process.exit(1)
812
+ }
813
+ const cfg = readConfig()
814
+ cfg[target] = { ...(cfg[target] || {}), enabled: command === 'enable' }
815
+ writeConfig(cfg)
816
+ out = collectStatus({ dryRun: false, force: flags.force, only: target })
817
+ break
818
+ }
819
+ case 'risk': {
820
+ const rest = []
821
+ for (let i = args.indexOf('risk') + 1; i < args.length; i++) {
822
+ if (args[i] === '--pkg') { i++; continue }
823
+ if (!args[i].startsWith('-')) rest.push(args[i])
824
+ }
825
+ const riskText = rest.join(' ')
826
+ if (!flags.only) {
827
+ console.error('用法: risk --pkg <包名> [风险说明](省略说明=清除)')
828
+ process.exit(1)
829
+ }
830
+ const cfg = readConfig()
831
+ cfg[flags.only] = { ...(cfg[flags.only] || {}), risk: riskText }
832
+ writeConfig(cfg)
833
+ out = { command: 'risk', name: flags.only, risk: riskText }
834
+ break
835
+ }
836
+ case 'note': {
837
+ const rest = []
838
+ for (let i = args.indexOf('note') + 1; i < args.length; i++) {
839
+ if (args[i] === '--pkg') { i++; continue } // 跳过 --pkg 及其值
840
+ if (!args[i].startsWith('-')) rest.push(args[i])
841
+ }
842
+ const noteText = rest.join(' ')
843
+ if (!flags.only || !noteText) {
844
+ console.error('用法: note --pkg <包名> <效果说明>')
845
+ process.exit(1)
846
+ }
847
+ const cfg = readConfig()
848
+ cfg[flags.only] = { ...(cfg[flags.only] || {}), note: noteText }
849
+ writeConfig(cfg)
850
+ out = { command: 'note', name: flags.only, note: noteText }
851
+ break
852
+ }
853
+ case 'adapt-auto': {
854
+ if (!flags.only) { console.error('用法: adapt-auto --pkg <包名> [--to <版本>]'); process.exit(1) }
855
+ out = cmdAdaptAuto({ name: flags.only, toVersion: flags.to, log })
856
+ break
857
+ }
858
+ case 'adapt-apply': {
859
+ if (!flags.only || !flags.to) { console.error('用法: adapt-apply --pkg <包名> --to <版本>(AI 补丁放在 adapt/<slug>/ai.patch)'); process.exit(1) }
860
+ out = cmdAdaptApply({ name: flags.only, toVersion: flags.to, log })
861
+ break
862
+ }
863
+ case 'doctor': out = cmdDoctor({ fix: flags.fix, log }); break
864
+ default:
865
+ console.log('用法: extract | apply [--force] | remount | revert | status | list | doctor [--fix] [--json] [--pkg <name>]')
866
+ process.exit(command === 'help' ? 0 : 1)
867
+ }
868
+
869
+ if (command === 'apply' || command === 'remount') {
870
+ writeState({ ts: new Date().toISOString(), lastApply: out.results })
871
+ }
872
+
873
+ if (flags.json) {
874
+ console.log(JSON.stringify(out, null, 2))
875
+ } else if (command === 'apply' || command === 'status' || command === 'revert' || command === 'remount') {
876
+ const icon = {
877
+ 'applied-now': '✓ 已挂载副本', applied: '· 副本已挂载', 'not-applied': '○ 未挂载',
878
+ conflict: '✗ 冲突', 'missing-target': '✗ 目标缺失', 'apply-failed': '✗ 挂载失败',
879
+ empty: '- 空补丁', 'version-mismatch': '⊘ 版本不匹配,已跳过', disabled: '⏸ 已禁用',
880
+ reverted: '✓ 已恢复原版', 'revert-failed': '✗ 恢复失败',
881
+ }
882
+ if (out.alarm) console.log(`\n${out.alarm}\n`)
883
+ for (const r of out.results) {
884
+ const vm = r.versionMatch === false ? ` (补丁 ${r.patchVersion} ≠ 已装 ${r.installedVersion})` : ''
885
+ console.log(`${icon[r.status] || r.status} ${r.name}${vm}`)
886
+ }
887
+ const skipped = out.results.filter((r) => r.status === 'version-mismatch')
888
+ if (skipped.length && command !== 'revert') {
889
+ console.log(`\n${skipped.length} 个补丁因版本不匹配被跳过(适配后用 extract 重建;硬打可用 apply --force)`)
890
+ }
891
+ const bad = out.results.filter((r) => ['conflict', 'missing-target', 'apply-failed', 'revert-failed'].includes(r.status))
892
+ if (bad.length) {
893
+ console.log(`\n${bad.length} 个补丁需要人工处理,reject 文件见 ${REJECTS_DIR}`)
894
+ process.exitCode = 2
895
+ }
896
+ } else if (command === 'list') {
897
+ for (const p of out.patches) {
898
+ const flag = p.enabled ? (p.mounted ? '✓ 挂载中' : '○ 未挂载') : '⏸ 已禁用'
899
+ console.log(`${flag} ${p.name}@${p.version}${p.note ? ' —— ' + p.note : ''}`)
900
+ }
901
+ if (!out.patches.length) console.log('(还没有补丁,先跑 extract)')
902
+ } else if (command === 'doctor') {
903
+ if (!out.issues.length) console.log('注册状态正常 ✓')
904
+ else for (const i of out.issues) console.log((out.fixed ? '已修复: ' : '问题: ') + i)
905
+ }