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
@@ -2,11 +2,14 @@ import { Importer } from '../core/importer.ts';
2
2
  import type { ConfigAdapter, GlobalConflictStrategy, HostContext, ImportAnalysis, ImportPlan, ImportResult, PathMapping, PlanItem, PlanItemKind, SecretScanner } from '../core/types.ts';
3
3
  import type { SectionData, SectionId } from '../schema/types.ts';
4
4
  import type { SnapshotFs } from './fs.ts';
5
+ import type { PluginRemovalReportItem } from './plugin-removal-apply.ts';
5
6
  import type { RetentionPolicy } from './retention-policy.ts';
6
7
  import type { PendingMerge } from './sync-state.ts';
7
8
  import type { SyncProbeResult, SyncSnapshotMeta, SyncTransport } from './transport.ts';
8
9
  import type { MsgFunc } from '../core/messages.ts';
9
- import type { MergeConflictReason, MergePlan, MergeSectionResult } from './merge.ts';
10
+ import type { MergePlan } from './merge.ts';
11
+ import type { MergePreview } from './merge-preview-view.ts';
12
+ export type { MergePreview, MergePreviewConflictView, MergePreviewSectionView } from './merge-preview-view.ts';
10
13
  import type { SyncApplyPlan } from './risk.ts';
11
14
  import type { TransactionSnapshotContext } from '../core/types.ts';
12
15
  import type { PlanItemProgress } from '../core/analyzer.ts';
@@ -56,6 +59,19 @@ export interface SyncEngineOptions {
56
59
  * 手动请求仍可用 push(opts.sections) 覆盖。
57
60
  */
58
61
  sections?: SectionId[];
62
+ /**
63
+ * 跟随远端删除插件(issue #132):祖先快照里有、远端快照里没有、本机未改过的插件 →
64
+ * 在本轮应用成功后执行 `dsh plugin remove`。
65
+ *
66
+ * 缺省 **false**(既有行为逐字不变)。只由宿主的持久化选择注入 —— 用户勾开关即授权,
67
+ * 手动合并与自动同步因此共享同一个判据(不再由调用点各自决定)。
68
+ */
69
+ deletePlugins?: boolean;
70
+ /**
71
+ * 本插件自己的包名(跟随删除时**永不**碰它;'' = 不设防,只用于不关心自身的测试)。
72
+ * 宿主注入 `PLUGIN_NAME`:删掉正在运行的宿主插件会让下一次启动直接缺功能。
73
+ */
74
+ selfPluginName?: string;
59
75
  /**
60
76
  * 远端快照保留策略提供者(m-retention 接线):缺省 = DEFAULT_RETENTION_POLICY
61
77
  * (keepLast=10,与改造前的硬编码 FIFO 逐字等价)。
@@ -229,7 +245,18 @@ export interface ApplyReport {
229
245
  review: import('./review-queue.ts').ReviewQueueItem[];
230
246
  /** 来自 Importer.ImportResult 的 warnings;UI 可用于红条提示(含回滚未完成项) */
231
247
  warnings: string[];
248
+ /**
249
+ * 跟随远端删除插件的逐项结果(issue #132;缺省不出现 = 本轮没有该步骤)。
250
+ *
251
+ * 之所以逐项回传而不是只回一条汇总:卸载是**不可回滚**的外部进程动作(plugins 分区没有
252
+ * snapshot/rollback 钩子),界面与报告必须能逐条说清「删了哪个版本、哪个没删成、为什么」。
253
+ */
254
+ pluginRemovals?: PluginRemovalReportItem[];
255
+ /** 删过插件 → 必须重启(与安装同语义;导入结果说不用也不能吞) */
256
+ needsRestart?: boolean;
232
257
  }
258
+ /** 一条插件卸载结果(实现与 undo 编排见 ./plugin-removal-apply.ts;此处再导出保持既有导入面)。 */
259
+ export type { PluginRemovalReportItem } from './plugin-removal-apply.ts';
233
260
  /** applyItems 报告(§3.4 ApplyItemsResponse 的服务端形态) */
234
261
  export interface ApplyItemsReport {
235
262
  ok: boolean;
@@ -278,48 +305,6 @@ export interface ApplyItemsReport {
278
305
  * 保留导出是为了让既有调用方/测试仍能引用「缺省保留份数」这一事实,不再作为唯一判据。
279
306
  */
280
307
  export declare const MAX_REMOTE_SNAPSHOTS: number;
281
- /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
282
- export interface MergePreviewConflictView {
283
- /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
284
- path: string;
285
- kind: 'key' | 'file';
286
- /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
287
- reason?: MergeConflictReason;
288
- /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
289
- localPreview: string;
290
- /** 远端侧的可读预览(同上)。 */
291
- remotePreview: string;
292
- /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
293
- ancestorPreview: string;
294
- }
295
- /** previewMerge 的单个分区视图。 */
296
- export interface MergePreviewSectionView {
297
- id: SectionId;
298
- decision: MergeSectionResult['decision'];
299
- /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
300
- autoMerged?: number;
301
- conflictCount: number;
302
- conflicts: MergePreviewConflictView[];
303
- }
304
- /** previewMerge 结果(只读、零写入)。 */
305
- export interface MergePreview {
306
- /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
307
- ok: boolean;
308
- /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
309
- snapshotId: string;
310
- /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
311
- hasAncestor: boolean;
312
- sections: MergePreviewSectionView[];
313
- /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
314
- summary: {
315
- auto: number;
316
- review: number;
317
- conflicts: number;
318
- skipped: number;
319
- };
320
- message?: string;
321
- reason?: 'remote-empty';
322
- }
323
308
  /**
324
309
  * 用户对**单个分区**的裁决(分区粒度:没有冲突项粒度 / 复合 id)。
325
310
  * - useRemote:用远端整分区原值(对键级冲突而言 = 放弃本机该分区里除冲突键以外的改动);远端没有该分区 → 无法表达删除,计入 pendingConflicts;
@@ -395,7 +380,13 @@ export declare class SyncEngine {
395
380
  * 原始值(键级冲突只给键值),而 'useRemote' / 'keepLocal' 必须落**整分区**数据才能进导入计划。
396
381
  */
397
382
  private lastMergeInputs;
383
+ /** issue #132:跟随远端删除插件(缺省 false = 既有行为逐字不变) */
384
+ private readonly deletePlugins;
385
+ /** 本插件自己的包名(永不跟随删除;'' = 不设防) */
386
+ private readonly selfPluginName;
398
387
  constructor(opts: SyncEngineOptions);
388
+ /** 删除计划(预览与执行共用同一份判据;本机清单读不到 → undefined = 本轮不判也不删)。 */
389
+ private pluginRemovalPlan;
399
390
  /** 同步只做 portable 分区(deviceSpecific/platformSpecific 永不参与)。
400
391
  * 构造注入 sections(同步范围)时再按注入范围过滤 —— 自动同步等后台流程
401
392
  * merge/apply/push 全链路复用用户选择;手动请求仍可用 push(opts.sections) 覆盖。 */
@@ -23,8 +23,6 @@ import { createAdapters } from '../adapters/index.js';
23
23
  import { defaultSecretScanner } from '../core/exporter.js';
24
24
  import { Importer } from '../core/importer.js';
25
25
  import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.js';
26
- // issue #91:只读预览与基线 hash 的口径判定(本地源插件在预览里不会被 npm pack)
27
- import { isLocalPluginSpec } from '../core/local-plugin-pack.js';
28
26
  import { isFileSection, SECTION_FILE_PREFIXES, SECTION_JSON_PATHS } from '../schema/config.js';
29
27
  import { buildManifest, CHECKSUMS_FILE, MANIFEST_FILE } from '../schema/manifest.js';
30
28
  import { CURRENT_SCHEMA_VERSION } from '../schema/versions.js';
@@ -35,6 +33,7 @@ import { createSnapshotFs, joinFs } from './fs.js';
35
33
  import { writeSnapshotToDir } from './layout.js';
36
34
  import { resolvePushBase } from './push-precheck.js';
37
35
  import { credentialsMapFromYaml, decryptCredentialsPayload, decryptSectionsPayload, encryptCredentialsPayload, encryptSectionsPayload, } from './snapshot-crypto.js';
36
+ import { applyPluginRemovalStep, pluginRemovalPlanOf, pluginRemovalPreviewOf, recordPluginRemovalUndo, } from './plugin-removal-apply.js';
38
37
  import { OPT_IN_SYNC_SECTIONS } from './sync-selection.js';
39
38
  import { listRemoteSnapshotIndex, planSessionBookkeeping, remoteTombstonesOf, stripTombstonedSessionsInPlace, } from './session-tombstones.js';
40
39
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './retention-policy.js';
@@ -45,7 +44,7 @@ import { engineMsg } from './messages.js';
45
44
  import { DEFAULT_ANCESTOR_KEEP, pruneAncestors, tryLoadAncestor, writeAncestor, writeEncryptedAncestor } from './ancestor.js';
46
45
  import { merge as mergeSections } from './merge.js';
47
46
  import { prepareApplyBundle } from './apply-bundle.js';
48
- import { previewTextOf } from './merge-preview-text.js';
47
+ import { mergePreviewSectionView, previewCaliberDiffersFromExport } from './merge-preview-view.js';
49
48
  import { gcSkipWarning, readGcSkipCode, reportGcSkipOnce } from './gc-skip.js';
50
49
  import { classifyMergePlan } from './risk.js';
51
50
  import { registerMessageCatalog } from '../core/engine-locale.js';
@@ -80,24 +79,6 @@ const en = {
80
79
  'sync.pushBaselineAdoptedNoAncestor': 'The newest remote snapshot {remote} was pushed by this device, but no local ancestor copy exists for it: the baseline has been adopted (the next merge degrades to a two-way merge, which is still safe)',
81
80
  };
82
81
  registerMessageCatalog({ id: 'sync-engine-merge', zh, en });
83
- /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
84
- function mergePreviewSectionView(result) {
85
- const conflicts = result.conflicts.map((c) => ({
86
- path: c.path,
87
- kind: c.kind,
88
- ...(c.reason !== undefined ? { reason: c.reason } : {}),
89
- localPreview: previewTextOf(c.local),
90
- remotePreview: previewTextOf(c.remote),
91
- ancestorPreview: previewTextOf(c.ancestor),
92
- }));
93
- return {
94
- id: result.id,
95
- decision: result.decision,
96
- ...(result.autoMerged !== undefined ? { autoMerged: result.autoMerged } : {}),
97
- conflictCount: result.conflicts.length,
98
- conflicts,
99
- };
100
- }
101
82
  /**
102
83
  * 失败路径的**显式兜底回滚**:把 core 的 RollbackReport 翻成「是否完整 + 告警行」。
103
84
  *
@@ -138,24 +119,6 @@ const FORBIDDEN_SECTIONS = ['credentialsStatus', 'secrets'];
138
119
  * 保留导出是为了让既有调用方/测试仍能引用「缺省保留份数」这一事实,不再作为唯一判据。
139
120
  */
140
121
  export const MAX_REMOTE_SNAPSHOTS = DEFAULT_RETENTION_POLICY.keepLast;
141
- /**
142
- * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
143
- *
144
- * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
145
- * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
146
- * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
147
- * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
148
- * (那正是本 issue 的缺陷本身)。
149
- *
150
- * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
151
- * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
152
- */
153
- function previewCaliberDiffersFromExport(sectionId, data) {
154
- if (sectionId !== 'plugins')
155
- return false;
156
- const plugins = data.plugins;
157
- return Array.isArray(plugins) && plugins.some((p) => isLocalPluginSpec(p?.spec));
158
- }
159
122
  export class SyncEngine {
160
123
  ctx;
161
124
  transport;
@@ -208,6 +171,10 @@ export class SyncEngine {
208
171
  * 原始值(键级冲突只给键值),而 'useRemote' / 'keepLocal' 必须落**整分区**数据才能进导入计划。
209
172
  */
210
173
  lastMergeInputs = null;
174
+ /** issue #132:跟随远端删除插件(缺省 false = 既有行为逐字不变) */
175
+ deletePlugins;
176
+ /** 本插件自己的包名(永不跟随删除;'' = 不设防) */
177
+ selfPluginName;
211
178
  constructor(opts) {
212
179
  if (opts.ctx === null || typeof opts.ctx !== 'object')
213
180
  throw new Error(zhMsg('sync.missingCtx'));
@@ -238,6 +205,28 @@ export class SyncEngine {
238
205
  // 归一:只有注册表声明的「可选分区」能被放行 —— 调用方传错 id 不会凭空解锁别的分区
239
206
  this.optInSections = new Set((opts.optInSections ?? []).filter((id) => OPT_IN_SYNC_SECTIONS.includes(id)));
240
207
  this.retentionPolicyProvider = opts.retentionPolicy ?? (() => DEFAULT_RETENTION_POLICY);
208
+ this.deletePlugins = opts.deletePlugins === true;
209
+ this.selfPluginName = opts.selfPluginName ?? '';
210
+ }
211
+ /** 删除计划(预览与执行共用同一份判据;本机清单读不到 → undefined = 本轮不判也不删)。 */
212
+ async pluginRemovalPlan() {
213
+ const inputs = this.lastMergeInputs;
214
+ if (inputs === null)
215
+ return undefined;
216
+ let installed;
217
+ try {
218
+ installed = await this.ctx.plugins.listInstalled();
219
+ }
220
+ catch {
221
+ return undefined; // 读不到本机清单 = 无法证明「本机装着」→ 一个都不删(绝不盲删)
222
+ }
223
+ return pluginRemovalPlanOf({
224
+ ancestor: inputs.ancestor['plugins'],
225
+ remote: inputs.remote['plugins'],
226
+ installed,
227
+ enabled: this.deletePlugins,
228
+ selfName: this.selfPluginName,
229
+ });
241
230
  }
242
231
  /** 同步只做 portable 分区(deviceSpecific/platformSpecific 永不参与)。
243
232
  * 构造注入 sections(同步范围)时再按注入范围过滤 —— 自动同步等后台流程
@@ -1149,7 +1138,7 @@ export class SyncEngine {
1149
1138
  ancestorPortable[id] = data;
1150
1139
  }
1151
1140
  }
1152
- const plan = mergeSections(localSections, remotePortable, ancestorPortable);
1141
+ const plan = mergeSections(localSections, remotePortable, ancestorPortable, { deletePlugins: this.deletePlugins });
1153
1142
  // 结果**经返回值**交给调用方(previewMerge / applyMergeResolutions 都用这一份,不会二次下载);
1154
1143
  // 这里只留两个进程内备忘:祖先可用性(预览要如实说明「为什么全是冲突」)与三方输入
1155
1144
  // (applyMergeResolutions 要把分区级裁决落回**整分区**数据)。
@@ -1179,12 +1168,17 @@ export class SyncEngine {
1179
1168
  summary.review = split.review.length;
1180
1169
  summary.skipped = split.skipped.length;
1181
1170
  summary.conflicts = plan.sections.filter((s) => s.decision === 'conflict').length;
1171
+ const removalView = pluginRemovalPreviewOf({
1172
+ plan: await this.pluginRemovalPlan(),
1173
+ sections: plan.sections,
1174
+ });
1182
1175
  return {
1183
1176
  ok: true,
1184
1177
  snapshotId,
1185
1178
  hasAncestor: this.lastMergeHadAncestor,
1186
1179
  sections: plan.sections.map(mergePreviewSectionView),
1187
1180
  summary,
1181
+ ...(removalView === undefined ? {} : removalView),
1188
1182
  };
1189
1183
  }
1190
1184
  /**
@@ -1555,6 +1549,17 @@ export class SyncEngine {
1555
1549
  rollbackFull: rb.full,
1556
1550
  };
1557
1551
  }
1552
+ // 4') issue #132:跟随远端删除插件(手动与自动共享此路径)。必须在 exportAppliedSections
1553
+ // 之前 —— 基线要记录「删完之后」的真实清单,否则祖先仍带着刚删的包、每轮重复提删除。
1554
+ // 4'') undo 线索:删掉的插件写进本次回滚快照,恢复计划据此反向重装;记不上只告警。
1555
+ const pluginStep = await applyPluginRemovalStep({
1556
+ appliedIds, plan: await this.pluginRemovalPlan(), enabled: this.deletePlugins,
1557
+ uninstall: (name) => this.ctx.plugins.uninstall(name), msg: this.msg,
1558
+ });
1559
+ const undoWarnings = await recordPluginRemovalUndo({
1560
+ removals: pluginStep.removals, snapshotId: snapshot.id,
1561
+ record: store.recordPluginRemovals?.bind(store), msg: this.msg,
1562
+ });
1558
1563
  // 5) 全成功 → recordBaseline(更新祖先基线)。
1559
1564
  // **基线必须以「实际落地的本地导出」为准(F-2,2026-10)**:写回时 adapter 会自增本机侧字段
1560
1565
  // (如 settings.namespaces[*].revision),而 merged 携带的是**远端快照里的值**;用它记基线
@@ -1569,7 +1574,8 @@ export class SyncEngine {
1569
1574
  restoreId: snapshot.id,
1570
1575
  rolledBack: false,
1571
1576
  review: [],
1572
- warnings: [...(result.warnings ?? []), this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1577
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1578
+ ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
1573
1579
  };
1574
1580
  }
1575
1581
  await this.recordBaseline(tempSnapshot.id, landed, undefined, {
@@ -1584,7 +1590,9 @@ export class SyncEngine {
1584
1590
  restoreId: snapshot.id,
1585
1591
  rolledBack: false,
1586
1592
  review: [],
1587
- warnings: result.warnings ?? [],
1593
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings],
1594
+ // 删过插件必须重启(与安装同语义):报告不能只说「已应用」
1595
+ ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
1588
1596
  };
1589
1597
  }
1590
1598
  finally {
@@ -29,6 +29,14 @@ export interface SyncSelection {
29
29
  encrypt: boolean;
30
30
  /** 手动推送默认导出真实凭据值(安全:必须同时 encrypt;自动同步恒 false) */
31
31
  includeSecrets: boolean;
32
+ /**
33
+ * 跟随远端删除插件(issue #132;缺省 **false** = 既有行为逐字不变)。
34
+ *
35
+ * 打开后:祖先快照里有、远端快照里没有、且本机未改过的插件,手动合并与自动同步都会执行
36
+ * `dsh plugin remove`(开关本身就是用户的显式授权,见 docs/known-issues/known-gaps.md G-20)。
37
+ * 关闭时一律不删(候选降级为 `switch-off`,报告里逐项写明原因)。
38
+ */
39
+ deletePlugins: boolean;
32
40
  }
33
41
  /** 全通道选择视图(v2 文件直接读取;status 路由一次返回两个通道的选择)。 */
34
42
  export type SyncSelectionByChannel = Record<SyncTransportType, SyncSelection>;
@@ -66,6 +66,7 @@ export function defaultSyncSelection() {
66
66
  sessionsInclude: [],
67
67
  encrypt: false,
68
68
  includeSecrets: false,
69
+ deletePlugins: false,
69
70
  };
70
71
  }
71
72
  /**
@@ -117,6 +118,9 @@ function parseChannelSelection(obj) {
117
118
  sel.encrypt = obj['encrypt'];
118
119
  if (typeof obj['includeSecrets'] === 'boolean')
119
120
  sel.includeSecrets = obj['includeSecrets'];
121
+ // issue #132:缺字段 = 旧文件 = 关(绝不把「没这个字段」解释成「用户同意删插件」)
122
+ if (typeof obj['deletePlugins'] === 'boolean')
123
+ sel.deletePlugins = obj['deletePlugins'];
120
124
  // 安全兜底:持久化数据被篡改导致 includeSecrets 但未 encrypt → 强制关掉导出密钥
121
125
  if (sel.includeSecrets && !sel.encrypt)
122
126
  sel.includeSecrets = false;
@@ -207,6 +211,8 @@ export async function writeSyncSelection(dir, channel, sel) {
207
211
  sessionsInclude: channels[ch].sessionsInclude,
208
212
  encrypt: channels[ch].encrypt,
209
213
  includeSecrets: channels[ch].includeSecrets,
214
+ // issue #132:落盘白名单漏写 = 用户勾了开关、重启后静默变回关(P0-3 的同一类错)
215
+ deletePlugins: channels[ch].deletePlugins,
210
216
  })),
211
217
  };
212
218
  const target = path.join(dir, SYNC_SELECTION_FILE);
@@ -30,7 +30,14 @@ export interface GranularMergeOutcome {
30
30
  /** 自动并入的变更点(口径 = 用户能感知的「两侧各自的改动都保住了」处数) */
31
31
  mergePoints: number;
32
32
  }
33
+ /**
34
+ * 钩子可读的合并上下文:目前只有 plugins 需要 —— 「跟随远端删除插件」是用户开关,
35
+ * 关着时钩子必须**不参与**(交给通用路径 = 与未引入 #132 前逐字一致),否则会静默丢掉本机条目。
36
+ */
37
+ export interface GranularMergeHooks {
38
+ deletePlugins?: boolean;
39
+ }
33
40
  /** 记录级合并钩子签名(`merge.ts` 按分区 id 调用;返回 undefined = 不参与,走通用路径)。 */
34
- export type GranularMerger = (local: SectionData, remote: SectionData, ancestor: SectionData | undefined) => GranularMergeOutcome | undefined;
41
+ export type GranularMerger = (local: SectionData, remote: SectionData, ancestor: SectionData | undefined, hooks?: GranularMergeHooks) => GranularMergeOutcome | undefined;
35
42
  /** workspaces 分区记录级合并(`merge.ts` 的分区钩子)。 */
36
43
  export declare const mergeWorkspacesSection: GranularMerger;
@@ -20,6 +20,7 @@ function statusOfKind(kind) {
20
20
  case 'fileRemove':
21
21
  return 'deleted';
22
22
  case 'pluginRemove':
23
+ case 'pluginInstall':
23
24
  return 'plugin';
24
25
  case 'credentialHint':
25
26
  return 'hint';
@@ -72,6 +72,11 @@ export interface SyncChannelSettings {
72
72
  sessionsInclude: readonly string[];
73
73
  encrypt: boolean;
74
74
  includeSecrets: boolean;
75
+ /**
76
+ * 跟随远端删除插件(issue #132,缺省 **false**):祖先有、远端没有、本机未改过的插件
77
+ * 会执行 `dsh plugin remove`。勾上 = 用户显式授权手动合并与自动同步都删。
78
+ */
79
+ deletePlugins: boolean;
75
80
  encryptPassword: string;
76
81
  encryptPasswordConfirm: string;
77
82
  /** 本机凭据库里是否已有密码(只回布尔,值永不回浏览器) */
@@ -139,6 +144,7 @@ export interface SyncSelectionRequestBody {
139
144
  sessionsInclude: string[];
140
145
  encrypt: boolean;
141
146
  includeSecrets: boolean;
147
+ deletePlugins: boolean;
142
148
  encryptPassword?: string;
143
149
  decryptPassword?: string;
144
150
  clearEncryptPassword?: boolean;
@@ -151,6 +157,7 @@ export interface SyncSelectionPatch {
151
157
  sessionsInclude?: string[];
152
158
  encrypt?: boolean;
153
159
  includeSecrets?: boolean;
160
+ deletePlugins?: boolean;
154
161
  encryptPassword?: string;
155
162
  decryptPassword?: string;
156
163
  clearEncryptPassword?: boolean;
@@ -163,6 +170,7 @@ export interface SyncChannelSettingsPatch {
163
170
  sessionsInclude?: string[];
164
171
  encrypt?: boolean;
165
172
  includeSecrets?: boolean;
173
+ deletePlugins?: boolean;
166
174
  encryptPassword?: string;
167
175
  encryptPasswordConfirm?: string;
168
176
  encryptPasswordSaved?: boolean;
@@ -177,6 +185,7 @@ export interface SyncChannelBackfill {
177
185
  sessionsInclude: string[];
178
186
  encrypt: boolean;
179
187
  includeSecrets: boolean;
188
+ deletePlugins: boolean;
180
189
  encryptPasswordSaved: boolean;
181
190
  decryptPasswordSaved: boolean;
182
191
  autosyncEnabled: boolean;
@@ -188,6 +197,7 @@ export interface SyncSelectionLike {
188
197
  sessionsInclude?: string[];
189
198
  encrypt?: boolean;
190
199
  includeSecrets?: boolean;
200
+ deletePlugins?: boolean;
191
201
  }
192
202
  /** 按通道的自动同步状态(/sync/status 的 autosyncByChannel[ch])。 */
193
203
  export interface SyncAutosyncLike {
@@ -303,6 +303,7 @@ export function buildSelectionRequest(channel, current, patch = {}) {
303
303
  sessionsInclude: [...(patch.sessionsInclude ?? current.sessionsInclude)],
304
304
  encrypt: patch.encrypt ?? current.encrypt,
305
305
  includeSecrets: patch.includeSecrets ?? current.includeSecrets,
306
+ deletePlugins: patch.deletePlugins ?? current.deletePlugins,
306
307
  ...(patch.encryptPassword !== undefined && patch.encryptPassword !== ''
307
308
  ? { encryptPassword: patch.encryptPassword }
308
309
  : {}),
@@ -438,6 +439,7 @@ export function channelBackfillFromStatus(input) {
438
439
  sessionsInclude: [...(selection?.sessionsInclude ?? [])],
439
440
  encrypt: selection?.encrypt ?? false,
440
441
  includeSecrets: selection?.includeSecrets ?? false,
442
+ deletePlugins: selection?.deletePlugins ?? false,
441
443
  encryptPasswordSaved: credentials?.encryptPasswordConfigured ?? false,
442
444
  decryptPasswordSaved: credentials?.decryptPasswordConfigured ?? false,
443
445
  autosyncEnabled: autosync?.enabled ?? false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-manager",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "license": "MIT",
5
5
  "description": "Backup, restore, export, import, migrate and sync your DeepSeek Harness (DSH) configuration: settings, plugins, MCP servers, skills, agent presets and workspaces. One-click migration to another machine. DSH 配置一键备份、恢复、导出、导入、迁移与同步插件。",
6
6
  "icon": "./icon.svg",
@@ -41,11 +41,31 @@ test('mcp: extractMcpServers 兼容单行与 insert 块', () => {
41
41
  assert.equal(http?.sourceLineId, 'mcp-http');
42
42
  });
43
43
 
44
- test('mcp: buildMcpPatchLine 构造写回行', () => {
44
+ test('mcp: buildMcpPatchLine 构造写回行(scoped 包名 + 显式 transport)', () => {
45
45
  const line = buildMcpPatchLine('mcp-fs', { serverName: 'filesystem', type: 'stdio', command: 'npx', args: ['-y', 'x'] });
46
46
  assert.equal(line.id, 'mcp-fs');
47
- assert.equal(line.name, 'dsh-mcp-client');
47
+ assert.equal(line.name, '@deepseek-ai/dsh-mcp-client', '宿主按 bundle id 解析 name,裸名不保证被接受(#133)');
48
+ assert.equal((line.config as Record<string, unknown>)['transport'], 'stdio', 'stdio 必须显式写 transport(此前只能靠 url 缺省猜)');
48
49
  assert.equal((line.config as Record<string, unknown>)['command'], 'npx');
50
+
51
+ const http = buildMcpPatchLine('mcp-remote', { serverName: 'remote', type: 'streamable-http', url: 'https://mcp.example.com/sse' });
52
+ const httpConfig = http.config as Record<string, unknown>;
53
+ assert.equal(httpConfig['transport'], 'streamable-http');
54
+ assert.equal(httpConfig['url'], 'https://mcp.example.com/sse');
55
+ });
56
+
57
+ test('mcp: extractMcpServers 以 transport 为准,缺该字段的旧行才回落 url 猜测', () => {
58
+ const withTransport = extractMcpServers([{
59
+ lineId: 'mcp-stdio-with-url',
60
+ raw: { id: 'mcp-stdio-with-url', name: '@deepseek-ai/dsh-mcp-client', config: { serverName: 's1', transport: 'stdio', command: 'node', url: 'http://127.0.0.1:1/mcp' } },
61
+ }]);
62
+ assert.equal(withTransport[0]?.type, 'stdio', 'transport 在就不该被 url 覆盖');
63
+
64
+ const legacy = extractMcpServers([{
65
+ lineId: 'legacy',
66
+ raw: { id: 'legacy', name: 'dsh-mcp-client', config: { serverName: 's2', url: 'https://mcp.example.com/sse' } },
67
+ }]);
68
+ assert.equal(legacy[0]?.type, 'streamable-http', '没有 transport 的旧行仍按原口径回落');
49
69
  });
50
70
 
51
71
  test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 patch(needsRestart)', async () => {
@@ -69,7 +89,7 @@ test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 pa
69
89
  assert.equal(r.ok, true);
70
90
  assert.equal(r.needsRestart, true, 'MCP 写 patch 必须重启生效');
71
91
  assert.ok(dst.patchFile.lines.has('mcp-fs'));
72
- assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], 'dsh-mcp-client');
92
+ assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], '@deepseek-ai/dsh-mcp-client');
73
93
 
74
94
  // 幂等:同 serverName 同内容 → Skip
75
95
  items = await adapter.analyzeImport(exported.data, makeImportContext(dst, sections));
@@ -65,7 +65,8 @@ export function extractMcpServers(lines: { lineId: string; raw: unknown; file?:
65
65
  const c = config as Record<string, unknown>;
66
66
  const serverName = c['serverName'];
67
67
  if (typeof serverName !== 'string' || serverName === '') continue;
68
- const type = typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio';
68
+ // transport 优先(写回时一定有);老行没有该字段才回落「有 url = 远程」的猜测
69
+ const type = mcpTransportOf(c) ?? (typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio');
69
70
  servers.push({
70
71
  serverName,
71
72
  type,
@@ -107,6 +108,12 @@ export function stripMcpEntries(raw: unknown): unknown | undefined {
107
108
  return isMcpEntry(single[0]) ? undefined : raw;
108
109
  }
109
110
 
111
+ /** `config.transport` 的合法取值;读不出来(缺字段/写错)返回 undefined,由调用方回落 url 判定。 */
112
+ function mcpTransportOf(c: Record<string, unknown>): McpServerEntry['type'] | undefined {
113
+ const transport = c['transport'];
114
+ return transport === 'stdio' || transport === 'streamable-http' ? transport : undefined;
115
+ }
116
+
110
117
  /** 单个 patch entry 是否是 MCP 服务器行(与 extractMcpServers 的判定同口径) */
111
118
  function isMcpEntry(entry: unknown): boolean {
112
119
  if (entry === null || typeof entry !== 'object') return false;
@@ -131,9 +138,22 @@ function entriesOf(raw: unknown): { id?: unknown; name?: unknown; config?: unkno
131
138
  return [];
132
139
  }
133
140
 
134
- /** 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致) */
141
+ /**
142
+ * MCP server 行的包名(bundle id,**必须带 scope**)。
143
+ *
144
+ * 宿主按 bundle id 解析 patch 行的 `name`;裸名 `dsh-mcp-client` 是否被归一化未经验证,
145
+ * 而用户机上的真实行都是 `@deepseek-ai/dsh-mcp-client`(issue #133 报告的原始行)。
146
+ */
147
+ const MCP_BUNDLE_NAME = '@deepseek-ai/dsh-mcp-client';
148
+
149
+ /**
150
+ * 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致)。
151
+ *
152
+ * `config.transport` 必须显式写:读侧靠它判定 server 类型,只在「没有 transport 的旧行」
153
+ * 上才回落 url 猜测(issue #133:此前写回丢了这个字段,stdio/http 只能靠 url 有没有值猜)。
154
+ */
135
155
  export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Record<string, unknown> {
136
- const config: Record<string, unknown> = { serverName: server.serverName };
156
+ const config: Record<string, unknown> = { serverName: server.serverName, transport: server.type };
137
157
  if (server.type === 'streamable-http') {
138
158
  config['url'] = server.url;
139
159
  if (server.headers !== undefined) config['headers'] = server.headers;
@@ -143,7 +163,7 @@ export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Recor
143
163
  if (server.env !== undefined) config['env'] = server.env;
144
164
  if (server.cwd !== undefined) config['cwd'] = server.cwd;
145
165
  }
146
- return { id: lineId, name: 'dsh-mcp-client', config };
166
+ return { id: lineId, name: MCP_BUNDLE_NAME, config };
147
167
  }
148
168
 
149
169
  /** 连接器计划项的 id 前缀(导入时按前缀分派到 applyConnectorItem) */
@@ -168,6 +168,16 @@ export class MemPlugins implements PluginsFacade {
168
168
  this.installed.set(pkg, { name: pkg, version: '1.0.0', enabled: true, spec });
169
169
  return { needsRestart: true };
170
170
  }
171
+ /** 测试钩子:卸载失败(模拟 desktop 保留档案被 CLI 拒绝) */
172
+ failUninstall = false;
173
+ /** 最近一次 uninstall 收到的包名(验证只删该删的那个) */
174
+ lastUninstalled: string | undefined;
175
+ async uninstall(pkg: string): Promise<{ needsRestart: boolean }> {
176
+ if (this.failUninstall) throw new Error(`profile "desktop" is managed exclusively by the Electron application`);
177
+ this.lastUninstalled = pkg;
178
+ this.installed.delete(pkg);
179
+ return { needsRestart: true };
180
+ }
171
181
  }
172
182
 
173
183
  export class MemWorkspace implements WorkspaceFacade {
@@ -1208,7 +1208,7 @@ export interface RestorePlanView {
1208
1208
 
1209
1209
  /** 危险动作判定:会改动磁盘的分区(skip / credentialHint 不算)。 */
1210
1210
  function isDangerousRestoreKind(kind: string): boolean {
1211
- return kind === 'hostFileRestore' || kind === 'hostFileRemove' || kind === 'fileRestore' || kind === 'fileRemove' || kind === 'pluginRemove'
1211
+ return kind === 'hostFileRestore' || kind === 'hostFileRemove' || kind === 'fileRestore' || kind === 'fileRemove' || kind === 'pluginRemove' || kind === 'pluginInstall'
1212
1212
  }
1213
1213
 
1214
1214
  /** 本机 DSH 包名(T8-F3;与 core/restore.ts 的 `DSH_PACKAGE_NAME` 同值 —— 两处读的是同一个文件)。 */
@@ -163,6 +163,7 @@ const MOVE_PINS: readonly MovePin[] = [
163
163
  { key: 'mode.encryptHint', file: 'src/client/sync/SecurityOptionsCard.tsx', kind: '机制' },
164
164
  { key: 'mode.encryptAutosyncNotice', file: 'src/client/sync/SecurityOptionsCard.tsx', kind: '边界' },
165
165
  { key: 'mode.includeSecretsHint', file: 'src/client/sync/SecurityOptionsCard.tsx', kind: '机制' },
166
+ { key: 'mode.deletePluginsHint', file: 'src/client/sync/SyncSectionPickerDialog.tsx', kind: '边界' },
166
167
  { key: 'mode.passwordSavedHint', file: 'src/client/sync/SecurityOptionsCard.tsx', kind: '机制' },
167
168
  { key: 'mode.decryptPasswordHint', file: 'src/client/sync/DecryptPasswordCard.tsx', kind: '机制' },
168
169
  { key: 'export.encryptHint', file: 'src/client/export/ExportView.tsx', kind: '机制' },
@@ -400,7 +401,7 @@ test('t6-1 MOVE:79 个说明键都已收进 ⓘ(逐字复用原键)且不
400
401
  // 2026-11-01:删掉「改动即时生效并保存」「分区选择已保存到本机」两处 ⓘ(用户要求,
401
402
  // 属解释「用户无从选择的事」的废话)⇒ 81 降到 79(不是删检查项)。
402
403
  // 2026-11-01:导入选择页的「从其它 agent 导入」按钮与其 ⓘ 一并移除(首页已有直达入口)⇒ 79 降到 78。
403
- assert.ok(MOVE_PINS.length === 78, 'MOVE 清单长度应为 78(实际 ' + String(MOVE_PINS.length) + ')');
404
+ assert.ok(MOVE_PINS.length === 79, 'MOVE 清单长度应为 79(实际 ' + String(MOVE_PINS.length) + ')');
404
405
  assert.ok(
405
406
  MOVE_PINS.filter((p) => p.kind === '输入规则').length >= 5,
406
407
  '输入规则类 MOVE 至少 5 处(config.repoUrlHint / webdav.urlHint / mode.sessionsLimitHint / retention.keep*Hint / export.fileNameHint)',
@@ -1009,13 +1009,14 @@ test('低频面板: 同步/市场/快照切片与当前面板刷新往返恢复
1009
1009
  createdAt: '2026-01-01T00:00:00Z',
1010
1010
  sourceZip: 'x.zip',
1011
1011
  actions: [],
1012
- summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 1 },
1012
+ summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 1 },
1013
1013
  pluginBaselineConfirmed: true,
1014
1014
  },
1015
1015
  report: {
1016
1016
  snapshotId: 'snap-1',
1017
1017
  restored: ['settings.yaml'],
1018
1018
  removedPlugins: [],
1019
+ installedPlugins: [],
1019
1020
  manualHints: [],
1020
1021
  failed: [],
1021
1022
  skipped: [],
@@ -1223,6 +1224,7 @@ test('m2-resume: 活跃 restore run 经 /runs 恢复 running 并轮询到完成
1223
1224
  snapshotId: 'snap-1',
1224
1225
  restored: ['settings.yaml'],
1225
1226
  removedPlugins: ['@scope/pkg'],
1227
+ installedPlugins: [],
1226
1228
  manualHints: [],
1227
1229
  failed: [],
1228
1230
  skipped: [],
@@ -1519,7 +1521,7 @@ test('P0-9: 宿主载荷(plan/analysis/result/confirmSession/snapshots.plan/ma
1519
1521
  detail: `MCP_TOKEN=${P0_9_SECRET}`, manualHint: `Authorization: Bearer ${P0_9_SECRET}`,
1520
1522
  }],
1521
1523
  summary: {
1522
- hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0,
1524
+ hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0,
1523
1525
  fileRestores: 0, fileRemoves: 0, credentialHints: 1, skips: 0,
1524
1526
  },
1525
1527
  pluginBaselineConfirmed: true,
@@ -1617,9 +1619,9 @@ test('P0-9: 持久化字段清单显式化(键集合断言 —— 新增字段
1617
1619
  'loadError', 'pullReport', 'pushPreview', 'pushReport', 'repoUrl', 'webdavUrl', 'webdavUsername',
1618
1620
  ])
1619
1621
  assert.deepEqual(keys(p.sync.byChannel.git), [
1620
- 'autosync', 'autosyncEnabled', 'autosyncInterval', 'autosyncRealtime', 'encrypt', 'includeSecrets',
1621
- 'loadingSnapshots', 'selectedSnapshotId', 'sessionsInclude', 'sessionsLimit', 'snapshots',
1622
- 'syncMode', 'syncSections',
1622
+ 'autosync', 'autosyncEnabled', 'autosyncInterval', 'autosyncRealtime', 'deletePlugins', 'encrypt',
1623
+ 'includeSecrets', 'loadingSnapshots', 'selectedSnapshotId', 'sessionsInclude', 'sessionsLimit',
1624
+ 'snapshots', 'syncMode', 'syncSections',
1623
1625
  ])
1624
1626
  assert.deepEqual(keys(p.market), [
1625
1627
  'category', 'conflictResolutions', 'detail', 'error', 'importResult', 'items', 'loadError',