@alequet/dsh-patchkeeper 0.5.3 → 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/README.md CHANGED
@@ -19,13 +19,23 @@ patches/<pkg>__<ver>.patch @scope/pkg ──软链──▶ shadows/<pkg>(原
19
19
 
20
20
  ## 安装
21
21
 
22
- 设置 → 插件 → 添加 → 安装第三方插件,输入:
22
+ 已发布到 npm:[**@alequet/dsh-patchkeeper**](https://www.npmjs.com/package/@alequet/dsh-patchkeeper)
23
+
24
+ **方式 A(推荐)**:设置 → 插件 → 添加 → 安装第三方插件,输入:
23
25
 
24
26
  ```
25
27
  @alequet/dsh-patchkeeper
26
28
  ```
27
29
 
28
- 重启后生效。
30
+ **方式 B(命令行)**:
31
+
32
+ ```bash
33
+ dsh plugin --profile desktop add @alequet/dsh-patchkeeper
34
+ ```
35
+
36
+ **方式 C(GitHub 源码)**:安装框里输入 `github:alequet/dsh-patchkeeper`
37
+
38
+ 装完重启 DSH 生效。
29
39
 
30
40
  ## 可观测性(不靠「没报错」脑补)
31
41
 
@@ -33,6 +43,7 @@ patches/<pkg>__<ver>.patch @scope/pkg ──软链──▶ shadows/<pkg>(原
33
43
  - **开机 toast**:启动后右上角「N 个补丁生效中 ✓」;异常则常驻红/黄牌
34
44
  - **补丁管理台**:patchkeeper 自己的详情页——补丁清单、效果说明、版本对照、每补丁启用开关(运行期即时挂载/摘除)、操作结果红绿反馈、失败常驻红字诊断
35
45
  - **CLI 失明告警**:补丁在库但 patchkeeper 未启用时,`status` 直接吼出来
46
+ - **AI 自动适配**:启动时发现插件升级导致补丁失配 → 后台先机械合并(fuzz),冲突文件交 LLM 解冲突 → 成功则补丁自动升级、下次重启挂载;失败则记录原因并**不再自动重试**(管理台可人工重试)
36
47
 
37
48
  ## CLI
38
49
 
package/bin/cli.mjs CHANGED
@@ -396,6 +396,150 @@ function extractOne(name, spec, { log }) {
396
396
  }
397
397
  }
398
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
+
399
543
  function cmdExtract({ only, log }) {
400
544
  const pkgFile = readJson(path.join(PROFILE, 'package.json'))
401
545
  const deps = Object.entries(pkgFile.dependencies || {})
@@ -601,6 +745,7 @@ const flags = {
601
745
  fix: args.includes('--fix'),
602
746
  force: args.includes('--force'),
603
747
  only: args.includes('--pkg') ? args[args.indexOf('--pkg') + 1] : null,
748
+ to: args.includes('--to') ? args[args.indexOf('--to') + 1] : null,
604
749
  }
605
750
  const log = flags.json ? null : (s) => console.log(s)
606
751
 
@@ -642,6 +787,7 @@ switch (command) {
642
787
  status: probe.status,
643
788
  mounted: !!probe.mounted,
644
789
  mountedAt: swaps[p.name]?.at || null,
790
+ adapt: (state.adapt || {})[`${p.name}@${probe.installedVersion}`] || null,
645
791
  // 上次真实挂载留下的错误(probe 是 dry-run,探不到这些)
646
792
  lastError: (lastApply && ['apply-failed', 'conflict'].includes(lastApply.status) && (lastApply.error || lastApply.status)) || null,
647
793
  }
@@ -704,6 +850,16 @@ switch (command) {
704
850
  out = { command: 'note', name: flags.only, note: noteText }
705
851
  break
706
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
+ }
707
863
  case 'doctor': out = cmdDoctor({ fix: flags.fix, log }); break
708
864
  default:
709
865
  console.log('用法: extract | apply [--force] | remount | revert | status | list | doctor [--fix] [--json] [--pkg <name>]')
package/client.js CHANGED
@@ -217,7 +217,7 @@ window.__ModuleLoader__.load({
217
217
  }
218
218
  }
219
219
 
220
- function PatchRow({ p, busy, op, bootTs, onToggle, onSaveNote }) {
220
+ function PatchRow({ p, busy, op, bootTs, onToggle, onSaveNote, onRetry }) {
221
221
  const [note, setNote] = React.useState(p.note || '')
222
222
  const [dirty, setDirty] = React.useState(false)
223
223
  const meta = statusOf(p, bootTs)
@@ -254,6 +254,27 @@ window.__ModuleLoader__.load({
254
254
  : null,
255
255
  diag ? h('div', { key: 'diag', style: { fontSize: 12, color: '#dc3c3c', marginTop: 4, lineHeight: 1.6 } }, diag) : null,
256
256
  p.risk ? h('div', { key: 'risk', style: { fontSize: 12, color: '#d29922', marginTop: 4, lineHeight: 1.6 } }, `⚠ 禁用风险:${p.risk}`) : null,
257
+ p.adapt
258
+ ? h('div', {
259
+ key: 'adapt',
260
+ style: {
261
+ fontSize: 12, marginTop: 4, lineHeight: 1.6,
262
+ color: p.adapt.outcome === 'ai-failed' ? '#dc3c3c' : p.adapt.outcome === 'adapted' ? '#2ea043' : '#d29922',
263
+ },
264
+ }, [
265
+ p.adapt.outcome === 'running' ? `🤖 补丁正在自动适配 v${p.installedVersion}(机械合并 → AI 解冲突)…` : null,
266
+ p.adapt.outcome === 'adapted' ? `✓ 补丁已自动适配 v${p.installedVersion}(${p.adapt.mode === 'ai' ? 'AI 解冲突' : '机械合并'}),重启 DSH 后自动挂载` : null,
267
+ p.adapt.outcome === 'ai-failed' ? `✗ 自动适配失败:${p.adapt.error || '未知原因'}——已转人工,不再自动重试` : null,
268
+ p.adapt.outcome === 'ai-failed'
269
+ ? h('button', {
270
+ key: 'retry',
271
+ style: { ...btnStyle, marginTop: 4, padding: '2px 10px', fontSize: 12, borderColor: 'rgba(220,60,60,0.5)' },
272
+ disabled: busy,
273
+ onClick: () => onRetry(p),
274
+ }, '人工重试 AI 适配')
275
+ : null,
276
+ ])
277
+ : null,
257
278
  op
258
279
  ? h('div', { key: 'op', style: { fontSize: 12, fontWeight: 600, marginTop: 4, color: op.ok ? '#2ea043' : '#dc3c3c' } }, op.text)
259
280
  : null,
@@ -353,6 +374,10 @@ window.__ModuleLoader__.load({
353
374
  act(pp.enabled ? 'disable' : 'enable', pp)
354
375
  },
355
376
  onSaveNote: (pp, note) => act('note', pp, { note }),
377
+ onRetry: (pp) => {
378
+ setOp(pp.name, true, '🤖 已重新开始 AI 适配…')
379
+ act('adapt-retry', pp)
380
+ },
356
381
  }),
357
382
  ))
358
383
  : h('div', { key: 'empty', style: { opacity: 0.6, padding: '8px 0' } }, '补丁库为空——改了插件代码后跑 extract 入库。'),
package/index.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * POST {action, name} → adapt / extract / revert / enable / disable / note
14
14
  */
15
15
  import { spawnSync } from 'node:child_process'
16
+ import fsSync from 'node:fs'
16
17
  import path from 'node:path'
17
18
  import { fileURLToPath } from 'node:url'
18
19
 
@@ -20,9 +21,11 @@ export const name = 'dsh-patchkeeper'
20
21
  // 本进程(≈冻结快照)时刻:快照之后挂载的补丁要下次启动才进运行代码
21
22
  const BOOT_TS = Date.now()
22
23
  // cordis 规矩:访问 ctx 上的服务必须先在这里声明;声明后服务不可用时仍为 null(参照 dsh-meme 同款写法)
23
- export const inject = ['webServer']
24
+ export const inject = ['webServer', 'llm']
24
25
 
25
26
  const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'cli.mjs')
27
+ const DATA_DIR = process.env.DSH_PATCHKEEPER_HOME || path.join(process.env.HOME || '~', '.dsh', 'patch-manager')
28
+ const STATE_FILE_PATH = path.join(DATA_DIR, 'state.json')
26
29
  const ROUTE = '/dsh-patchkeeper-api'
27
30
 
28
31
  function runCli(logger, args, timeoutMs = 180_000) {
@@ -65,6 +68,91 @@ function applyPatches(logger) {
65
68
  for (const r of bad) {
66
69
  logger.warn(`补丁未打上: ${r.name} [${r.status}](补丁版本 ${r.patchVersion} / 已装 ${r.installedVersion ?? '无'})`)
67
70
  }
71
+ return out.results
72
+ }
73
+
74
+ // ---- AI 适配管线:版本失配 → 机械合 → 冲突交 AI → 成功则下次重启自动挂载;失败记录不再重试 ----
75
+
76
+ function readState() {
77
+ try {
78
+ return JSON.parse(fsSync.readFileSync(STATE_FILE_PATH, 'utf8'))
79
+ } catch {
80
+ return {}
81
+ }
82
+ }
83
+
84
+ async function callAiForPatch(ctx, contextPack) {
85
+ const filesText = Object.entries(contextPack.files)
86
+ .map(([f, info]) => `### 文件 ${f}\n没打进去的 hunk(旧版语境):\n\`\`\`\n${info.rej}\n\`\`\`\n该文件的**新版**内容:\n\`\`\`\n${info_truncate(f, info.newContent)}\n\`\`\``)
87
+ .join('\n\n')
88
+ const prompt = `你是补丁适配器。插件 ${contextPack.name} 从 ${contextPack.fromVersion} 升级到 ${contextPack.toVersion},旧补丁有几个文件打不进新代码了。
89
+
90
+ 下面按文件给出:没打进去的 hunk(旧版语境)+ 该文件的新版内容。请为每个文件输出能直接打进新版本的 unified diff(路径前缀 a/ b/,patch -p1 可用,diff 头格式:diff -ruN a/<路径> b/<路径>)。只输出补丁本体,不要任何解释。
91
+
92
+ ${filesText}`
93
+ const call = await ctx.llm.prepareCall({ maxTokens: 8192 })
94
+ let text = ''
95
+ const stream = call.stream({
96
+ ...call.config,
97
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
98
+ sessionId: 'patchkeeper-adapt',
99
+ purpose: 'patch-adapt',
100
+ })
101
+ for await (const chunk of stream) {
102
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
103
+ }
104
+ return text
105
+ }
106
+
107
+ function info_truncate(f, content) {
108
+ if (content == null) return '(该文件在新版中不存在)'
109
+ const MAX = 40000
110
+ return content.length > MAX ? content.slice(0, MAX) + '\n…(文件过大已截断)' : content
111
+ }
112
+
113
+ // 从 AI 回复里抠出补丁本体(容错 markdown 围栏)
114
+ function extractPatch(text) {
115
+ const fence = /```(?:diff|patch)?\s*\n([\s\S]*?)```/.exec(text)
116
+ let body = fence ? fence[1] : text
117
+ const start = body.search(/^(diff ---|--- a\/)/m)
118
+ return start >= 0 ? body.slice(start) : null
119
+ }
120
+
121
+ async function adaptPipeline(ctx, logger, results) {
122
+ const mismatched = results.filter((r) => r.status === 'version-mismatch' && r.enabled !== false)
123
+ if (!mismatched.length) return
124
+ const state = readState()
125
+ const records = state.adapt || {}
126
+ for (const r of mismatched) {
127
+ const key = `${r.name}@${r.installedVersion}`
128
+ if (records[key]) continue // 适配过(成功或失败)都不重复,失败留人工
129
+ logger.info(`检测到版本失配:${r.name} 补丁${r.patchVersion} ≠ 已装${r.installedVersion},启动 AI 适配…`)
130
+ records[key] = { outcome: 'running', at: new Date().toISOString() }
131
+ fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...state, adapt: records }, null, 2))
132
+ try {
133
+ const auto = runCli(logger, ['adapt-auto', '--pkg', r.name, '--to', r.installedVersion])
134
+ if (auto?.outcome === 'auto-merged') {
135
+ records[key] = { outcome: 'adapted', mode: 'auto', at: new Date().toISOString() }
136
+ logger.info(`${r.name} 补丁机械适配成功(${r.patchVersion} → ${r.installedVersion}),重启后自动挂载`)
137
+ } else if (auto?.outcome === 'needs-ai') {
138
+ const contextPack = JSON.parse(fsSync.readFileSync(path.join(auto.contextDir, 'context.json'), 'utf8'))
139
+ const aiText = await callAiForPatch(ctx, contextPack)
140
+ const patchText = extractPatch(aiText)
141
+ if (!patchText) throw new Error('AI 回复里没有可用的补丁')
142
+ fsSync.writeFileSync(path.join(auto.contextDir, 'ai.patch'), patchText)
143
+ const applied = runCli(logger, ['adapt-apply', '--pkg', r.name, '--to', r.installedVersion])
144
+ if (applied?.outcome !== 'adapted') throw new Error(`AI 补丁验证失败: ${applied?.outcome || 'unknown'} ${applied?.error || ''}`)
145
+ records[key] = { outcome: 'adapted', mode: 'ai', at: new Date().toISOString() }
146
+ logger.info(`${r.name} 补丁 AI 适配成功(${r.patchVersion} → ${r.installedVersion}),重启后自动挂载`)
147
+ } else {
148
+ throw new Error(`机械合并未启动: ${auto?.outcome || 'unknown'} ${auto?.error || ''}`)
149
+ }
150
+ } catch (err) {
151
+ records[key] = { outcome: 'ai-failed', at: new Date().toISOString(), error: String(err?.message || err).slice(0, 500) }
152
+ logger.warn(`${r.name} AI 适配失败:${err?.message || err}——已记录,不再自动重试,请人工适配`)
153
+ }
154
+ fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...readState(), adapt: records }, null, 2))
155
+ }
68
156
  }
69
157
 
70
158
  // 挂载变更后尝试借插件管理器的机器即时生效:
@@ -141,6 +229,18 @@ function registerApi(ctx, logger) {
141
229
  else if (action === 'enable') out = runCli(logger, ['enable', '--pkg', pkgName])
142
230
  else if (action === 'disable') out = runCli(logger, ['disable', '--pkg', pkgName])
143
231
  else if (action === 'note') out = runCli(logger, ['note', '--pkg', pkgName, String(payload.note ?? '')])
232
+ else if (action === 'adapt-retry') {
233
+ // 人工点重试:清掉该版本的适配记录并重跑管线
234
+ const cur = runCli(logger, ['status', '--pkg', pkgName])
235
+ const row = cur?.results?.[0]
236
+ if (!row) return sendJson(res, 404, { error: 'patch not found' })
237
+ const st = readState()
238
+ const adapt = { ...(st.adapt || {}) }
239
+ delete adapt[`${pkgName}@${row.installedVersion}`]
240
+ fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...st, adapt }, null, 2))
241
+ void adaptPipeline(ctx, logger, [row]).catch(() => {})
242
+ out = { command: 'adapt-retry', name: pkgName, started: true }
243
+ }
144
244
  else return sendJson(res, 400, { error: 'unknown action' })
145
245
  if (!out) return sendJson(res, 500, { error: 'cli failed' })
146
246
  // 挂载类操作成功后,借插件管理器的 HMR 机器尝试即时生效
@@ -166,7 +266,11 @@ export function apply(ctx, config = {}) {
166
266
  const logger = ctx.logger('patchkeeper')
167
267
 
168
268
  // 启动:保底清除 + 版本匹配补挂。挂载是常驻的——本进程的冻结快照已在用它们。
169
- applyPatches(logger)
269
+ const results = applyPatches(logger)
270
+ // 版本失配的补丁:后台 AI 适配(不阻塞启动)
271
+ if (results?.some((r) => r.status === 'version-mismatch' && r.enabled !== false)) {
272
+ void adaptPipeline(ctx, logger, results).catch((err) => logger.warn(`AI 适配管线异常: ${err?.message || err}`))
273
+ }
170
274
 
171
275
  // UI 通道
172
276
  registerApi(ctx, logger)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alequet/dsh-patchkeeper",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "description": "【补丁总开关:禁用我会让所有插件补丁静默失效!】本地补丁管家:影子副本热挂载,原版永远干净,官方升级后自动重打。Local patch keeper for DSH plugins — disabling me silently disables every patch.",
5
5
  "license": "MIT",
6
6
  "type": "module",