dsh-config-manager 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/lib/adapters/mcp.d.ts +6 -1
  2. package/lib/adapters/mcp.js +22 -4
  3. package/lib/adapters/test-helpers.d.ts +7 -0
  4. package/lib/adapters/test-helpers.js +11 -0
  5. package/lib/cli/actions.js +1 -1
  6. package/lib/client.d.ts +9 -2
  7. package/lib/client.js +683 -647
  8. package/lib/core/backup.d.ts +9 -1
  9. package/lib/core/backup.js +21 -0
  10. package/lib/core/messages-core.d.ts +3 -0
  11. package/lib/core/messages-core.js +6 -0
  12. package/lib/core/messages.d.ts +7 -0
  13. package/lib/core/messages.js +14 -0
  14. package/lib/core/model-tools.js +2 -0
  15. package/lib/core/patch-document.d.ts +65 -0
  16. package/lib/core/patch-document.js +161 -0
  17. package/lib/core/phase4-crash-child.js +1 -1
  18. package/lib/core/plugin-cli.d.ts +11 -0
  19. package/lib/core/plugin-cli.js +30 -0
  20. package/lib/core/restore-wal.d.ts +2 -0
  21. package/lib/core/restore-wal.js +11 -6
  22. package/lib/core/restore.d.ts +15 -2
  23. package/lib/core/restore.js +65 -3
  24. package/lib/core/snapshot-diff.js +2 -1
  25. package/lib/core/types.d.ts +32 -0
  26. package/lib/index.d.ts +8 -1
  27. package/lib/index.js +51 -68
  28. package/lib/routes/route-support.d.ts +5 -0
  29. package/lib/routes/route-support.js +28 -2
  30. package/lib/routes/sync.js +3 -0
  31. package/lib/sync/merge-preview-view.d.ts +78 -0
  32. package/lib/sync/merge-preview-view.js +46 -0
  33. package/lib/sync/merge.d.ts +2 -1
  34. package/lib/sync/merge.js +9 -4
  35. package/lib/sync/plugin-removal-apply.d.ts +95 -0
  36. package/lib/sync/plugin-removal-apply.js +158 -0
  37. package/lib/sync/plugin-removals.d.ts +90 -0
  38. package/lib/sync/plugin-removals.js +167 -0
  39. package/lib/sync/sync-engine.d.ts +34 -43
  40. package/lib/sync/sync-engine.js +50 -42
  41. package/lib/sync/sync-selection.d.ts +8 -0
  42. package/lib/sync/sync-selection.js +6 -0
  43. package/lib/sync/workspace-merge.d.ts +8 -1
  44. package/lib/ui/restore-plan-view.js +1 -0
  45. package/lib/ui/sync-settings-view.d.ts +10 -0
  46. package/lib/ui/sync-settings-view.js +2 -0
  47. package/package.json +1 -1
  48. package/src/adapters/mcp.test.ts +23 -3
  49. package/src/adapters/mcp.ts +24 -4
  50. package/src/adapters/test-helpers.ts +10 -0
  51. package/src/cli/actions.ts +1 -1
  52. package/src/client/common/info-hint-guard.test.ts +2 -1
  53. package/src/client/run-store.test.ts +7 -5
  54. package/src/client/run-store.ts +4 -5
  55. package/src/client/sync/SyncPanel.tsx +10 -0
  56. package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
  57. package/src/client/sync/sync-locales.ts +4 -0
  58. package/src/client/sync/sync-view.ts +6 -0
  59. package/src/core/backup.ts +21 -1
  60. package/src/core/messages-core.ts +6 -0
  61. package/src/core/messages.ts +14 -0
  62. package/src/core/model-tools.ts +2 -0
  63. package/src/core/patch-document.test.ts +107 -0
  64. package/src/core/patch-document.ts +194 -0
  65. package/src/core/phase4-crash-child.ts +1 -1
  66. package/src/core/plugin-cli.ts +37 -0
  67. package/src/core/restore-plugin-install.test.ts +116 -0
  68. package/src/core/restore-wal.ts +12 -6
  69. package/src/core/restore.ts +79 -4
  70. package/src/core/smoke.test.ts +5 -0
  71. package/src/core/snapshot-diff.test.ts +1 -1
  72. package/src/core/snapshot-diff.ts +2 -1
  73. package/src/core/types.ts +31 -0
  74. package/src/index.facade.test.ts +83 -1
  75. package/src/index.ts +57 -67
  76. package/src/routes/route-support.ts +27 -2
  77. package/src/routes/sync.ts +3 -0
  78. package/src/security/security.test.ts +1 -0
  79. package/src/sync/merge-preview-view.ts +97 -0
  80. package/src/sync/merge.test.ts +17 -15
  81. package/src/sync/merge.ts +10 -3
  82. package/src/sync/plugin-removal-apply.ts +198 -0
  83. package/src/sync/plugin-removals.test.ts +221 -0
  84. package/src/sync/plugin-removals.ts +208 -0
  85. package/src/sync/sync-engine.test.ts +251 -1
  86. package/src/sync/sync-engine.ts +84 -83
  87. package/src/sync/sync-selection.test.ts +29 -7
  88. package/src/sync/sync-selection.ts +13 -0
  89. package/src/sync/workspace-merge.ts +9 -0
  90. package/src/ui/restore-plan-view.test.ts +1 -1
  91. package/src/ui/restore-plan-view.ts +1 -0
  92. package/src/ui/snapshots-view.test.ts +1 -1
  93. package/src/ui/sync-settings-view.test.ts +20 -0
  94. package/src/ui/sync-settings-view.ts +12 -0
  95. package/src/utils/patch-yaml.test.ts +1 -1
package/src/index.ts CHANGED
@@ -92,11 +92,12 @@ import { ROLLBACK_ACTIVITY_FILE_NAME, RollbackSessionActivity } from './core/rol
92
92
  import { isRollbackEnabled, onRollbackEnabledChange, setRollbackEnabled } from './core/rollback-gate.ts'
93
93
  // t3:宿主斜杠命令 /rollback(与 HTTP 路由同一道写入门;命令服务惰取,未组合时安静跳过)。
94
94
  import { agentSessionFactsOf, registerRollbackCommand, type CommandServiceLike, type RollbackCommandHost } from './core/command-rollback.ts'
95
- import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
95
+ import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, uninstallViaCli, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
96
96
  import { ImportUserSkippedError, type ConfigAdapter, type CredentialsFacade, type ExportUnit, type FileSystemFacade, type HostContext, type ImportDecisions, type ImportPlan, type NamedNamespaceInfo, type NamespaceInfo, type PatchFileFacade, type PluginInfo, type PluginsFacade, type Portability, type SecretScanner, type SessionFormatDisposition, type SessionMoveResult, type SessionParentRelation, type SessionRewriteResult, type SessionStoreFacade, type SettingsFacade, type SkillDefinitionView, type SkillStoreFacade, type SkillSummaryView, type WorkspaceFacade } from './core/types.ts'
97
97
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.ts'
98
98
  import { planSelfUpdate, runSelfUpdate, type SelfUpdateOutcome } from './core/self-update.ts'
99
99
  import { createAdapters } from './adapters/index.ts'
100
+ import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, promotedTopLevelIds } from './core/patch-document.ts'
100
101
  import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.ts'
101
102
  import { createLocalPluginPackHook } from './core/local-plugin-host.ts'
102
103
  import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.ts'
@@ -183,7 +184,7 @@ export const name = 'config-manager'
183
184
  export const inject = ['settings', 'credentials']
184
185
 
185
186
  /** Plugin version, kept in sync with package.json ("version"). */
186
- export const PLUGIN_VERSION = '0.7.0'
187
+ export const PLUGIN_VERSION = '0.8.1'
187
188
 
188
189
  /** Plugin own package name — excluded from its own exported plugins list. */
189
190
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -597,6 +598,11 @@ export class DshPluginsFacade implements PluginsFacade {
597
598
  // 回读实际落盘版本:调用方据此校验升级是否真的生效(issue #101),而不是只看子进程退出码。
598
599
  return { needsRestart: true, installedVersion: readInstalledVersion(profileDir, pkg) }
599
600
  }
601
+
602
+ /** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
603
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{ needsRestart: boolean }> {
604
+ return uninstallViaCli(this.homeDir, this.profile, pkg, this.runner, signal)
605
+ }
600
606
  }
601
607
 
602
608
  /** Workspace facade over the real ctx.workspaceRegistry. */
@@ -1709,15 +1715,13 @@ export class DshPatchFileFacade implements PatchFileFacade {
1709
1715
  ): Promise<void> {
1710
1716
  const p = this.patchPath(file)
1711
1717
 
1712
- // 1. Load the current document into an ordered lineId → raw table.
1718
+ // 1. Load the current document (the ordered table itself is built by planPatchDocument).
1713
1719
  //
1714
1720
  // 读不出来的既有内容**绝不能当作空文档**(issue #75 的数据丢失点):重建后的文件只包含
1715
1721
  // 本次写入的行,等于把用户手写的其余行整段删掉。三种情况分开处理:
1716
1722
  // - 真不存在(ENOENT)→ 空文档(首次创建,既有语义);
1717
1723
  // - 存在但读不到(EACCES/EBUSY/…)→ 抛错,不改写;
1718
1724
  // - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
1719
- const rows = new Map<string, unknown>()
1720
- const order: string[] = []
1721
1725
  let existing: string | null = null
1722
1726
  try {
1723
1727
  existing = await fs.readFile(p, 'utf8')
@@ -1734,55 +1738,46 @@ export class DshPatchFileFacade implements PatchFileFacade {
1734
1738
  throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err })
1735
1739
  }
1736
1740
  }
1737
- if (Array.isArray(doc)) {
1738
- for (const item of doc) {
1739
- if (item === null || typeof item !== 'object') continue
1740
- const obj = item as Record<string, unknown>
1741
- const insert = obj['insert']
1742
- if (Array.isArray(insert)) {
1743
- for (const entry of insert) {
1744
- if (entry === null || typeof entry !== 'object') continue
1745
- const id = (entry as Record<string, unknown>)['id']
1746
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1747
- rows.set(id, entry)
1748
- order.push(id)
1749
- }
1750
- }
1751
- continue
1752
- }
1753
- const id = obj['id']
1754
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1755
- rows.set(id, obj)
1756
- order.push(id)
1757
- }
1758
- }
1759
- }
1760
1741
 
1761
- // 2. Apply the changes.
1762
- for (const change of changes) {
1763
- if (change.action === 'remove') {
1764
- if (rows.delete(change.lineId)) {
1765
- const at = order.indexOf(change.lineId)
1766
- if (at >= 0) order.splice(at, 1)
1767
- }
1768
- } else if (change.action === 'insert' || change.action === 'update') {
1769
- if (!rows.has(change.lineId)) order.push(change.lineId)
1770
- rows.set(change.lineId, change.raw)
1771
- }
1742
+ // 2. Rebuild through core/patch-document.ts (issue #133): the two shapes are **not**
1743
+ // equivalent on the host side. A top-level `- id: X` row *overrides* entry X and is
1744
+ // dropped with `patch: entry "X" not found` when X does not exist; only an
1745
+ // `- insert:` block member *adds* entries. Emitting every row top-level therefore
1746
+ // turned one update into "every insert-only entry (MCP servers, most notably) is
1747
+ // gone after restart".
1748
+ const plan = planPatchDocument(doc, changes)
1749
+ const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1750
+ + dumpPatchDocument(plan.items)
1751
+
1752
+ // 3. Post-write structure self-check, before anything touches the disk: re-parse the
1753
+ // text we just serialized and require both id sets to match the plan item by item.
1754
+ // A serializer or dialect change that flattens or swallows insert blocks stops here
1755
+ // (zero write) instead of silently degrading every patch row to an override.
1756
+ const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)))
1757
+ if (drift !== null) {
1758
+ throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }))
1772
1759
  }
1773
1760
 
1774
- // 3. Rebuild: every id row is emitted as a top-level row. The loader treats
1775
- // a top-level { id, name } row exactly like an `- insert:` block member
1776
- // (dsh-base patch precedent), so the document stays semantically equal.
1777
- const out: unknown[] = []
1778
- for (const id of order) {
1779
- const raw = rows.get(id)
1780
- if (raw !== undefined) out.push(raw)
1761
+ // 4. 跨层提升守卫(issue #133):待写的顶层 id 若是**另一层**的 insert 成员,写下去就从
1762
+ // 「新增」变成「覆盖」(宿主查不到则丢弃)。对侧读不出来/解析不了只跳过守卫 —— 读护栏
1763
+ // 已在各自层报错,损坏的兄弟文件不该永久阻塞本层写入。
1764
+ const other = file === USER_PATCH_FILE ? profilePatchRel(this.profile) : USER_PATCH_FILE
1765
+ const promoted = promotedTopLevelIds(await this.readPatchDocQuietly(other), plan.topLevelIds)
1766
+ if (promoted.length > 0) {
1767
+ throw new Error(this.msg('host.patchRefusePromote', { file, ids: promoted.join(', ') }))
1781
1768
  }
1782
- const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1783
- + dumpPatchDocument(out)
1769
+
1784
1770
  await atomicWriteFile(p, text)
1785
1771
  }
1772
+
1773
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
1774
+ private async readPatchDocQuietly(file: string): Promise<unknown> {
1775
+ try {
1776
+ return loadPatchDocument(await fs.readFile(resolve(this.homeDir, file), 'utf8'))
1777
+ } catch {
1778
+ return undefined
1779
+ }
1780
+ }
1786
1781
  }
1787
1782
 
1788
1783
  /** File facade over $DSH_HOME, confined to the home root. */
@@ -2240,7 +2235,7 @@ export interface PluginDiagnostics {
2240
2235
  bundles: string[]
2241
2236
  }
2242
2237
 
2243
- type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean }
2238
+ type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean; deletePlugins: boolean }
2244
2239
 
2245
2240
 
2246
2241
  /**
@@ -2641,21 +2636,17 @@ function makeRoutes(deps: RoutesDeps): {
2641
2636
 
2642
2637
  /** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
2643
2638
  /** 指定通道的分区选择视图。 */
2644
- const selectionView = async (channel: SyncTransportType): Promise<SelectionView> => {
2645
- const sel = await ensureSelectionLoaded(channel)
2646
- return { mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets }
2647
- }
2639
+ /** SyncSelection → SelectionView(字段白名单;密码值永不进视图)。 */
2640
+ const toSelectionView = (sel: SyncSelection): SelectionView =>
2641
+ ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets, deletePlugins: sel.deletePlugins })
2642
+
2643
+ const selectionView = async (channel: SyncTransportType): Promise<SelectionView> => toSelectionView(await ensureSelectionLoaded(channel))
2648
2644
 
2649
2645
  const selectionViewByChannel = async (): Promise<Record<SyncTransportType, SelectionView>> => {
2650
2646
  const all = await readAllSyncSelections(syncDir)
2651
- const view = (sel: SyncSelection): SelectionView =>
2652
- ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets })
2653
2647
  // 通道集合来自唯一枚举(SYNC_CHANNELS);不得穷举字面量(漏一处即该通道状态静默缺失)
2654
2648
  const out = {} as Record<SyncTransportType, SelectionView>
2655
- for (const channel of SYNC_CHANNELS) {
2656
- selectionCache[channel] = all[channel]
2657
- out[channel] = view(all[channel])
2658
- }
2649
+ for (const channel of SYNC_CHANNELS) { selectionCache[channel] = all[channel]; out[channel] = toSelectionView(all[channel]) }
2659
2650
  return out
2660
2651
  }
2661
2652
 
@@ -2757,7 +2748,8 @@ function makeRoutes(deps: RoutesDeps): {
2757
2748
  transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir)
2758
2749
  }
2759
2750
  const channel: SyncTransportType = channelOf(cfg)
2760
- const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection())
2751
+ const selection = selectionCache[channel] ?? defaultSyncSelection()
2752
+ const sections = effectiveSections(selection)
2761
2753
  return new SyncEngine({
2762
2754
  ctx: host,
2763
2755
  transport,
@@ -2768,11 +2760,10 @@ function makeRoutes(deps: RoutesDeps): {
2768
2760
  zipDir: tmpDir,
2769
2761
  msg,
2770
2762
  ...(sections === undefined ? {} : { sections }),
2771
- ...(engineOpts.optInSections === undefined || engineOpts.optInSections.length === 0
2772
- ? {}
2773
- : { optInSections: engineOpts.optInSections }),
2774
- // m-retention:远端快照裁剪与本地备份产物共用同一份 GFS 保留策略(缺省 = 最近 10 个,
2775
- // 与改造前逐字等价);用户改完策略即时生效(每次 prune 都重读)。
2763
+ // issue #132:开关开 = 授权(手动/自动同判据);self 守卫防同步把自己删掉
2764
+ deletePlugins: selection.deletePlugins, selfPluginName: PLUGIN_NPM_PACKAGE,
2765
+ ...(engineOpts.optInSections?.length ? { optInSections: engineOpts.optInSections } : {}),
2766
+ // m-retention:远端裁剪与本地备份共用 GFS 策略(缺省最近 10 个,每次 prune 重读 ⇒ 改完即时生效)。
2776
2767
  retentionPolicy: () => retentionPolicyProvider(),
2777
2768
  })
2778
2769
  }
@@ -3795,8 +3786,7 @@ export function apply(ctx: Context, config?: Config): void {
3795
3786
  namespaces: async () => (await ctx.settings.describe({ redactSecrets: true })).map((d) => String(d.ns)),
3796
3787
  // Sessions 分区默认关(含敏感内容):挂载 adapter 供 Custom Export 显式勾选(§3.3/§15)。
3797
3788
  includeSessions: true,
3798
- // 导出 plugins 分区时不列本插件自身,避免备份中的自引用条目。
3799
- selfPluginName: PLUGIN_NAME,
3789
+ selfPluginName: PLUGIN_NAME, // 导出 plugins 分区时不列本插件自身,避免备份里的自引用条目
3800
3790
  // pluginFiles 扩展:额外白名单文件 + 约定配置目录(都相对 ~/.dsh 根),支持导出更多插件配置。
3801
3791
  pluginFiles: config?.pluginFiles,
3802
3792
  pluginFilesDir: config?.pluginFilesDir,
@@ -32,7 +32,7 @@ import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
32
32
  import { engineMsg } from '../core/engine-locale.ts'
33
33
  import { createPreRestoreAttemptDir } from '../core/restore.ts'
34
34
  import type { RestoreActionKind, RestorePlan, RestoreReport } from '../core/restore.ts'
35
- import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
35
+ import { collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
36
36
  import type { RestoreResumeHint } from '../core/restore-resume.ts'
37
37
  import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
38
38
  import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts'
@@ -554,6 +554,8 @@ export interface RestoreExecutor {
554
554
  removeHome(relPath: string): Promise<void>
555
555
  /** 卸载插件(官方通道);失败返回 { ok:false, message } */
556
556
  uninstallPlugin(name: string): Promise<{ ok: boolean; message?: string }>
557
+ /** 装回跟远端删掉的插件(官方通道,issue 132 的反向);失败返回 { ok:false, message } */
558
+ installPlugin(name: string, target: string): Promise<{ ok: boolean; message?: string }>
557
559
  /**
558
560
  * home 相对路径 → 磁盘绝对路径(逐动作 WAL 用:journal 的 ref 必须是绝对路径,
559
561
  * reconcile 的 verifyStepFingerprint 直接拿它读盘算指纹)。缺省 = 不登记 WAL。
@@ -578,6 +580,7 @@ export async function executeRestorePlan(
578
580
  snapshotId: plan.snapshotId,
579
581
  restored: [],
580
582
  removedPlugins: [],
583
+ installedPlugins: [],
581
584
  manualHints: [],
582
585
  failed: [],
583
586
  skipped: [],
@@ -589,7 +592,7 @@ export async function executeRestorePlan(
589
592
  const walByAction = new Map<(typeof plan.actions)[number], RestoreWalHandle | undefined>()
590
593
  const resume = resumeHint
591
594
  const absOf = (action: (typeof plan.actions)[number]): string | null =>
592
- action.kind === 'pluginRemove' || action.target === undefined || exec.absPath === undefined
595
+ isExternalPluginKind(action.kind) || action.target === undefined || exec.absPath === undefined
593
596
  ? null
594
597
  : exec.absPath(action.target)
595
598
  if (wal !== null && exec.absPath !== undefined) {
@@ -656,6 +659,21 @@ export async function executeRestorePlan(
656
659
  }
657
660
  break
658
661
  }
662
+ case 'pluginInstall': {
663
+ const name = action.pluginName
664
+ const target = action.pluginTarget ?? name
665
+ if (name === undefined || target === undefined) throw new Error(engineMsg('restore.missingPluginName'))
666
+ const result = await exec.installPlugin(name, target)
667
+ if (result.ok) {
668
+ report.installedPlugins.push(target)
669
+ } else {
670
+ const reason = result.message ?? engineMsg('restore.pluginInstallFailed')
671
+ report.failed.push({ item: `plugin:${name}`, reason })
672
+ settleStatus = 'attention'
673
+ settleMessage = reason
674
+ }
675
+ break
676
+ }
659
677
  case 'credentialHint':
660
678
  report.manualHints.push(action.manualHint ?? action.description)
661
679
  break
@@ -720,6 +738,13 @@ export function makeRestoreExecutor(snapshotDir: string, host: HostContext, prof
720
738
  const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
721
739
  return { ok: false, message: msgOf(host)('host.restoreUninstallFailed', { name, code: String(result.exitCode), tail }) }
722
740
  },
741
+ installPlugin: async (name, target) => {
742
+ const result = await runDshPlugin(profileDir, profile, ['add', target])
743
+ if (result.exitCode === 0) return { ok: true }
744
+ const output = `${result.stderr}\n${result.stdout}`.trim()
745
+ const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
746
+ return { ok: false, message: engineMsg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) }
747
+ },
723
748
  }
724
749
  }
725
750
 
@@ -1220,6 +1220,9 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
1220
1220
  encrypt: body['encrypt'] === true,
1221
1221
  // 安全兜底:includeSecrets 必须同时 encrypt(密钥绝不明文进同步通道)
1222
1222
  includeSecrets: body['includeSecrets'] === true && body['encrypt'] === true,
1223
+ // issue #132:跟随远端删除插件。缺省关;请求体非 true 一律按关处理
1224
+ // (重新保存表单时收起开关 = 明确关掉,不留上一次的 true)
1225
+ deletePlugins: body['deletePlugins'] === true,
1223
1226
  }
1224
1227
  // 加密/解密密码持久化(用户要求:勾选即记住,取消勾选或主动删除才清)。
1225
1228
  // 值只写进 DSH credentials(绝不进 sync-selection.json / 日志 / 响应);
@@ -200,6 +200,7 @@ class MemCredentials implements CredentialsFacade {
200
200
  class MemPlugins implements PluginsFacade {
201
201
  async listInstalled() { return []; }
202
202
  async install(_pkg: string, _spec?: string) { return { needsRestart: true }; }
203
+ async uninstall(_pkg: string) { return { needsRestart: true }; }
203
204
  }
204
205
 
205
206
  class MemWorkspace implements WorkspaceFacade {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 合并预览的**可渲染视图**(分区结果 → 界面结构),与「预览产物能否与基线比对」的判定。
3
+ *
4
+ * 为什么独立成文件:sync-engine 已顶到文件体量棘轮(tests/file-size-ratchet.test.ts),
5
+ * 而这两件事都只依赖 merge.ts 的结果类型与预览文本工具,不碰引擎实例状态;放这里可单测,
6
+ * 也让引擎只管编排。类型经 sync-engine 再导出,既有导入方(model-tools 等)无需改动。
7
+ */
8
+ import { isLocalPluginSpec } from '../core/local-plugin-pack.ts';
9
+ import type { SectionData, SectionId } from '../schema/types.ts';
10
+ import type { MergeConflictReason, MergeSectionResult } from './merge.ts';
11
+ import { previewTextOf } from './merge-preview-text.ts';
12
+
13
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
14
+ export function mergePreviewSectionView(result: MergeSectionResult): MergePreviewSectionView {
15
+ const conflicts: MergePreviewConflictView[] = result.conflicts.map((c) => ({
16
+ path: c.path,
17
+ kind: c.kind,
18
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
19
+ localPreview: previewTextOf(c.local),
20
+ remotePreview: previewTextOf(c.remote),
21
+ ancestorPreview: previewTextOf(c.ancestor),
22
+ }));
23
+ return {
24
+ id: result.id,
25
+ decision: result.decision,
26
+ ...(result.autoMerged !== undefined ? { autoMerged: result.autoMerged } : {}),
27
+ conflictCount: result.conflicts.length,
28
+ conflicts,
29
+ };
30
+ }
31
+
32
+ /**
33
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
34
+ *
35
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
36
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
37
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
38
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
39
+ * (那正是本 issue 的缺陷本身)。
40
+ *
41
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
42
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
43
+ */
44
+ export function previewCaliberDiffersFromExport(sectionId: SectionId, data: SectionData): boolean {
45
+ if (sectionId !== 'plugins') return false;
46
+ const plugins = (data as { plugins?: { spec?: string }[] }).plugins;
47
+ return Array.isArray(plugins) && plugins.some((p) => isLocalPluginSpec(p?.spec));
48
+ }
49
+
50
+ /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
51
+ export interface MergePreviewConflictView {
52
+ /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
53
+ path: string;
54
+ kind: 'key' | 'file';
55
+ /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
56
+ reason?: MergeConflictReason;
57
+ /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
58
+ localPreview: string;
59
+ /** 远端侧的可读预览(同上)。 */
60
+ remotePreview: string;
61
+ /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
62
+ ancestorPreview: string;
63
+ }
64
+
65
+ /** previewMerge 的单个分区视图。 */
66
+ export interface MergePreviewSectionView {
67
+ id: SectionId;
68
+ decision: MergeSectionResult['decision'];
69
+ /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
70
+ autoMerged?: number;
71
+ conflictCount: number;
72
+ conflicts: MergePreviewConflictView[];
73
+ }
74
+
75
+ /** previewMerge 结果(只读、零写入)。 */
76
+ export interface MergePreview {
77
+ /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
78
+ ok: boolean;
79
+ /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
80
+ snapshotId: string;
81
+ /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
82
+ hasAncestor: boolean;
83
+ sections: MergePreviewSectionView[];
84
+ /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
85
+ summary: { auto: number; review: number; conflicts: number; skipped: number };
86
+ message?: string;
87
+ reason?: 'remote-empty'; // 远端没有任何快照:首次同步的正常起点,不是故障(客户端据此给「先推送」引导,issue 116)
88
+ /**
89
+ * 本轮合并**将卸载**的插件(issue #132):确认页必须单列出来,用户据此可以整轮取消。
90
+ * 仅在 plugins 分区可应用(useRemote/keepLocal/merge)时才有条目 —— 分区冲突时不删。
91
+ */
92
+ pluginRemovals?: { name: string; version: string }[];
93
+ /** 远端删了、本机却改过 → 不删,等人工裁决(与 conflict 清单同语义,这里为插件专列) */
94
+ pluginRemovalConflicts?: { name: string; ancestorVersion: string; localVersion: string }[];
95
+ /** 考察过但没删的条目及原因(含开关关闭 = 'switch-off',界面据此如实说明) */
96
+ pluginRemovalSkipped?: { name: string; reason: string }[];
97
+ }
@@ -132,34 +132,36 @@ test('merge: 深层嵌套 JSON 合并(不同叶子自动合,未知字段两
132
132
  assert.equal(merged.ui['remoteOnly'], true, '远端新增的未知字段不得被静默丢弃');
133
133
  });
134
134
 
135
+ // 注意:这里**故意**用 settings 的普通数组做样本。plugins 自 issue #132 起有了按包名的专属
136
+ // 合并钩子(见 plugin-removals.test.ts),不再走通用「数组两侧各改即冲突」的口径。
135
137
  test('merge: 数组双侧都改且不同 → conflict(reason=array),不按索引猜', () => {
136
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
137
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
138
- const rem: SectionData = { version: 1, plugins: [{ spec: 'c' }] } as unknown as SectionData;
139
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
138
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
139
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
140
+ const rem: SectionData = { version: 1, list: [{ spec: 'c' }] } as unknown as SectionData;
141
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
140
142
  const r = plan.sections[0]!;
141
143
  assert.equal(r.decision, 'conflict');
142
- assert.equal(r.conflicts[0]!.path, 'plugins');
144
+ assert.equal(r.conflicts[0]!.path, 'list');
143
145
  assert.equal(r.conflicts[0]!.reason, 'array');
144
146
  });
145
147
 
146
148
  test('merge: 数组仅一侧改 → 采纳该侧(另一侧键的改动同时保住)', () => {
147
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
148
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
149
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
150
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
149
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
150
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
151
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
152
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
151
153
  const r = plan.sections[0]!;
152
154
  assert.equal(r.decision, 'merge');
153
- const merged = r.merged as unknown as { plugins: unknown[]; note: string };
154
- assert.equal(merged.plugins.length, 2);
155
+ const merged = r.merged as unknown as { list: unknown[]; note: string };
156
+ assert.equal(merged.list.length, 2);
155
157
  assert.equal(merged.note, 'y');
156
158
  });
157
159
 
158
160
  test('merge: 数组双侧改成相同结果 → 收敛为一份(不算冲突)', () => {
159
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
160
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
161
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
162
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
161
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
162
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
163
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
164
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
163
165
  assert.equal(plan.sections[0]!.decision, 'skip');
164
166
  });
165
167
 
package/src/sync/merge.ts CHANGED
@@ -32,8 +32,9 @@
32
32
  import type { FilesSection, SectionData, SectionId } from '../schema/types.ts';
33
33
  import { hashSection } from './sync-state.ts';
34
34
  import { mergeBytesThreeWay, mergeJsonValues, type TextMergeConflict } from './text-merge.ts';
35
+ import { mergePluginsSection } from './plugin-removals.ts';
35
36
  import { mergeWorkspacesSection } from './workspace-merge.ts';
36
- import type { GranularMerger } from './workspace-merge.ts';
37
+ import type { GranularMergeHooks, GranularMerger } from './workspace-merge.ts';
37
38
 
38
39
  /**
39
40
  * 分区级决胜结果(三方合并,2026-10 收口):
@@ -298,6 +299,10 @@ function mergeFilesSectionGranular(
298
299
  */
299
300
  const GRANULAR_MERGES: Partial<Record<SectionId, GranularMerger>> = {
300
301
  workspaces: mergeWorkspacesSection,
302
+ // plugins(issue #132):plugins 是**数组**,通用 JSON 合并对「两侧各自改过」一律判冲突 ——
303
+ // 本机装了 Y、远端删了 X 就会整分区冲突,X 永远删不掉、Y 也永远同步不出去。
304
+ // 钩子按包名做三方逐条判定(本地新增保留 / 远端删除跟随 / 版本冲突交人工)。
305
+ plugins: mergePluginsSection,
301
306
  };
302
307
 
303
308
  /** 单分区三方合并(决策链见文件头注释)。 */
@@ -307,6 +312,7 @@ function mergeSectionTriple(
307
312
  rData: SectionData | undefined,
308
313
  aData: SectionData | undefined,
309
314
  h: TripleHashes,
315
+ hooks: GranularMergeHooks,
310
316
  ): MergeSectionResult {
311
317
  // ⓪ 形状闸门(先于一切取舍):远端载荷来自不可信输入(解析层只保证整体是合法 JSON,
312
318
  // 不保证每个分区的值形状正确)。值形状不对时**绝不原样采用** —— 那等于把畸形数据
@@ -366,7 +372,7 @@ function mergeSectionTriple(
366
372
  // 没有祖先时也应并集(否则首轮同步就整分区冲突),字段取值分歧由钩子逐键如实报冲突。
367
373
  const granular = GRANULAR_MERGES[id];
368
374
  if (granular !== undefined) {
369
- const res = granular(local, remote, aData);
375
+ const res = granular(local, remote, aData, hooks);
370
376
  if (res !== undefined) {
371
377
  if (res.conflicts.length > 0) return { id, decision: 'conflict', conflicts: res.conflicts };
372
378
  const merged = res.merged;
@@ -433,6 +439,7 @@ export function merge(
433
439
  local: Partial<Record<SectionId, SectionData>>,
434
440
  remote: Partial<Record<SectionId, SectionData>>,
435
441
  ancestor?: Partial<Record<SectionId, SectionData>>,
442
+ hooks: GranularMergeHooks = {},
436
443
  ): MergePlan {
437
444
  const l = local as Record<string, SectionData>;
438
445
  const r = remote as Record<string, SectionData>;
@@ -441,7 +448,7 @@ export function merge(
441
448
  const hashes = computeHashes(l, r, a, ids);
442
449
  const results: MergeSectionResult[] = [];
443
450
  for (const id of ids) {
444
- results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id)!));
451
+ results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id)!, hooks));
445
452
  }
446
453
  return { sections: results };
447
454
  }