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
@@ -0,0 +1,116 @@
1
+ /**
2
+ * issue #132 undo 面:跟远端删掉插件的**反向补偿** —— 快照里记录过 pluginRemovals 的包,
3
+ * 恢复时若本机已缺就装回(复现被删的那一版),本机已存在则跳过。
4
+ *
5
+ * 为什么只认快照里记录过的名字、不按 beforePlugins 反推「缺了就是被删了」:
6
+ * 手动卸载 / 换包也会让基线里的名字消失,按差集重装等于替用户改主意(判据见 planRestore 的 2') 段)。
7
+ */
8
+ import test from 'node:test';
9
+ import assert from 'node:assert/strict';
10
+ import fssync from 'node:fs';
11
+ import fs from 'node:fs/promises';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+
15
+ import { planRestore, restore } from './restore.ts';
16
+ import type { Snapshot } from './types.ts';
17
+
18
+ const SNAP_ID = 'snap-132-plugin-install';
19
+ const PKG = '@deepseek-ai/dsh-ssh';
20
+ const VERSION = '1.0.0';
21
+ const TARGET = `${PKG}@${VERSION}`;
22
+
23
+ interface Fixture {
24
+ homeDir: string;
25
+ snapshotDir: string;
26
+ profileDir: string;
27
+ }
28
+
29
+ function workdir(t: test.TestContext): string {
30
+ const dir = fssync.mkdtempSync(path.join(os.tmpdir(), 'dsh-cm-132-install-'));
31
+ t.after(() => fssync.rmSync(dir, { recursive: true, force: true }));
32
+ return dir;
33
+ }
34
+
35
+ /** 快照目录:无 entries / 无 hostFileBackups、基线为空(→ 不会产出 pluginRemove),只有 pluginRemovals。 */
36
+ async function makeFixture(workDir: string): Promise<Fixture> {
37
+ const homeDir = path.join(workDir, 'home');
38
+ const profileDir = path.join(homeDir, 'profiles', 'web');
39
+ const snapshotDir = path.join(workDir, 'data', 'snapshots', SNAP_ID);
40
+ await fs.mkdir(path.join(snapshotDir, 'blobs', 'host'), { recursive: true });
41
+ await fs.mkdir(profileDir, { recursive: true });
42
+ const snapshot: Snapshot = {
43
+ id: SNAP_ID,
44
+ createdAt: '2026-11-10T00:00:00.000Z',
45
+ sourceZip: 'audit.zip',
46
+ entries: [],
47
+ status: 'done',
48
+ beforePlugins: [],
49
+ hostFileBackups: [],
50
+ pluginRemovals: [{ name: PKG, version: VERSION, target: TARGET }],
51
+ };
52
+ await fs.writeFile(path.join(snapshotDir, 'snapshot.json'), JSON.stringify(snapshot, null, 2), 'utf8');
53
+ return { homeDir, snapshotDir, profileDir };
54
+ }
55
+
56
+ async function writeInstalledProfile(profileDir: string, deps: Record<string, string>): Promise<void> {
57
+ await fs.writeFile(
58
+ path.join(profileDir, 'package.json'),
59
+ `${JSON.stringify({ name: 'dsh-profile-web', dependencies: deps }, null, 2)}\n`,
60
+ 'utf8',
61
+ );
62
+ }
63
+
64
+ test('132-R1 记录过跟删的包在本机缺失 → 计划出 pluginInstall(target=name、pluginTarget=name@version)', async (t) => {
65
+ const f = await makeFixture(workdir(t));
66
+ const plan = await planRestore({ snapshotDir: f.snapshotDir, homeDir: f.homeDir, profile: 'web' });
67
+
68
+ const installs = plan.actions.filter((a) => a.kind === 'pluginInstall');
69
+ assert.equal(installs.length, 1, '应恰好规划一条重装动作');
70
+ assert.equal(installs[0]!.target, PKG);
71
+ assert.equal(installs[0]!.pluginName, PKG);
72
+ assert.equal(installs[0]!.pluginTarget, TARGET, '重装目标必须钉住被删时的版本');
73
+ assert.equal(plan.summary.pluginInstalls, 1);
74
+ assert.equal(plan.summary.pluginRemoves, 0, '基线为空且本机无任何已装 ⇒ 不应产出卸载');
75
+ });
76
+
77
+ test('132-R2 本机已装回(profile dependencies 里有该包)→ 计划转成 skip,不重复装', async (t) => {
78
+ const f = await makeFixture(workdir(t));
79
+ await writeInstalledProfile(f.profileDir, { [PKG]: '^1.0.0' });
80
+
81
+ const plan = await planRestore({ snapshotDir: f.snapshotDir, homeDir: f.homeDir, profile: 'web' });
82
+ assert.equal(plan.actions.filter((a) => a.kind === 'pluginInstall').length, 0);
83
+ assert.equal(plan.summary.pluginInstalls, 0);
84
+ assert.ok(
85
+ plan.actions.some((a) => a.kind === 'skip' && a.description.includes(PKG)),
86
+ '已装应留下一条带包名的 skip 说明',
87
+ );
88
+ });
89
+
90
+ test('132-R3 执行面:重装成功进 report.installedPlugins,失败进 report.failed 且不静默', async (t) => {
91
+ const f = await makeFixture(workdir(t));
92
+ const seen: string[] = [];
93
+ const okReport = await restore({
94
+ snapshotDir: f.snapshotDir,
95
+ homeDir: f.homeDir,
96
+ profile: 'web',
97
+ pluginInstaller: async (name, target) => {
98
+ seen.push(`${name}=>${target}`);
99
+ return { ok: true };
100
+ },
101
+ });
102
+ assert.deepEqual(seen, [`${PKG}=>${TARGET}`], '重装器必须收到包名与被删版本组成的 target');
103
+ assert.deepEqual(okReport.installedPlugins, [TARGET]);
104
+ assert.deepEqual(okReport.failed, []);
105
+
106
+ const failReport = await restore({
107
+ snapshotDir: f.snapshotDir,
108
+ homeDir: f.homeDir,
109
+ profile: 'web',
110
+ pluginInstaller: async () => ({ ok: false, message: 'dsh plugin add 失败:registry 不可达' }),
111
+ });
112
+ assert.deepEqual(failReport.installedPlugins, []);
113
+ assert.equal(failReport.failed.length, 1);
114
+ assert.equal(failReport.failed[0]!.item, `plugin:${PKG}`);
115
+ assert.match(failReport.failed[0]!.reason, /registry 不可达/);
116
+ });
@@ -32,8 +32,14 @@ const WAL_KINDS: ReadonlySet<string> = new Set([
32
32
  'fileRestore',
33
33
  'fileRemove',
34
34
  'pluginRemove',
35
+ 'pluginInstall',
35
36
  ]);
36
37
 
38
+ /** 插件类动作 = 外部副作用(不带文件指纹;reconcile 恒走保守分支)。 */
39
+ export function isExternalPluginKind(kind: string): boolean {
40
+ return kind === 'pluginRemove' || kind === 'pluginInstall';
41
+ }
42
+
37
43
  export function isWalActionKind(kind: string): boolean {
38
44
  return WAL_KINDS.has(kind);
39
45
  }
@@ -113,8 +119,8 @@ export function createRestoreWal(journal: RestoreJournalPort | undefined): Resto
113
119
  out.push(undefined);
114
120
  continue;
115
121
  }
116
- // 插件卸载:外部副作用,刻意不带指纹(probeExternal 会得 unknown → 保守)。
117
- const external = entry.kind === 'pluginRemove';
122
+ // 插件装卸:外部副作用,刻意不带指纹(probeExternal 会得 unknown → 保守)。
123
+ const external = isExternalPluginKind(entry.kind);
118
124
  const ref = external ? '' : (entry.abs ?? '');
119
125
  const beforeFp = external ? null : await restoreFingerprint(entry.abs);
120
126
  const id = stepIdOf(entry, ref);
@@ -163,7 +169,7 @@ export function restoreStepId(kind: string, subject: string): string {
163
169
 
164
170
  /** step id 的 subject 段:插件卸载用包名,其余用绝对路径(拿不到绝对路径时退回流相对 target)。 */
165
171
  export function restoreWalSubject(kind: string, pluginName: string | undefined, refOrTarget: string): string {
166
- return kind === 'pluginRemove' ? (pluginName ?? refOrTarget) : refOrTarget;
172
+ return isExternalPluginKind(kind) ? (pluginName ?? refOrTarget) : refOrTarget;
167
173
  }
168
174
 
169
175
  function stepIdOf(entry: RestoreWalEntry, ref: string): string {
@@ -175,7 +181,7 @@ export function restoreActionStepId(
175
181
  action: { kind: string; target?: string; pluginName?: string },
176
182
  abs: string | null,
177
183
  ): string {
178
- const ref = action.kind === 'pluginRemove' ? '' : (abs ?? '');
184
+ const ref = isExternalPluginKind(action.kind) ? '' : (abs ?? '');
179
185
  return restoreStepId(action.kind, restoreWalSubject(action.kind, action.pluginName, ref || (action.target ?? '')));
180
186
  }
181
187
 
@@ -196,7 +202,7 @@ export function collectRestoreWalEntries<A extends { kind: string; target?: stri
196
202
  kind: action.kind,
197
203
  ...(action.target !== undefined ? { target: action.target } : {}),
198
204
  ...(action.pluginName !== undefined ? { pluginName: action.pluginName } : {}),
199
- abs: action.kind === 'pluginRemove' || action.target === undefined ? null : absOf(action),
205
+ abs: isExternalPluginKind(action.kind) || action.target === undefined ? null : absOf(action),
200
206
  });
201
207
  }
202
208
  return { mutating, entries };
@@ -212,7 +218,7 @@ export function restoreWalHandlesFromSteps(
212
218
  ): (RestoreWalHandle | undefined)[] {
213
219
  return entries.map((entry) => {
214
220
  if (!isWalActionKind(entry.kind)) return undefined;
215
- const external = entry.kind === 'pluginRemove';
221
+ const external = isExternalPluginKind(entry.kind);
216
222
  const ref = external ? '' : (entry.abs ?? '');
217
223
  const id = restoreStepId(entry.kind, restoreWalSubject(entry.kind, entry.pluginName, ref || (entry.target ?? '')));
218
224
  const known = steps[id];
@@ -34,7 +34,7 @@ import {
34
34
  classifyDshPluginFailure, readInstalled, readInstalledVersion, resolveProfileDir, runDshPlugin,
35
35
  } from './plugin-cli.ts';
36
36
  import {
37
- collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps,
37
+ collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps,
38
38
  } from './restore-wal.ts';
39
39
  import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from './restore-wal.ts';
40
40
  import type { RestoreResumeHint } from './restore-resume.ts';
@@ -50,6 +50,7 @@ export type RestoreActionKind =
50
50
  | 'hostFileRestore' // 宿主整文件 blob → 写回 $DSH_HOME
51
51
  | 'hostFileRemove' // 快照时不存在、现已出现的宿主文件 → 删除
52
52
  | 'pluginRemove' // 导入期间新增插件 → dsh plugin remove
53
+ | 'pluginInstall' // 跟远端删插件的反向:快照记录了删过、本机现在缺 → dsh plugin add 装回
53
54
  | 'fileRestore' // file 类条目 blob → 写回原路径
54
55
  | 'fileRemove' // file 类条目快照时不存在 → 删除导入写入的文件
55
56
  | 'credentialHint' // 凭据值不可回读 → 人工补录提示(无自动动作)
@@ -63,8 +64,10 @@ export interface RestoreAction {
63
64
  target?: string;
64
65
  /** hostFileRestore/fileRestore:快照内 blob 相对路径(相对 snapshotDir) */
65
66
  blobPath?: string;
66
- /** pluginRemove:插件包名 */
67
+ /** pluginRemove / pluginInstall:插件包名 */
67
68
  pluginName?: string;
69
+ /** pluginInstall:重装目标(name@version;版本未知时就是裸包名) */
70
+ pluginTarget?: string;
68
71
  /** credentialHint:人工提示文本 */
69
72
  manualHint?: string;
70
73
  /** 附加说明(旧快照缺基线 / 离线无法恢复等) */
@@ -82,6 +85,7 @@ export interface RestorePlan {
82
85
  hostFileRestores: number;
83
86
  hostFileRemoves: number;
84
87
  pluginRemoves: number;
88
+ pluginInstalls: number;
85
89
  fileRestores: number;
86
90
  fileRemoves: number;
87
91
  credentialHints: number;
@@ -122,6 +126,13 @@ export interface RestoreOptions {
122
126
  pluginUninstaller?: (
123
127
  name: string, profileDir: string, profile: string,
124
128
  ) => Promise<{ ok: boolean; message?: string }>;
129
+ /**
130
+ * 注入式插件重装器(issue #132 undo;测试用)。缺省走官方 `dsh plugin add <name>@<version>`。
131
+ * 只用于「快照记录过跟删、本机现在缺失」的插件;未记录过的插件绝不重装。
132
+ */
133
+ pluginInstaller?: (
134
+ name: string, target: string, profileDir: string, profile: string,
135
+ ) => Promise<{ ok: boolean; message?: string }>;
125
136
  /** 每项动作执行回调(宿主路由埋点:更新 RunRegistry 进度;index/1-based、total=计划动作数、
126
137
  * detail=动作描述。dry-run/planRestore 不触发) */
127
138
  onAction?: (info: { index: number; total: number; detail: string }) => void;
@@ -163,6 +174,8 @@ export interface RestoreReport {
163
174
  restored: string[];
164
175
  /** 已卸载的插件名 */
165
176
  removedPlugins: string[];
177
+ /** 已按 undo 记录装回的插件目标(name@version;issue #132) */
178
+ installedPlugins: string[];
166
179
  /** 需人工处理的提示(凭据补录等) */
167
180
  manualHints: string[];
168
181
  /** 失败清单 */
@@ -440,6 +453,26 @@ async function defaultPluginUninstaller(
440
453
  return { ok: false, message: msg('restore.uninstallFailedExit', { name, code: String(result.exitCode), tail }) };
441
454
  }
442
455
 
456
+ /**
457
+ * 默认插件重装器(issue #132 undo):官方 dsh plugin add 通道 + 失败分类诊断。
458
+ *
459
+ * 与卸载器同口径:非 0 退出先归类(已知失败码给准确文案),否则回落到退出码 + 输出尾部。
460
+ * 绝不在这里做版本回退/猜测 —— target 就是快照里记下的 `name@version`。
461
+ */
462
+ async function defaultPluginInstaller(
463
+ name: string, target: string, profileDir: string, profile: string, msg: MsgFunc,
464
+ ): Promise<{ ok: boolean; message?: string }> {
465
+ const result = await runDshPlugin(profileDir, profile, ['add', target]);
466
+ if (result.exitCode === 0) return { ok: true };
467
+ const output = `${result.stderr}\n${result.stdout}`.trim();
468
+ const failure = classifyDshPluginFailure(output);
469
+ if (failure !== null) {
470
+ return { ok: false, message: msg('restore.installFailedCode', { name, code: failure.code, message: failure.message }) };
471
+ }
472
+ const tail = output.split('\n').slice(-8).join('\n') || msg('restore.noOutput');
473
+ return { ok: false, message: msg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) };
474
+ }
475
+
443
476
  /* -------------------------------------------------- 统一恢复校验(Phase 4 F8/F9/F25) */
444
477
 
445
478
  /**
@@ -704,6 +737,30 @@ export async function planRestore(opts: RestoreOptions): Promise<RestorePlan> {
704
737
  }
705
738
  }
706
739
 
740
+ // 2') 插件重装(issue #132 跟远端删插件的反向):只认快照里**明确记录过**的跟删项。
741
+ // 为什么不按 beforePlugins 反推「缺了就是被删了」:手动卸载/换包也会让基线里的名字消失,
742
+ // 那种情况下重装是替用户改主意。记录过的才装回;现在已存在的直接跳过。
743
+ const recordedRemovals = snapshot.pluginRemovals ?? [];
744
+ if (recordedRemovals.length > 0) {
745
+ const installed = readInstalled(profileDir);
746
+ for (const removal of recordedRemovals) {
747
+ if (Object.hasOwn(installed, removal.name)) {
748
+ actions.push({
749
+ kind: 'skip',
750
+ description: msg('restore.pluginInstallAlreadyPresent', { name: removal.name }),
751
+ });
752
+ continue;
753
+ }
754
+ actions.push({
755
+ kind: 'pluginInstall',
756
+ description: msg('restore.pluginInstall', { name: removal.name, version: removal.version }),
757
+ target: removal.name,
758
+ pluginName: removal.name,
759
+ pluginTarget: removal.target,
760
+ });
761
+ }
762
+ }
763
+
707
764
  // 3) file 类条目补偿 + credentials 提示(聚合计数供报告)
708
765
  let namespaceCount = 0;
709
766
  let patchLineCount = 0;
@@ -860,7 +917,7 @@ export async function planRestore(opts: RestoreOptions): Promise<RestorePlan> {
860
917
 
861
918
  function summarizeActions(actions: RestoreAction[]): RestorePlan['summary'] {
862
919
  const summary: RestorePlan['summary'] = {
863
- hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0,
920
+ hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0,
864
921
  fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0,
865
922
  };
866
923
  for (const a of actions) {
@@ -868,6 +925,7 @@ function summarizeActions(actions: RestoreAction[]): RestorePlan['summary'] {
868
925
  case 'hostFileRestore': summary.hostFileRestores += 1; break;
869
926
  case 'hostFileRemove': summary.hostFileRemoves += 1; break;
870
927
  case 'pluginRemove': summary.pluginRemoves += 1; break;
928
+ case 'pluginInstall': summary.pluginInstalls += 1; break;
871
929
  case 'fileRestore': summary.fileRestores += 1; break;
872
930
  case 'fileRemove': summary.fileRemoves += 1; break;
873
931
  case 'credentialHint': summary.credentialHints += 1; break;
@@ -892,11 +950,14 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
892
950
  const profileDir = resolveProfileDir(homeDir, profile);
893
951
  const uninstaller = opts.pluginUninstaller
894
952
  ?? ((name: string, dir: string, prof: string) => defaultPluginUninstaller(name, dir, prof, msg));
953
+ const installer = opts.pluginInstaller
954
+ ?? ((name: string, target: string, dir: string, prof: string) => defaultPluginInstaller(name, target, dir, prof, msg));
895
955
 
896
956
  const report: RestoreReport = {
897
957
  snapshotId: plan.snapshotId,
898
958
  restored: [],
899
959
  removedPlugins: [],
960
+ installedPlugins: [],
900
961
  manualHints: [],
901
962
  failed: [],
902
963
  skipped: [],
@@ -936,7 +997,7 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
936
997
  }
937
998
  /** 文件类动作的绝对目标(reconcile 直接拿它读盘算指纹);插件卸载/越界目标 → null(不可指纹)。 */
938
999
  function walAbsOf(action: RestoreAction): string | null {
939
- if (action.kind === 'pluginRemove' || action.target === undefined) return null;
1000
+ if (isExternalPluginKind(action.kind) || action.target === undefined) return null;
940
1001
  try {
941
1002
  return homeAbs(homeDir, action.target, msg);
942
1003
  } catch {
@@ -1013,6 +1074,20 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
1013
1074
  }
1014
1075
  break;
1015
1076
  }
1077
+ case 'pluginInstall': {
1078
+ const target = action.pluginTarget ?? action.pluginName!;
1079
+ const result = await installer(action.pluginName!, target, profileDir, profile);
1080
+ if (result.ok) {
1081
+ report.installedPlugins.push(target);
1082
+ } else {
1083
+ const reason = result.message ?? msg('restore.pluginInstallFailed');
1084
+ report.failed.push({ item: `plugin:${action.pluginName}`, reason });
1085
+ // 同卸载分支:外部副作用没做成 → attention(绝不记 done)
1086
+ settleStatus = 'attention';
1087
+ settleMessage = reason;
1088
+ }
1089
+ break;
1090
+ }
1016
1091
  case 'credentialHint':
1017
1092
  report.manualHints.push(action.manualHint ?? action.description);
1018
1093
  break;
@@ -113,6 +113,11 @@ class MemPlugins implements PluginsFacade {
113
113
  this.installed.set(pkg, { name: pkg, version: '1.0.0', enabled: true });
114
114
  return { needsRestart: true };
115
115
  }
116
+ /** issue #132:卸载(跟随远端删除);缺失即抛,模拟真实 CLI 的失败语义。 */
117
+ async uninstall(pkg: string) {
118
+ if (!this.installed.delete(pkg)) throw new Error(`plugin ${pkg} is not installed`);
119
+ return { needsRestart: true };
120
+ }
116
121
  }
117
122
 
118
123
  class MemWorkspace implements WorkspaceFacade {
@@ -52,7 +52,7 @@ function planWith(actions: RestorePlan['actions']): RestorePlan {
52
52
  createdAt: '2026-09-21T00:00:00.000Z',
53
53
  sourceZip: 'x.zip',
54
54
  pluginBaselineConfirmed: true,
55
- summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0 },
55
+ summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0 },
56
56
  actions,
57
57
  };
58
58
  }
@@ -139,6 +139,7 @@ function statusOf(kind: RestoreActionKind, beforeExists: boolean): SnapshotChang
139
139
  case 'fileRemove':
140
140
  return 'deleted';
141
141
  case 'pluginRemove':
142
+ case 'pluginInstall':
142
143
  return 'plugin';
143
144
  case 'credentialHint':
144
145
  return 'hint';
@@ -293,7 +294,7 @@ export async function summarizeRestoreChanges(opts: {
293
294
  entries.push(entry);
294
295
  continue;
295
296
  }
296
- if (action.kind === 'pluginRemove') entry.status = 'plugin';
297
+ if (action.kind === 'pluginRemove' || action.kind === 'pluginInstall') entry.status = 'plugin';
297
298
  else if (action.kind === 'credentialHint') entry.status = 'hint';
298
299
  else entry.status = 'skip';
299
300
  entries.push(entry);
package/src/core/types.ts CHANGED
@@ -259,6 +259,14 @@ export interface PluginsFacade {
259
259
  * signal 可选:中止时宿主应 kill 子进程并清理半装状态(恢复 package.json + 删 node_modules/<pkg>)。
260
260
  */
261
261
  install(pkg: string, target?: string, signal?: AbortSignal): Promise<{ needsRestart: boolean; installedVersion?: string | null }>;
262
+ /**
263
+ * 卸载插件(issue #132 跟随远端删除;`dsh plugin remove <pkg>`)。
264
+ *
265
+ * 失败即抛(消息经 `classifyDshPluginFailure` 给出可操作诊断,例如 desktop 保留档案被 CLI 拒绝)。
266
+ * 调用方逐项记录 warning、**不阻断**其余项:一次卸载失败不该让整轮同步回滚。
267
+ * `signal` 中止语义与 install 一致(宿主 kill 子进程)。
268
+ */
269
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{ needsRestart: boolean }>;
262
270
  }
263
271
 
264
272
  export interface WorkspaceFacade {
@@ -1021,6 +1029,21 @@ export interface HostFileBackup {
1021
1029
  unreadable?: boolean;
1022
1030
  }
1023
1031
 
1032
+ /**
1033
+ * 一轮同步里**跟随远端删除**掉的插件(issue #132)。
1034
+ *
1035
+ * 为什么写进快照:undo 必须能把用户装回去 —— 删插件是不可逆的外部副作用,只有快照记得
1036
+ * 「删的是谁、哪个版本」。有意**不进** computeMetadataHash(它只覆盖 entries/hostFileBackups/
1037
+ * beforePlugins 三样破坏性内容),因此记录它不需要重写 manifest 与 blob。
1038
+ */
1039
+ export interface SnapshotPluginRemoval {
1040
+ name: string;
1041
+ /** 删除时本机已装的版本(快照记的是事实;重装用 target = name@version) */
1042
+ version: string;
1043
+ /** 重装目标(name@version;版本未知时就是裸包名) */
1044
+ target: string;
1045
+ }
1046
+
1024
1047
  export interface Snapshot {
1025
1048
  id: string;
1026
1049
  createdAt: string;
@@ -1030,6 +1053,8 @@ export interface Snapshot {
1030
1053
  status?: SnapshotStatus;
1031
1054
  /** 导入前已安装插件清单(M2 restore 撤销插件时与当前已装对比)。旧快照缺省 */
1032
1055
  beforePlugins?: PluginInfo[];
1056
+ /** 本轮跟随远端删除的插件(issue #132;restore 计划里对称地重装)。旧快照缺省 */
1057
+ pluginRemovals?: SnapshotPluginRemoval[];
1033
1058
  /** 宿主整文件备份(settings.yaml / settings.json / cordis.patch.yml / profiles/<p>/cordis.patch.yml)。旧快照缺省 */
1034
1059
  hostFileBackups?: HostFileBackup[];
1035
1060
  /**
@@ -1079,6 +1104,12 @@ export interface SnapshotStore {
1079
1104
  readBlob(id: string, blobPath: string): Promise<Uint8Array>;
1080
1105
  /** 标记快照生命周期状态(导入成功→done;失败回滚→rolled-back;持久化由实现负责) */
1081
1106
  updateStatus(id: string, status: SnapshotStatus): Promise<void>;
1107
+ /**
1108
+ * 记录「本轮跟删掉的插件」(issue #132):只重写 snapshot.json 的这一个字段,
1109
+ * 不动 manifest 与 blob(它不在 metadataHash 覆盖面内)。不可用时调用方**跳过记录**并靠
1110
+ * 报告里的重装目标人工兜底,绝不因为记不上就中止同步。
1111
+ */
1112
+ recordPluginRemovals?(id: string, removals: SnapshotPluginRemoval[]): Promise<void>;
1082
1113
  }
1083
1114
 
1084
1115
  /**
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import test from 'node:test';
12
12
  import assert from 'node:assert/strict';
13
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
 
@@ -1002,3 +1002,85 @@ test('#75 不存在的层仍按「本来就没有」处理(ENOENT 不是错误
1002
1002
  cleanup()
1003
1003
  }
1004
1004
  })
1005
+
1006
+ /* --------------------- issue #133:顶层行 ≠ `- insert:` 块(摊平事故) --------------------- */
1007
+
1008
+ /**
1009
+ * 真机形态:顶层行 + `- insert:` 块 + 手写注释。宿主合并循环里顶层行按 id **覆盖**(查不到就
1010
+ * `patch: entry "X" not found` 丢弃),只有 insert 块成员是**新增** —— 所以这两种形态在
1011
+ * 语义上不等价,重建时必须原样分流。
1012
+ */
1013
+ const INSERT_BLOCK_YAML = [
1014
+ '# 手写注释(重建后本来就不保留,这里只用来确认真机形态)',
1015
+ '- id: llm-pi-ai',
1016
+ ' name: "@deepseek-ai/dsh-llm-pi-ai"',
1017
+ '- insert:',
1018
+ ' - id: mcp-a',
1019
+ ' name: dsh-mcp-client',
1020
+ ' config:',
1021
+ ' transport: stdio',
1022
+ ' command: npx',
1023
+ '- id: plain-plugin',
1024
+ ' disabled: true',
1025
+ '',
1026
+ ].join('\n')
1027
+
1028
+ test('#133 applyPatchChanges:一条 update 不得把 insert 块摊平成顶层行', async () => {
1029
+ const { home, cleanup } = patchHome()
1030
+ try {
1031
+ writeFileSync(join(home, USER_PATCH_FILE), INSERT_BLOCK_YAML, 'utf8')
1032
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1033
+ await facade.applyPatchChanges(USER_PATCH_FILE, [
1034
+ { lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'uvx' } }, action: 'update' },
1035
+ ])
1036
+ const text = readFileSync(join(home, USER_PATCH_FILE), 'utf8')
1037
+ assert.ok(text.includes('- insert:'), 'insert 块必须仍在(摊平 = 该条目重启后整条作废): ' + text)
1038
+ const lines = await facade.readPatchLines(USER_PATCH_FILE)
1039
+ assert.deepEqual(lines.map((l) => l.lineId), ['llm-pi-ai', 'mcp-a', 'plain-plugin'])
1040
+ const config = (lines[1]?.raw as { config?: Record<string, unknown> } | undefined)?.config
1041
+ assert.equal(config?.['command'], 'uvx')
1042
+ } finally {
1043
+ cleanup()
1044
+ }
1045
+ })
1046
+
1047
+ test('#133 applyPatchChanges:新 id 走 insert 动作时落进 insert 块(新增语义)', async () => {
1048
+ const { home, cleanup } = patchHome()
1049
+ try {
1050
+ writeFileSync(join(home, USER_PATCH_FILE), INSERT_BLOCK_YAML, 'utf8')
1051
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1052
+ await facade.applyPatchChanges(USER_PATCH_FILE, [
1053
+ { lineId: 'mcp-new', raw: { id: 'mcp-new', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'node' } }, action: 'insert' },
1054
+ ])
1055
+ const text = readFileSync(join(home, USER_PATCH_FILE), 'utf8')
1056
+ assert.ok(text.includes('- insert:'), '新增必须落在 insert 块里: ' + text)
1057
+ assert.equal(/^- id: mcp-new$/m.test(text), false, '新增绝不能写成顶层行(顶层行查不到就丢弃)')
1058
+ const lines = await facade.readPatchLines(USER_PATCH_FILE)
1059
+ assert.deepEqual(lines.map((l) => l.lineId), ['llm-pi-ai', 'mcp-a', 'plain-plugin', 'mcp-new'])
1060
+ } finally {
1061
+ cleanup()
1062
+ }
1063
+ })
1064
+
1065
+ test('#133 跨层提升:把另一层的 insert 成员写成顶层行必须拒写(文件不动)', async () => {
1066
+ const { home, cleanup } = patchHome()
1067
+ try {
1068
+ mkdirSync(join(home, 'profiles', 'web'), { recursive: true })
1069
+ writeFileSync(join(home, 'profiles', 'web', 'cordis.patch.yml'), INSERT_BLOCK_YAML.replace('- id: llm-pi-ai\n name: "@deepseek-ai/dsh-llm-pi-ai"\n', ''), 'utf8')
1070
+ const profileLayer = join(home, 'profiles', 'web', 'cordis.patch.yml')
1071
+ const before = readFileSync(profileLayer, 'utf8')
1072
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1073
+
1074
+ // 用户层此时不存在:写一条与 profile 层 insert 成员同 id 的顶层行 = 跨层语义翻转
1075
+ const err = await facade
1076
+ .applyPatchChanges(USER_PATCH_FILE, [{ lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client' }, action: 'update' }])
1077
+ .then(() => null, (e: unknown) => e as Error)
1078
+ assert.ok(err !== null, '跨层提升必须拒写')
1079
+ assert.match(String(err.message), /mcp-a/)
1080
+ assert.equal(existsSync(join(home, USER_PATCH_FILE)), false, '拒写 = 用户层文件一个字节都没写')
1081
+ assert.equal(readFileSync(profileLayer, 'utf8'), before, '另一层当然也不许动')
1082
+ } finally {
1083
+ cleanup()
1084
+ }
1085
+ })
1086
+