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
@@ -29,7 +29,7 @@ import { isPatchLayerRel } from './patch-layers.js';
29
29
  import { expectedSessionRefs, sweepGhostSessions } from './ghost-sweep.js';
30
30
  import { zhMsg } from './messages.js';
31
31
  import { classifyDshPluginFailure, readInstalled, readInstalledVersion, resolveProfileDir, runDshPlugin, } from './plugin-cli.js';
32
- import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps, } from './restore-wal.js';
32
+ import { collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps, } from './restore-wal.js';
33
33
  import { parseJsonSafe } from '../utils/json.js';
34
34
  import { isPathInside } from '../utils/paths.js';
35
35
  import { atomicCopyFile, atomicWriteFile } from '../utils/atomic-write.js';
@@ -265,6 +265,24 @@ async function defaultPluginUninstaller(name, profileDir, profile, msg) {
265
265
  const tail = output.split('\n').slice(-8).join('\n') || msg('restore.noOutput');
266
266
  return { ok: false, message: msg('restore.uninstallFailedExit', { name, code: String(result.exitCode), tail }) };
267
267
  }
268
+ /**
269
+ * 默认插件重装器(issue #132 undo):官方 dsh plugin add 通道 + 失败分类诊断。
270
+ *
271
+ * 与卸载器同口径:非 0 退出先归类(已知失败码给准确文案),否则回落到退出码 + 输出尾部。
272
+ * 绝不在这里做版本回退/猜测 —— target 就是快照里记下的 `name@version`。
273
+ */
274
+ async function defaultPluginInstaller(name, target, profileDir, profile, msg) {
275
+ const result = await runDshPlugin(profileDir, profile, ['add', target]);
276
+ if (result.exitCode === 0)
277
+ return { ok: true };
278
+ const output = `${result.stderr}\n${result.stdout}`.trim();
279
+ const failure = classifyDshPluginFailure(output);
280
+ if (failure !== null) {
281
+ return { ok: false, message: msg('restore.installFailedCode', { name, code: failure.code, message: failure.message }) };
282
+ }
283
+ const tail = output.split('\n').slice(-8).join('\n') || msg('restore.noOutput');
284
+ return { ok: false, message: msg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) };
285
+ }
268
286
  /** 递归检查快照目录内关键文件非 symlink(F25:拒绝 symlink 化 metadata/blob 写穿)。 */
269
287
  async function assertNoSnapshotSymlink(dir, rel) {
270
288
  const p = path.join(dir, rel);
@@ -496,6 +514,29 @@ export async function planRestore(opts) {
496
514
  });
497
515
  }
498
516
  }
517
+ // 2') 插件重装(issue #132 跟远端删插件的反向):只认快照里**明确记录过**的跟删项。
518
+ // 为什么不按 beforePlugins 反推「缺了就是被删了」:手动卸载/换包也会让基线里的名字消失,
519
+ // 那种情况下重装是替用户改主意。记录过的才装回;现在已存在的直接跳过。
520
+ const recordedRemovals = snapshot.pluginRemovals ?? [];
521
+ if (recordedRemovals.length > 0) {
522
+ const installed = readInstalled(profileDir);
523
+ for (const removal of recordedRemovals) {
524
+ if (Object.hasOwn(installed, removal.name)) {
525
+ actions.push({
526
+ kind: 'skip',
527
+ description: msg('restore.pluginInstallAlreadyPresent', { name: removal.name }),
528
+ });
529
+ continue;
530
+ }
531
+ actions.push({
532
+ kind: 'pluginInstall',
533
+ description: msg('restore.pluginInstall', { name: removal.name, version: removal.version }),
534
+ target: removal.name,
535
+ pluginName: removal.name,
536
+ pluginTarget: removal.target,
537
+ });
538
+ }
539
+ }
499
540
  // 3) file 类条目补偿 + credentials 提示(聚合计数供报告)
500
541
  let namespaceCount = 0;
501
542
  let patchLineCount = 0;
@@ -649,7 +690,7 @@ export async function planRestore(opts) {
649
690
  }
650
691
  function summarizeActions(actions) {
651
692
  const summary = {
652
- hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0,
693
+ hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0,
653
694
  fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0,
654
695
  };
655
696
  for (const a of actions) {
@@ -663,6 +704,9 @@ function summarizeActions(actions) {
663
704
  case 'pluginRemove':
664
705
  summary.pluginRemoves += 1;
665
706
  break;
707
+ case 'pluginInstall':
708
+ summary.pluginInstalls += 1;
709
+ break;
666
710
  case 'fileRestore':
667
711
  summary.fileRestores += 1;
668
712
  break;
@@ -693,10 +737,13 @@ export async function restore(opts) {
693
737
  const profileDir = resolveProfileDir(homeDir, profile);
694
738
  const uninstaller = opts.pluginUninstaller
695
739
  ?? ((name, dir, prof) => defaultPluginUninstaller(name, dir, prof, msg));
740
+ const installer = opts.pluginInstaller
741
+ ?? ((name, target, dir, prof) => defaultPluginInstaller(name, target, dir, prof, msg));
696
742
  const report = {
697
743
  snapshotId: plan.snapshotId,
698
744
  restored: [],
699
745
  removedPlugins: [],
746
+ installedPlugins: [],
700
747
  manualHints: [],
701
748
  failed: [],
702
749
  skipped: [],
@@ -737,7 +784,7 @@ export async function restore(opts) {
737
784
  }
738
785
  /** 文件类动作的绝对目标(reconcile 直接拿它读盘算指纹);插件卸载/越界目标 → null(不可指纹)。 */
739
786
  function walAbsOf(action) {
740
- if (action.kind === 'pluginRemove' || action.target === undefined)
787
+ if (isExternalPluginKind(action.kind) || action.target === undefined)
741
788
  return null;
742
789
  try {
743
790
  return homeAbs(homeDir, action.target, msg);
@@ -818,6 +865,21 @@ export async function restore(opts) {
818
865
  }
819
866
  break;
820
867
  }
868
+ case 'pluginInstall': {
869
+ const target = action.pluginTarget ?? action.pluginName;
870
+ const result = await installer(action.pluginName, target, profileDir, profile);
871
+ if (result.ok) {
872
+ report.installedPlugins.push(target);
873
+ }
874
+ else {
875
+ const reason = result.message ?? msg('restore.pluginInstallFailed');
876
+ report.failed.push({ item: `plugin:${action.pluginName}`, reason });
877
+ // 同卸载分支:外部副作用没做成 → attention(绝不记 done)
878
+ settleStatus = 'attention';
879
+ settleMessage = reason;
880
+ }
881
+ break;
882
+ }
821
883
  case 'credentialHint':
822
884
  report.manualHints.push(action.manualHint ?? action.description);
823
885
  break;
@@ -83,6 +83,7 @@ function statusOf(kind, beforeExists) {
83
83
  case 'fileRemove':
84
84
  return 'deleted';
85
85
  case 'pluginRemove':
86
+ case 'pluginInstall':
86
87
  return 'plugin';
87
88
  case 'credentialHint':
88
89
  return 'hint';
@@ -225,7 +226,7 @@ export async function summarizeRestoreChanges(opts) {
225
226
  entries.push(entry);
226
227
  continue;
227
228
  }
228
- if (action.kind === 'pluginRemove')
229
+ if (action.kind === 'pluginRemove' || action.kind === 'pluginInstall')
229
230
  entry.status = 'plugin';
230
231
  else if (action.kind === 'credentialHint')
231
232
  entry.status = 'hint';
@@ -267,6 +267,16 @@ export interface PluginsFacade {
267
267
  needsRestart: boolean;
268
268
  installedVersion?: string | null;
269
269
  }>;
270
+ /**
271
+ * 卸载插件(issue #132 跟随远端删除;`dsh plugin remove <pkg>`)。
272
+ *
273
+ * 失败即抛(消息经 `classifyDshPluginFailure` 给出可操作诊断,例如 desktop 保留档案被 CLI 拒绝)。
274
+ * 调用方逐项记录 warning、**不阻断**其余项:一次卸载失败不该让整轮同步回滚。
275
+ * `signal` 中止语义与 install 一致(宿主 kill 子进程)。
276
+ */
277
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{
278
+ needsRestart: boolean;
279
+ }>;
270
280
  }
271
281
  export interface WorkspaceFacade {
272
282
  listRecords(): Promise<WorkspaceRecord[]>;
@@ -1040,6 +1050,20 @@ export interface HostFileBackup {
1040
1050
  */
1041
1051
  unreadable?: boolean;
1042
1052
  }
1053
+ /**
1054
+ * 一轮同步里**跟随远端删除**掉的插件(issue #132)。
1055
+ *
1056
+ * 为什么写进快照:undo 必须能把用户装回去 —— 删插件是不可逆的外部副作用,只有快照记得
1057
+ * 「删的是谁、哪个版本」。有意**不进** computeMetadataHash(它只覆盖 entries/hostFileBackups/
1058
+ * beforePlugins 三样破坏性内容),因此记录它不需要重写 manifest 与 blob。
1059
+ */
1060
+ export interface SnapshotPluginRemoval {
1061
+ name: string;
1062
+ /** 删除时本机已装的版本(快照记的是事实;重装用 target = name@version) */
1063
+ version: string;
1064
+ /** 重装目标(name@version;版本未知时就是裸包名) */
1065
+ target: string;
1066
+ }
1043
1067
  export interface Snapshot {
1044
1068
  id: string;
1045
1069
  createdAt: string;
@@ -1049,6 +1073,8 @@ export interface Snapshot {
1049
1073
  status?: SnapshotStatus;
1050
1074
  /** 导入前已安装插件清单(M2 restore 撤销插件时与当前已装对比)。旧快照缺省 */
1051
1075
  beforePlugins?: PluginInfo[];
1076
+ /** 本轮跟随远端删除的插件(issue #132;restore 计划里对称地重装)。旧快照缺省 */
1077
+ pluginRemovals?: SnapshotPluginRemoval[];
1052
1078
  /** 宿主整文件备份(settings.yaml / settings.json / cordis.patch.yml / profiles/<p>/cordis.patch.yml)。旧快照缺省 */
1053
1079
  hostFileBackups?: HostFileBackup[];
1054
1080
  /**
@@ -1096,6 +1122,12 @@ export interface SnapshotStore {
1096
1122
  readBlob(id: string, blobPath: string): Promise<Uint8Array>;
1097
1123
  /** 标记快照生命周期状态(导入成功→done;失败回滚→rolled-back;持久化由实现负责) */
1098
1124
  updateStatus(id: string, status: SnapshotStatus): Promise<void>;
1125
+ /**
1126
+ * 记录「本轮跟删掉的插件」(issue #132):只重写 snapshot.json 的这一个字段,
1127
+ * 不动 manifest 与 blob(它不在 metadataHash 覆盖面内)。不可用时调用方**跳过记录**并靠
1128
+ * 报告里的重装目标人工兜底,绝不因为记不上就中止同步。
1129
+ */
1130
+ recordPluginRemovals?(id: string, removals: SnapshotPluginRemoval[]): Promise<void>;
1099
1131
  }
1100
1132
  /**
1101
1133
  * Phase 4 生产 journal↔snapshot 绑定 context(由宿主注入引擎,引擎在首 destructive side effect 前调用)。
package/lib/index.d.ts CHANGED
@@ -75,7 +75,7 @@ export declare const name = "config-manager";
75
75
  /** Services required before the engine can mount (present in every profile). */
76
76
  export declare const inject: string[];
77
77
  /** Plugin version, kept in sync with package.json ("version"). */
78
- export declare const PLUGIN_VERSION = "0.7.0";
78
+ export declare const PLUGIN_VERSION = "0.8.1";
79
79
  /**
80
80
  * Star 引导弹窗指向的 GitHub 仓库(用户引导点 Star 的目标)。
81
81
  * 与 package.json 的 repository 字段保持一致;界面不可改(硬编码,参照
@@ -188,6 +188,10 @@ export declare class DshPluginsFacade implements PluginsFacade {
188
188
  needsRestart: boolean;
189
189
  installedVersion?: string | null;
190
190
  }>;
191
+ /** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
192
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{
193
+ needsRestart: boolean;
194
+ }>;
191
195
  }
192
196
  /**
193
197
  * 宿主 `sessionPersistence` 的 API 形状(**按 API 形状探测,绝不按 DSH 版本号猜**)。
@@ -570,6 +574,8 @@ export declare class DshPatchFileFacade implements PatchFileFacade {
570
574
  raw: unknown;
571
575
  action: 'insert' | 'update' | 'remove';
572
576
  }[]): Promise<void>;
577
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
578
+ private readPatchDocQuietly;
573
579
  }
574
580
  /** File facade over $DSH_HOME, confined to the home root. */
575
581
  export declare class DshFileSystemFacade implements FileSystemFacade {
@@ -873,6 +879,7 @@ type SelectionView = {
873
879
  sessionsInclude: string[];
874
880
  encrypt: boolean;
875
881
  includeSecrets: boolean;
882
+ deletePlugins: boolean;
876
883
  };
877
884
  /**
878
885
  * Mount the config-manager engine: host context, adapters, and the
package/lib/index.js CHANGED
@@ -75,11 +75,12 @@ import { ROLLBACK_ACTIVITY_FILE_NAME, RollbackSessionActivity } from './core/rol
75
75
  import { isRollbackEnabled, onRollbackEnabledChange, setRollbackEnabled } from './core/rollback-gate.js';
76
76
  // t3:宿主斜杠命令 /rollback(与 HTTP 路由同一道写入门;命令服务惰取,未组合时安静跳过)。
77
77
  import { agentSessionFactsOf, registerRollbackCommand } from './core/command-rollback.js';
78
- import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.js';
78
+ import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, uninstallViaCli, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.js';
79
79
  import { ImportUserSkippedError } from './core/types.js';
80
80
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.js';
81
81
  import { planSelfUpdate, runSelfUpdate } from './core/self-update.js';
82
82
  import { createAdapters } from './adapters/index.js';
83
+ import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, promotedTopLevelIds } from './core/patch-document.js';
83
84
  import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.js';
84
85
  import { createLocalPluginPackHook } from './core/local-plugin-host.js';
85
86
  import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.js';
@@ -148,7 +149,7 @@ export const name = 'config-manager';
148
149
  /** Services required before the engine can mount (present in every profile). */
149
150
  export const inject = ['settings', 'credentials'];
150
151
  /** Plugin version, kept in sync with package.json ("version"). */
151
- export const PLUGIN_VERSION = '0.7.0';
152
+ export const PLUGIN_VERSION = '0.8.1';
152
153
  /** Plugin own package name — excluded from its own exported plugins list. */
153
154
  const PLUGIN_NAME = 'dsh-config-manager';
154
155
  /**
@@ -488,6 +489,10 @@ export class DshPluginsFacade {
488
489
  // 回读实际落盘版本:调用方据此校验升级是否真的生效(issue #101),而不是只看子进程退出码。
489
490
  return { needsRestart: true, installedVersion: readInstalledVersion(profileDir, pkg) };
490
491
  }
492
+ /** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
493
+ uninstall(pkg, signal) {
494
+ return uninstallViaCli(this.homeDir, this.profile, pkg, this.runner, signal);
495
+ }
491
496
  }
492
497
  /** Workspace facade over the real ctx.workspaceRegistry. */
493
498
  class DshWorkspaceFacade {
@@ -1483,15 +1488,13 @@ export class DshPatchFileFacade {
1483
1488
  }
1484
1489
  async applyPatchChanges(file, changes) {
1485
1490
  const p = this.patchPath(file);
1486
- // 1. Load the current document into an ordered lineId → raw table.
1491
+ // 1. Load the current document (the ordered table itself is built by planPatchDocument).
1487
1492
  //
1488
1493
  // 读不出来的既有内容**绝不能当作空文档**(issue #75 的数据丢失点):重建后的文件只包含
1489
1494
  // 本次写入的行,等于把用户手写的其余行整段删掉。三种情况分开处理:
1490
1495
  // - 真不存在(ENOENT)→ 空文档(首次创建,既有语义);
1491
1496
  // - 存在但读不到(EACCES/EBUSY/…)→ 抛错,不改写;
1492
1497
  // - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
1493
- const rows = new Map();
1494
- const order = [];
1495
1498
  let existing = null;
1496
1499
  try {
1497
1500
  existing = await fs.readFile(p, 'utf8');
@@ -1510,58 +1513,41 @@ export class DshPatchFileFacade {
1510
1513
  throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
1511
1514
  }
1512
1515
  }
1513
- if (Array.isArray(doc)) {
1514
- for (const item of doc) {
1515
- if (item === null || typeof item !== 'object')
1516
- continue;
1517
- const obj = item;
1518
- const insert = obj['insert'];
1519
- if (Array.isArray(insert)) {
1520
- for (const entry of insert) {
1521
- if (entry === null || typeof entry !== 'object')
1522
- continue;
1523
- const id = entry['id'];
1524
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1525
- rows.set(id, entry);
1526
- order.push(id);
1527
- }
1528
- }
1529
- continue;
1530
- }
1531
- const id = obj['id'];
1532
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1533
- rows.set(id, obj);
1534
- order.push(id);
1535
- }
1536
- }
1516
+ // 2. Rebuild through core/patch-document.ts (issue #133): the two shapes are **not**
1517
+ // equivalent on the host side. A top-level `- id: X` row *overrides* entry X and is
1518
+ // dropped with `patch: entry "X" not found` when X does not exist; only an
1519
+ // `- insert:` block member *adds* entries. Emitting every row top-level therefore
1520
+ // turned one update into "every insert-only entry (MCP servers, most notably) is
1521
+ // gone after restart".
1522
+ const plan = planPatchDocument(doc, changes);
1523
+ const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1524
+ + dumpPatchDocument(plan.items);
1525
+ // 3. Post-write structure self-check, before anything touches the disk: re-parse the
1526
+ // text we just serialized and require both id sets to match the plan item by item.
1527
+ // A serializer or dialect change that flattens or swallows insert blocks stops here
1528
+ // (zero write) instead of silently degrading every patch row to an override.
1529
+ const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)));
1530
+ if (drift !== null) {
1531
+ throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }));
1532
+ }
1533
+ // 4. 跨层提升守卫(issue #133):待写的顶层 id 若是**另一层**的 insert 成员,写下去就从
1534
+ // 「新增」变成「覆盖」(宿主查不到则丢弃)。对侧读不出来/解析不了只跳过守卫 —— 读护栏
1535
+ // 已在各自层报错,损坏的兄弟文件不该永久阻塞本层写入。
1536
+ const other = file === USER_PATCH_FILE ? profilePatchRel(this.profile) : USER_PATCH_FILE;
1537
+ const promoted = promotedTopLevelIds(await this.readPatchDocQuietly(other), plan.topLevelIds);
1538
+ if (promoted.length > 0) {
1539
+ throw new Error(this.msg('host.patchRefusePromote', { file, ids: promoted.join(', ') }));
1537
1540
  }
1538
- // 2. Apply the changes.
1539
- for (const change of changes) {
1540
- if (change.action === 'remove') {
1541
- if (rows.delete(change.lineId)) {
1542
- const at = order.indexOf(change.lineId);
1543
- if (at >= 0)
1544
- order.splice(at, 1);
1545
- }
1546
- }
1547
- else if (change.action === 'insert' || change.action === 'update') {
1548
- if (!rows.has(change.lineId))
1549
- order.push(change.lineId);
1550
- rows.set(change.lineId, change.raw);
1551
- }
1541
+ await atomicWriteFile(p, text);
1542
+ }
1543
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
1544
+ async readPatchDocQuietly(file) {
1545
+ try {
1546
+ return loadPatchDocument(await fs.readFile(resolve(this.homeDir, file), 'utf8'));
1552
1547
  }
1553
- // 3. Rebuild: every id row is emitted as a top-level row. The loader treats
1554
- // a top-level { id, name } row exactly like an `- insert:` block member
1555
- // (dsh-base patch precedent), so the document stays semantically equal.
1556
- const out = [];
1557
- for (const id of order) {
1558
- const raw = rows.get(id);
1559
- if (raw !== undefined)
1560
- out.push(raw);
1548
+ catch {
1549
+ return undefined;
1561
1550
  }
1562
- const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1563
- + dumpPatchDocument(out);
1564
- await atomicWriteFile(p, text);
1565
1551
  }
1566
1552
  }
1567
1553
  /** File facade over $DSH_HOME, confined to the home root. */
@@ -2327,18 +2313,16 @@ function makeRoutes(deps) {
2327
2313
  /** 分区选择视图形状(无 schemaVersion;密码值永不进视图)。 */
2328
2314
  /** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
2329
2315
  /** 指定通道的分区选择视图。 */
2330
- const selectionView = async (channel) => {
2331
- const sel = await ensureSelectionLoaded(channel);
2332
- return { mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets };
2333
- };
2316
+ /** SyncSelection → SelectionView(字段白名单;密码值永不进视图)。 */
2317
+ const toSelectionView = (sel) => ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets, deletePlugins: sel.deletePlugins });
2318
+ const selectionView = async (channel) => toSelectionView(await ensureSelectionLoaded(channel));
2334
2319
  const selectionViewByChannel = async () => {
2335
2320
  const all = await readAllSyncSelections(syncDir);
2336
- const view = (sel) => ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets });
2337
2321
  // 通道集合来自唯一枚举(SYNC_CHANNELS);不得穷举字面量(漏一处即该通道状态静默缺失)
2338
2322
  const out = {};
2339
2323
  for (const channel of SYNC_CHANNELS) {
2340
2324
  selectionCache[channel] = all[channel];
2341
- out[channel] = view(all[channel]);
2325
+ out[channel] = toSelectionView(all[channel]);
2342
2326
  }
2343
2327
  return out;
2344
2328
  };
@@ -2443,7 +2427,8 @@ function makeRoutes(deps) {
2443
2427
  transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir);
2444
2428
  }
2445
2429
  const channel = channelOf(cfg);
2446
- const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection());
2430
+ const selection = selectionCache[channel] ?? defaultSyncSelection();
2431
+ const sections = effectiveSections(selection);
2447
2432
  return new SyncEngine({
2448
2433
  ctx: host,
2449
2434
  transport,
@@ -2454,11 +2439,10 @@ function makeRoutes(deps) {
2454
2439
  zipDir: tmpDir,
2455
2440
  msg,
2456
2441
  ...(sections === undefined ? {} : { sections }),
2457
- ...(engineOpts.optInSections === undefined || engineOpts.optInSections.length === 0
2458
- ? {}
2459
- : { optInSections: engineOpts.optInSections }),
2460
- // m-retention:远端快照裁剪与本地备份产物共用同一份 GFS 保留策略(缺省 = 最近 10 个,
2461
- // 与改造前逐字等价);用户改完策略即时生效(每次 prune 都重读)。
2442
+ // issue #132:开关开 = 授权(手动/自动同判据);self 守卫防同步把自己删掉
2443
+ deletePlugins: selection.deletePlugins, selfPluginName: PLUGIN_NPM_PACKAGE,
2444
+ ...(engineOpts.optInSections?.length ? { optInSections: engineOpts.optInSections } : {}),
2445
+ // m-retention:远端裁剪与本地备份共用 GFS 策略(缺省最近 10 个,每次 prune 重读 ⇒ 改完即时生效)。
2462
2446
  retentionPolicy: () => retentionPolicyProvider(),
2463
2447
  });
2464
2448
  };
@@ -3505,8 +3489,7 @@ export function apply(ctx, config) {
3505
3489
  namespaces: async () => (await ctx.settings.describe({ redactSecrets: true })).map((d) => String(d.ns)),
3506
3490
  // Sessions 分区默认关(含敏感内容):挂载 adapter 供 Custom Export 显式勾选(§3.3/§15)。
3507
3491
  includeSessions: true,
3508
- // 导出 plugins 分区时不列本插件自身,避免备份中的自引用条目。
3509
- selfPluginName: PLUGIN_NAME,
3492
+ selfPluginName: PLUGIN_NAME, // 导出 plugins 分区时不列本插件自身,避免备份里的自引用条目
3510
3493
  // pluginFiles 扩展:额外白名单文件 + 约定配置目录(都相对 ~/.dsh 根),支持导出更多插件配置。
3511
3494
  pluginFiles: config?.pluginFiles,
3512
3495
  pluginFilesDir: config?.pluginFilesDir,
@@ -231,6 +231,11 @@ export interface RestoreExecutor {
231
231
  ok: boolean;
232
232
  message?: string;
233
233
  }>;
234
+ /** 装回跟远端删掉的插件(官方通道,issue 132 的反向);失败返回 { ok:false, message } */
235
+ installPlugin(name: string, target: string): Promise<{
236
+ ok: boolean;
237
+ message?: string;
238
+ }>;
234
239
  /**
235
240
  * home 相对路径 → 磁盘绝对路径(逐动作 WAL 用:journal 的 ref 必须是绝对路径,
236
241
  * reconcile 的 verifyStepFingerprint 直接拿它读盘算指纹)。缺省 = 不登记 WAL。
@@ -24,7 +24,7 @@ import { collectCredentialRefs } from '../security/credentials-yaml.js';
24
24
  import { decryptCredentials, SecurityError } from '../security/index.js';
25
25
  import { engineMsg } from '../core/engine-locale.js';
26
26
  import { createPreRestoreAttemptDir } from '../core/restore.js';
27
- import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.js';
27
+ import { collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.js';
28
28
  import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, normalizeGitSubdir, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.js';
29
29
  import { DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, lastRunFailureMessage, readAllAutosyncConfigs, readAutosyncConfig } from '../sync/autosync-config.js';
30
30
  import { SYNC_CHANNELS } from '../sync/sync-config.js';
@@ -459,6 +459,7 @@ export async function executeRestorePlan(plan, exec, onAction, journal, resumeHi
459
459
  snapshotId: plan.snapshotId,
460
460
  restored: [],
461
461
  removedPlugins: [],
462
+ installedPlugins: [],
462
463
  manualHints: [],
463
464
  failed: [],
464
465
  skipped: [],
@@ -469,7 +470,7 @@ export async function executeRestorePlan(plan, exec, onAction, journal, resumeHi
469
470
  const wal = createRestoreWal(journal);
470
471
  const walByAction = new Map();
471
472
  const resume = resumeHint;
472
- const absOf = (action) => action.kind === 'pluginRemove' || action.target === undefined || exec.absPath === undefined
473
+ const absOf = (action) => isExternalPluginKind(action.kind) || action.target === undefined || exec.absPath === undefined
473
474
  ? null
474
475
  : exec.absPath(action.target);
475
476
  if (wal !== null && exec.absPath !== undefined) {
@@ -543,6 +544,23 @@ export async function executeRestorePlan(plan, exec, onAction, journal, resumeHi
543
544
  }
544
545
  break;
545
546
  }
547
+ case 'pluginInstall': {
548
+ const name = action.pluginName;
549
+ const target = action.pluginTarget ?? name;
550
+ if (name === undefined || target === undefined)
551
+ throw new Error(engineMsg('restore.missingPluginName'));
552
+ const result = await exec.installPlugin(name, target);
553
+ if (result.ok) {
554
+ report.installedPlugins.push(target);
555
+ }
556
+ else {
557
+ const reason = result.message ?? engineMsg('restore.pluginInstallFailed');
558
+ report.failed.push({ item: `plugin:${name}`, reason });
559
+ settleStatus = 'attention';
560
+ settleMessage = reason;
561
+ }
562
+ break;
563
+ }
546
564
  case 'credentialHint':
547
565
  report.manualHints.push(action.manualHint ?? action.description);
548
566
  break;
@@ -612,6 +630,14 @@ export function makeRestoreExecutor(snapshotDir, host, profile) {
612
630
  const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput');
613
631
  return { ok: false, message: msgOf(host)('host.restoreUninstallFailed', { name, code: String(result.exitCode), tail }) };
614
632
  },
633
+ installPlugin: async (name, target) => {
634
+ const result = await runDshPlugin(profileDir, profile, ['add', target]);
635
+ if (result.exitCode === 0)
636
+ return { ok: true };
637
+ const output = `${result.stderr}\n${result.stdout}`.trim();
638
+ const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput');
639
+ return { ok: false, message: engineMsg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) };
640
+ },
615
641
  };
616
642
  }
617
643
  /**
@@ -1174,6 +1174,9 @@ export function syncRoutes(env) {
1174
1174
  encrypt: body['encrypt'] === true,
1175
1175
  // 安全兜底:includeSecrets 必须同时 encrypt(密钥绝不明文进同步通道)
1176
1176
  includeSecrets: body['includeSecrets'] === true && body['encrypt'] === true,
1177
+ // issue #132:跟随远端删除插件。缺省关;请求体非 true 一律按关处理
1178
+ // (重新保存表单时收起开关 = 明确关掉,不留上一次的 true)
1179
+ deletePlugins: body['deletePlugins'] === true,
1177
1180
  };
1178
1181
  // 加密/解密密码持久化(用户要求:勾选即记住,取消勾选或主动删除才清)。
1179
1182
  // 值只写进 DSH credentials(绝不进 sync-selection.json / 日志 / 响应);
@@ -0,0 +1,78 @@
1
+ import type { SectionData, SectionId } from '../schema/types.ts';
2
+ import type { MergeConflictReason, MergeSectionResult } from './merge.ts';
3
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
4
+ export declare function mergePreviewSectionView(result: MergeSectionResult): MergePreviewSectionView;
5
+ /**
6
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
7
+ *
8
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
9
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
10
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
11
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
12
+ * (那正是本 issue 的缺陷本身)。
13
+ *
14
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
15
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
16
+ */
17
+ export declare function previewCaliberDiffersFromExport(sectionId: SectionId, data: SectionData): boolean;
18
+ /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
19
+ export interface MergePreviewConflictView {
20
+ /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
21
+ path: string;
22
+ kind: 'key' | 'file';
23
+ /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
24
+ reason?: MergeConflictReason;
25
+ /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
26
+ localPreview: string;
27
+ /** 远端侧的可读预览(同上)。 */
28
+ remotePreview: string;
29
+ /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
30
+ ancestorPreview: string;
31
+ }
32
+ /** previewMerge 的单个分区视图。 */
33
+ export interface MergePreviewSectionView {
34
+ id: SectionId;
35
+ decision: MergeSectionResult['decision'];
36
+ /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
37
+ autoMerged?: number;
38
+ conflictCount: number;
39
+ conflicts: MergePreviewConflictView[];
40
+ }
41
+ /** previewMerge 结果(只读、零写入)。 */
42
+ export interface MergePreview {
43
+ /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
44
+ ok: boolean;
45
+ /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
46
+ snapshotId: string;
47
+ /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
48
+ hasAncestor: boolean;
49
+ sections: MergePreviewSectionView[];
50
+ /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
51
+ summary: {
52
+ auto: number;
53
+ review: number;
54
+ conflicts: number;
55
+ skipped: number;
56
+ };
57
+ message?: string;
58
+ reason?: 'remote-empty';
59
+ /**
60
+ * 本轮合并**将卸载**的插件(issue #132):确认页必须单列出来,用户据此可以整轮取消。
61
+ * 仅在 plugins 分区可应用(useRemote/keepLocal/merge)时才有条目 —— 分区冲突时不删。
62
+ */
63
+ pluginRemovals?: {
64
+ name: string;
65
+ version: string;
66
+ }[];
67
+ /** 远端删了、本机却改过 → 不删,等人工裁决(与 conflict 清单同语义,这里为插件专列) */
68
+ pluginRemovalConflicts?: {
69
+ name: string;
70
+ ancestorVersion: string;
71
+ localVersion: string;
72
+ }[];
73
+ /** 考察过但没删的条目及原因(含开关关闭 = 'switch-off',界面据此如实说明) */
74
+ pluginRemovalSkipped?: {
75
+ name: string;
76
+ reason: string;
77
+ }[];
78
+ }