dsh-config-manager 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/lib/adapters/test-helpers.d.ts +7 -0
  2. package/lib/adapters/test-helpers.js +11 -0
  3. package/lib/cli/actions.js +1 -1
  4. package/lib/client.d.ts +9 -2
  5. package/lib/client.js +685 -649
  6. package/lib/core/backup.d.ts +9 -1
  7. package/lib/core/backup.js +21 -0
  8. package/lib/core/messages-core.d.ts +3 -0
  9. package/lib/core/messages-core.js +6 -0
  10. package/lib/core/messages.d.ts +5 -0
  11. package/lib/core/messages.js +10 -0
  12. package/lib/core/model-tools.js +2 -0
  13. package/lib/core/phase4-crash-child.js +1 -1
  14. package/lib/core/plugin-cli.d.ts +11 -0
  15. package/lib/core/plugin-cli.js +30 -0
  16. package/lib/core/restore-wal.d.ts +2 -0
  17. package/lib/core/restore-wal.js +11 -6
  18. package/lib/core/restore.d.ts +15 -2
  19. package/lib/core/restore.js +65 -3
  20. package/lib/core/snapshot-diff.js +2 -1
  21. package/lib/core/types.d.ts +32 -0
  22. package/lib/index.d.ts +6 -1
  23. package/lib/index.js +17 -16
  24. package/lib/routes/route-support.d.ts +5 -0
  25. package/lib/routes/route-support.js +28 -2
  26. package/lib/routes/sync.js +3 -0
  27. package/lib/sync/merge-preview-view.d.ts +78 -0
  28. package/lib/sync/merge-preview-view.js +46 -0
  29. package/lib/sync/merge.d.ts +2 -1
  30. package/lib/sync/merge.js +9 -4
  31. package/lib/sync/plugin-removal-apply.d.ts +95 -0
  32. package/lib/sync/plugin-removal-apply.js +158 -0
  33. package/lib/sync/plugin-removals.d.ts +90 -0
  34. package/lib/sync/plugin-removals.js +167 -0
  35. package/lib/sync/sync-engine.d.ts +34 -43
  36. package/lib/sync/sync-engine.js +50 -42
  37. package/lib/sync/sync-selection.d.ts +8 -0
  38. package/lib/sync/sync-selection.js +6 -0
  39. package/lib/sync/workspace-merge.d.ts +8 -1
  40. package/lib/ui/restore-plan-view.js +1 -0
  41. package/lib/ui/sync-settings-view.d.ts +10 -0
  42. package/lib/ui/sync-settings-view.js +2 -0
  43. package/package.json +1 -1
  44. package/src/adapters/test-helpers.ts +10 -0
  45. package/src/cli/actions.ts +1 -1
  46. package/src/client/common/info-hint-guard.test.ts +2 -1
  47. package/src/client/run-store.test.ts +7 -5
  48. package/src/client/run-store.ts +4 -5
  49. package/src/client/sync/SyncPanel.tsx +10 -0
  50. package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
  51. package/src/client/sync/sync-locales.ts +4 -0
  52. package/src/client/sync/sync-view.ts +6 -0
  53. package/src/core/backup.ts +21 -1
  54. package/src/core/messages-core.ts +6 -0
  55. package/src/core/messages.ts +10 -0
  56. package/src/core/model-tools.ts +2 -0
  57. package/src/core/phase4-crash-child.ts +1 -1
  58. package/src/core/plugin-cli.ts +37 -0
  59. package/src/core/restore-plugin-install.test.ts +116 -0
  60. package/src/core/restore-wal.ts +12 -6
  61. package/src/core/restore.ts +79 -4
  62. package/src/core/smoke.test.ts +5 -0
  63. package/src/core/snapshot-diff.test.ts +1 -1
  64. package/src/core/snapshot-diff.ts +2 -1
  65. package/src/core/types.ts +31 -0
  66. package/src/index.ts +21 -21
  67. package/src/routes/route-support.ts +27 -2
  68. package/src/routes/sync.ts +3 -0
  69. package/src/security/security.test.ts +1 -0
  70. package/src/sync/merge-preview-view.ts +97 -0
  71. package/src/sync/merge.test.ts +17 -15
  72. package/src/sync/merge.ts +10 -3
  73. package/src/sync/plugin-removal-apply.ts +198 -0
  74. package/src/sync/plugin-removals.test.ts +221 -0
  75. package/src/sync/plugin-removals.ts +208 -0
  76. package/src/sync/sync-engine.test.ts +251 -1
  77. package/src/sync/sync-engine.ts +84 -83
  78. package/src/sync/sync-selection.test.ts +29 -7
  79. package/src/sync/sync-selection.ts +13 -0
  80. package/src/sync/workspace-merge.ts +9 -0
  81. package/src/ui/restore-plan-view.test.ts +1 -1
  82. package/src/ui/restore-plan-view.ts +1 -0
  83. package/src/ui/snapshots-view.test.ts +1 -1
  84. package/src/ui/sync-settings-view.test.ts +20 -0
  85. package/src/ui/sync-settings-view.ts +12 -0
@@ -1,5 +1,5 @@
1
1
  import type { SectionId } from '../schema/types.ts';
2
- import type { ConfigAdapter, FileSystemFacade, HostContext, ImportPlan, PlanItem, Snapshot, SnapshotStatus, SnapshotStore } from './types.ts';
2
+ import type { ConfigAdapter, FileSystemFacade, HostContext, ImportPlan, PlanItem, Snapshot, SnapshotPluginRemoval, SnapshotStatus, SnapshotStore } from './types.ts';
3
3
  /**
4
4
  * 「会写目标」的**单点事实源**:该计划项是否会被引擎交给 `adapter.applyItem`
5
5
  * (即可能产生目标写入)。
@@ -260,6 +260,14 @@ export declare class FileSnapshotStore implements SnapshotStore {
260
260
  readBlob(id: string, blobPath: string): Promise<Uint8Array>;
261
261
  /** 标记快照生命周期状态:重写 <dir>/<id>/snapshot.json(保留其余字段)。 */
262
262
  updateStatus(id: string, status: SnapshotStatus): Promise<void>;
263
+ /**
264
+ * 记录本轮跟删的插件(issue #132 undo 线索):只重写 snapshot.json 的 pluginRemovals 字段。
265
+ *
266
+ * 为什么不像 save() 那样走 finalizeSnapshot:那条路会重算 manifest.blobHashes(本次没有 blob
267
+ * 可写 → 空 map → 磁盘校验直接判失败)并重跑 verify。这里只补一个**不在 metadataHash 覆盖面内**
268
+ * 的字段,manifest 与 blob 一字不动,快照的 READY/完整性语义不受影响。
269
+ */
270
+ recordPluginRemovals(id: string, removals: SnapshotPluginRemoval[]): Promise<void>;
263
271
  }
264
272
  /**
265
273
  * 破坏性内容 hash(稳定,不含 readiness/status):entries + hostFileBackups + beforePlugins。
@@ -793,6 +793,27 @@ export class FileSnapshotStore {
793
793
  snapshot.status = status;
794
794
  await atomicWriteFile(file, JSON.stringify(snapshot, null, 2));
795
795
  }
796
+ /**
797
+ * 记录本轮跟删的插件(issue #132 undo 线索):只重写 snapshot.json 的 pluginRemovals 字段。
798
+ *
799
+ * 为什么不像 save() 那样走 finalizeSnapshot:那条路会重算 manifest.blobHashes(本次没有 blob
800
+ * 可写 → 空 map → 磁盘校验直接判失败)并重跑 verify。这里只补一个**不在 metadataHash 覆盖面内**
801
+ * 的字段,manifest 与 blob 一字不动,快照的 READY/完整性语义不受影响。
802
+ */
803
+ async recordPluginRemovals(id, removals) {
804
+ if (removals.length === 0)
805
+ return;
806
+ const file = path.join(this.snapshotDir(id), 'snapshot.json');
807
+ const snapshot = parseJsonSafe(await fs.readFile(file, 'utf8'));
808
+ // 同日多次应用:保留既有记录(append 而不是覆盖),undo 才能把每一轮删的都装回来
809
+ const merged = [...(snapshot.pluginRemovals ?? [])];
810
+ for (const r of removals) {
811
+ if (!merged.some((m) => m.name === r.name))
812
+ merged.push(r);
813
+ }
814
+ snapshot.pluginRemovals = merged;
815
+ await atomicWriteFile(file, JSON.stringify(snapshot, null, 2));
816
+ }
796
817
  }
797
818
  /* ---------------- Phase 4:manifest / verifySnapshot(F1) ---------------- */
798
819
  /**
@@ -316,6 +316,9 @@ export declare const zh: {
316
316
  'core.pluginCli.installFailed': string;
317
317
  'core.pluginCli.noOutput': string;
318
318
  'core.pluginCli.installFailedWithTail': string;
319
+ 'core.pluginCli.uninstallTimeout': string;
320
+ 'core.pluginCli.uninstallFailed': string;
321
+ 'core.pluginCli.uninstallFailedWithTail': string;
319
322
  'core.consult.compatNoManifest': string;
320
323
  'core.consult.compatPartial': string;
321
324
  'core.consult.compatUnsupported': string;
@@ -340,6 +340,9 @@ export const zh = {
340
340
  'core.pluginCli.installFailed': '安装 {pkg} 失败({code}):{message}',
341
341
  'core.pluginCli.noOutput': '无输出',
342
342
  'core.pluginCli.installFailedWithTail': 'dsh plugin 安装 {pkg} 失败(exit {exitCode}):{tail}',
343
+ 'core.pluginCli.uninstallTimeout': '卸载 {pkg} 超时(进程已终止):请稍后重试 / remove {pkg} timed out (process killed): retry later',
344
+ 'core.pluginCli.uninstallFailed': '卸载 {pkg} 失败({code}):{message}',
345
+ 'core.pluginCli.uninstallFailedWithTail': 'dsh plugin remove {pkg} 失败(exit {exitCode}):{tail}',
343
346
  // ---------- migration-consult ----------
344
347
  'core.consult.compatNoManifest': '无法评估兼容性:manifest 缺失',
345
348
  'core.consult.compatPartial': '部分兼容:跨平台 / 分区缺失 / 版本超前,需人工确认',
@@ -683,6 +686,9 @@ export const en = {
683
686
  'core.pluginCli.installFailed': 'install {pkg} failed ({code}): {message}',
684
687
  'core.pluginCli.noOutput': 'no output',
685
688
  'core.pluginCli.installFailedWithTail': 'dsh plugin install {pkg} failed (exit {exitCode}): {tail}',
689
+ 'core.pluginCli.uninstallTimeout': 'remove {pkg} timed out (process killed): retry later',
690
+ 'core.pluginCli.uninstallFailed': 'remove {pkg} failed ({code}): {message}',
691
+ 'core.pluginCli.uninstallFailedWithTail': 'dsh plugin remove {pkg} failed (exit {exitCode}): {tail}',
686
692
  // ---------- migration-consult ----------
687
693
  'core.consult.compatNoManifest': 'cannot assess compatibility: the manifest is missing',
688
694
  'core.consult.compatPartial': 'partly compatible: cross-platform / missing sections / newer version; manual confirmation required',
@@ -160,6 +160,11 @@ export declare const zh: {
160
160
  readonly 'restore.uninstallFailedExit': 'dsh plugin remove {name} 失败(exit {code}):{tail}';
161
161
  readonly 'restore.noOutput': '无输出';
162
162
  readonly 'restore.pluginRemoveFailed': '卸载失败';
163
+ readonly 'restore.pluginInstall': '装回跟远端删除过的插件 {name}@{version}';
164
+ readonly 'restore.pluginInstallAlreadyPresent': '插件 {name} 已在本机,无需装回';
165
+ readonly 'restore.pluginInstallFailed': '重装失败';
166
+ readonly 'restore.installFailedCode': 'dsh plugin add {name} 失败({code}):{message}';
167
+ readonly 'restore.installFailedExit': 'dsh plugin add {name} 失败(exit {code}):{tail}';
163
168
  readonly 'restore.unknownAction': '未知动作 {kind}: {description}';
164
169
  readonly 'restore.missingTargetBlob': '恢复动作缺少 target/blobPath';
165
170
  readonly 'restore.missingTarget': '恢复动作缺少 target';
@@ -147,6 +147,11 @@ export const zh = {
147
147
  'restore.uninstallFailedExit': 'dsh plugin remove {name} 失败(exit {code}):{tail}',
148
148
  'restore.noOutput': '无输出',
149
149
  'restore.pluginRemoveFailed': '卸载失败',
150
+ 'restore.pluginInstall': '装回跟远端删除过的插件 {name}@{version}',
151
+ 'restore.pluginInstallAlreadyPresent': '插件 {name} 已在本机,无需装回',
152
+ 'restore.pluginInstallFailed': '重装失败',
153
+ 'restore.installFailedCode': 'dsh plugin add {name} 失败({code}):{message}',
154
+ 'restore.installFailedExit': 'dsh plugin add {name} 失败(exit {code}):{tail}',
150
155
  'restore.unknownAction': '未知动作 {kind}: {description}',
151
156
  'restore.missingTargetBlob': '恢复动作缺少 target/blobPath',
152
157
  'restore.missingTarget': '恢复动作缺少 target',
@@ -655,6 +660,11 @@ export const en = {
655
660
  'restore.uninstallFailedExit': 'dsh plugin remove {name} failed (exit {code}): {tail}',
656
661
  'restore.noOutput': 'no output',
657
662
  'restore.pluginRemoveFailed': 'Uninstall failed',
663
+ 'restore.pluginInstall': 'Reinstall plugin {name}@{version} (removed earlier to follow the remote)',
664
+ 'restore.pluginInstallAlreadyPresent': 'Plugin {name} is already installed here; nothing to reinstall',
665
+ 'restore.pluginInstallFailed': 'Reinstall failed',
666
+ 'restore.installFailedCode': 'dsh plugin add {name} failed ({code}): {message}',
667
+ 'restore.installFailedExit': 'dsh plugin add {name} failed (exit {code}): {tail}',
658
668
  'restore.unknownAction': 'Unknown action {kind}: {description}',
659
669
  'restore.missingTargetBlob': 'Restore action is missing target/blobPath',
660
670
  'restore.missingTarget': 'Restore action is missing target',
@@ -336,6 +336,8 @@ export function createModelTools(deps) {
336
336
  hostFileRestores: plan.summary.hostFileRestores,
337
337
  hostFileRemoves: plan.summary.hostFileRemoves,
338
338
  pluginRemoves: plan.summary.pluginRemoves,
339
+ // issue #132:undo 会反向装回跟删过的插件,计数单独给出(agent 不必自己数 actions)
340
+ pluginInstalls: plan.summary.pluginInstalls,
339
341
  fileRestores: plan.summary.fileRestores,
340
342
  fileRemoves: plan.summary.fileRemoves,
341
343
  credentialHints: plan.summary.credentialHints,
@@ -48,7 +48,7 @@ async function main() {
48
48
  describe: async (ref) => ({ value: { theme: 'dark' }, revision: 1, secrets: [] }),
49
49
  },
50
50
  credentials: { describe: async () => ({ configured: false }) },
51
- plugins: { listInstalled: async () => [] },
51
+ plugins: { listInstalled: async () => [], uninstall: async () => ({ needsRestart: true }) },
52
52
  workspace: { listRecords: async () => [] },
53
53
  patchFile: { readPatchLines: async () => [] },
54
54
  log: { warn: () => { } },
@@ -268,6 +268,17 @@ export declare function isTransientDshPluginFailure(output: string): boolean;
268
268
  * @returns 分类结果;未识别返回 null(调用方展示原始摘要)。
269
269
  */
270
270
  export declare function classifyDshPluginFailure(output: string): DshPluginFailure | null;
271
+ /**
272
+ * 卸载一个插件(issue #132 的唯一写入口):`dsh plugin remove`,不自己改 package.json。
273
+ *
274
+ * 为什么不复用安装后的 reconcileBundlesAfterInstall:对账是「安装成功后补一次」的写操作,
275
+ * 卸载后 bundles 由 CLI 自己收尾;这里再补一次只会在失败语义上制造歧义。
276
+ */
277
+ export declare function uninstallViaCli(homeDir: string, profile: string, pkg: string, runner: (profileDir: string, profile: string, argv: readonly string[], input?: undefined, signal?: AbortSignal) => Promise<DshPluginResult>, signal?: AbortSignal): Promise<{
278
+ needsRestart: boolean;
279
+ }>;
280
+ /** 卸载失败(issue #132)→ 与安装同一套分类口径的双语可读 Error。 */
281
+ export declare function uninstallErrorFor(pkg: string, result: DshPluginResult): Error;
271
282
  /** 安装失败 → 分类后的双语可读 Error;未识别则保留 stderr 尾部摘要。 */
272
283
  export declare function installErrorFor(pkg: string, result: DshPluginResult): Error;
273
284
  export {};
@@ -737,6 +737,36 @@ export function classifyDshPluginFailure(output) {
737
737
  }
738
738
  return null;
739
739
  }
740
+ /**
741
+ * 卸载一个插件(issue #132 的唯一写入口):`dsh plugin remove`,不自己改 package.json。
742
+ *
743
+ * 为什么不复用安装后的 reconcileBundlesAfterInstall:对账是「安装成功后补一次」的写操作,
744
+ * 卸载后 bundles 由 CLI 自己收尾;这里再补一次只会在失败语义上制造歧义。
745
+ */
746
+ export async function uninstallViaCli(homeDir, profile, pkg, runner, signal) {
747
+ const result = await runner(resolveProfileDir(homeDir, profile), profile, ['remove', pkg], undefined, signal);
748
+ if (result.exitCode !== 0 || result.timedOut)
749
+ throw uninstallErrorFor(pkg, result);
750
+ return { needsRestart: true };
751
+ }
752
+ /** 卸载失败(issue #132)→ 与安装同一套分类口径的双语可读 Error。 */
753
+ export function uninstallErrorFor(pkg, result) {
754
+ if (result.spawnError !== undefined && /ENOENT|EINVAL/.test(result.spawnError)) {
755
+ return new Error(engineMsg('core.pluginCli.dshCliStartFailed', { spawnError: result.spawnError, pkg }));
756
+ }
757
+ if (result.timedOut) {
758
+ return new Error(engineMsg('core.pluginCli.uninstallTimeout', { pkg }));
759
+ }
760
+ const output = `${result.stderr}\n${result.stdout}`;
761
+ const failure = classifyDshPluginFailure(output);
762
+ if (failure !== null) {
763
+ return new Error(engineMsg('core.pluginCli.uninstallFailed', { pkg, code: failure.code, message: failure.message }));
764
+ }
765
+ const tail = (result.stderr.trim().split('\n').slice(-8).join('\n')
766
+ || result.stdout.trim().split('\n').slice(-8).join('\n')
767
+ || engineMsg('core.pluginCli.noOutput'));
768
+ return new Error(engineMsg('core.pluginCli.uninstallFailedWithTail', { pkg, exitCode: String(result.exitCode), tail }));
769
+ }
740
770
  /** 安装失败 → 分类后的双语可读 Error;未识别则保留 stderr 尾部摘要。 */
741
771
  export function installErrorFor(pkg, result) {
742
772
  if (result.spawnError !== undefined && /ENOENT|EINVAL/.test(result.spawnError)) {
@@ -1,4 +1,6 @@
1
1
  import type { JournalStepRecord } from './types.ts';
2
+ /** 插件类动作 = 外部副作用(不带文件指纹;reconcile 恒走保守分支)。 */
3
+ export declare function isExternalPluginKind(kind: string): boolean;
2
4
  export declare function isWalActionKind(kind: string): boolean;
3
5
  /**
4
6
  * 引擎侧最小 journal 端口(结构上兼容 phase3-host 的 JournalRunContext)。
@@ -29,7 +29,12 @@ const WAL_KINDS = new Set([
29
29
  'fileRestore',
30
30
  'fileRemove',
31
31
  'pluginRemove',
32
+ 'pluginInstall',
32
33
  ]);
34
+ /** 插件类动作 = 外部副作用(不带文件指纹;reconcile 恒走保守分支)。 */
35
+ export function isExternalPluginKind(kind) {
36
+ return kind === 'pluginRemove' || kind === 'pluginInstall';
37
+ }
33
38
  export function isWalActionKind(kind) {
34
39
  return WAL_KINDS.has(kind);
35
40
  }
@@ -65,8 +70,8 @@ export function createRestoreWal(journal) {
65
70
  out.push(undefined);
66
71
  continue;
67
72
  }
68
- // 插件卸载:外部副作用,刻意不带指纹(probeExternal 会得 unknown → 保守)。
69
- const external = entry.kind === 'pluginRemove';
73
+ // 插件装卸:外部副作用,刻意不带指纹(probeExternal 会得 unknown → 保守)。
74
+ const external = isExternalPluginKind(entry.kind);
70
75
  const ref = external ? '' : (entry.abs ?? '');
71
76
  const beforeFp = external ? null : await restoreFingerprint(entry.abs);
72
77
  const id = stepIdOf(entry, ref);
@@ -114,14 +119,14 @@ export function restoreStepId(kind, subject) {
114
119
  }
115
120
  /** step id 的 subject 段:插件卸载用包名,其余用绝对路径(拿不到绝对路径时退回流相对 target)。 */
116
121
  export function restoreWalSubject(kind, pluginName, refOrTarget) {
117
- return kind === 'pluginRemove' ? (pluginName ?? refOrTarget) : refOrTarget;
122
+ return isExternalPluginKind(kind) ? (pluginName ?? refOrTarget) : refOrTarget;
118
123
  }
119
124
  function stepIdOf(entry, ref) {
120
125
  return restoreStepId(entry.kind, restoreWalSubject(entry.kind, entry.pluginName, ref || (entry.target ?? '')));
121
126
  }
122
127
  /** 计划动作 → step id(调用方比对「这条动作是否已证明完成」时必须用同一规则)。 */
123
128
  export function restoreActionStepId(action, abs) {
124
- const ref = action.kind === 'pluginRemove' ? '' : (abs ?? '');
129
+ const ref = isExternalPluginKind(action.kind) ? '' : (abs ?? '');
125
130
  return restoreStepId(action.kind, restoreWalSubject(action.kind, action.pluginName, ref || (action.target ?? '')));
126
131
  }
127
132
  /**
@@ -139,7 +144,7 @@ export function collectRestoreWalEntries(actions, absOf) {
139
144
  kind: action.kind,
140
145
  ...(action.target !== undefined ? { target: action.target } : {}),
141
146
  ...(action.pluginName !== undefined ? { pluginName: action.pluginName } : {}),
142
- abs: action.kind === 'pluginRemove' || action.target === undefined ? null : absOf(action),
147
+ abs: isExternalPluginKind(action.kind) || action.target === undefined ? null : absOf(action),
143
148
  });
144
149
  }
145
150
  return { mutating, entries };
@@ -152,7 +157,7 @@ export function restoreWalHandlesFromSteps(entries, steps) {
152
157
  return entries.map((entry) => {
153
158
  if (!isWalActionKind(entry.kind))
154
159
  return undefined;
155
- const external = entry.kind === 'pluginRemove';
160
+ const external = isExternalPluginKind(entry.kind);
156
161
  const ref = external ? '' : (entry.abs ?? '');
157
162
  const id = restoreStepId(entry.kind, restoreWalSubject(entry.kind, entry.pluginName, ref || (entry.target ?? '')));
158
163
  const known = steps[id];
@@ -2,7 +2,7 @@ import type { MsgFunc } from './messages.ts';
2
2
  import type { RestoreJournalPort } from './restore-wal.ts';
3
3
  import type { RestoreResumeHint } from './restore-resume.ts';
4
4
  import type { SnapshotStatus } from './types.ts';
5
- export type RestoreActionKind = 'hostFileRestore' | 'hostFileRemove' | 'pluginRemove' | 'fileRestore' | 'fileRemove' | 'credentialHint' | 'skip';
5
+ export type RestoreActionKind = 'hostFileRestore' | 'hostFileRemove' | 'pluginRemove' | 'pluginInstall' | 'fileRestore' | 'fileRemove' | 'credentialHint' | 'skip';
6
6
  export interface RestoreAction {
7
7
  kind: RestoreActionKind;
8
8
  /** 人类可读描述 */
@@ -11,8 +11,10 @@ export interface RestoreAction {
11
11
  target?: string;
12
12
  /** hostFileRestore/fileRestore:快照内 blob 相对路径(相对 snapshotDir) */
13
13
  blobPath?: string;
14
- /** pluginRemove:插件包名 */
14
+ /** pluginRemove / pluginInstall:插件包名 */
15
15
  pluginName?: string;
16
+ /** pluginInstall:重装目标(name@version;版本未知时就是裸包名) */
17
+ pluginTarget?: string;
16
18
  /** credentialHint:人工提示文本 */
17
19
  manualHint?: string;
18
20
  /** 附加说明(旧快照缺基线 / 离线无法恢复等) */
@@ -29,6 +31,7 @@ export interface RestorePlan {
29
31
  hostFileRestores: number;
30
32
  hostFileRemoves: number;
31
33
  pluginRemoves: number;
34
+ pluginInstalls: number;
32
35
  fileRestores: number;
33
36
  fileRemoves: number;
34
37
  credentialHints: number;
@@ -69,6 +72,14 @@ export interface RestoreOptions {
69
72
  ok: boolean;
70
73
  message?: string;
71
74
  }>;
75
+ /**
76
+ * 注入式插件重装器(issue #132 undo;测试用)。缺省走官方 `dsh plugin add <name>@<version>`。
77
+ * 只用于「快照记录过跟删、本机现在缺失」的插件;未记录过的插件绝不重装。
78
+ */
79
+ pluginInstaller?: (name: string, target: string, profileDir: string, profile: string) => Promise<{
80
+ ok: boolean;
81
+ message?: string;
82
+ }>;
72
83
  /** 每项动作执行回调(宿主路由埋点:更新 RunRegistry 进度;index/1-based、total=计划动作数、
73
84
  * detail=动作描述。dry-run/planRestore 不触发) */
74
85
  onAction?: (info: {
@@ -113,6 +124,8 @@ export interface RestoreReport {
113
124
  restored: string[];
114
125
  /** 已卸载的插件名 */
115
126
  removedPlugins: string[];
127
+ /** 已按 undo 记录装回的插件目标(name@version;issue #132) */
128
+ installedPlugins: string[];
116
129
  /** 需人工处理的提示(凭据补录等) */
117
130
  manualHints: string[];
118
131
  /** 失败清单 */
@@ -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.0";
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 版本号猜**)。
@@ -873,6 +877,7 @@ type SelectionView = {
873
877
  sessionsInclude: string[];
874
878
  encrypt: boolean;
875
879
  includeSecrets: boolean;
880
+ deletePlugins: boolean;
876
881
  };
877
882
  /**
878
883
  * Mount the config-manager engine: host context, adapters, and the
package/lib/index.js CHANGED
@@ -75,7 +75,7 @@ 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';
@@ -148,7 +148,7 @@ export const name = 'config-manager';
148
148
  /** Services required before the engine can mount (present in every profile). */
149
149
  export const inject = ['settings', 'credentials'];
150
150
  /** Plugin version, kept in sync with package.json ("version"). */
151
- export const PLUGIN_VERSION = '0.7.0';
151
+ export const PLUGIN_VERSION = '0.8.0';
152
152
  /** Plugin own package name — excluded from its own exported plugins list. */
153
153
  const PLUGIN_NAME = 'dsh-config-manager';
154
154
  /**
@@ -488,6 +488,10 @@ export class DshPluginsFacade {
488
488
  // 回读实际落盘版本:调用方据此校验升级是否真的生效(issue #101),而不是只看子进程退出码。
489
489
  return { needsRestart: true, installedVersion: readInstalledVersion(profileDir, pkg) };
490
490
  }
491
+ /** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
492
+ uninstall(pkg, signal) {
493
+ return uninstallViaCli(this.homeDir, this.profile, pkg, this.runner, signal);
494
+ }
491
495
  }
492
496
  /** Workspace facade over the real ctx.workspaceRegistry. */
493
497
  class DshWorkspaceFacade {
@@ -2327,18 +2331,16 @@ function makeRoutes(deps) {
2327
2331
  /** 分区选择视图形状(无 schemaVersion;密码值永不进视图)。 */
2328
2332
  /** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
2329
2333
  /** 指定通道的分区选择视图。 */
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
- };
2334
+ /** SyncSelection → SelectionView(字段白名单;密码值永不进视图)。 */
2335
+ const toSelectionView = (sel) => ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets, deletePlugins: sel.deletePlugins });
2336
+ const selectionView = async (channel) => toSelectionView(await ensureSelectionLoaded(channel));
2334
2337
  const selectionViewByChannel = async () => {
2335
2338
  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
2339
  // 通道集合来自唯一枚举(SYNC_CHANNELS);不得穷举字面量(漏一处即该通道状态静默缺失)
2338
2340
  const out = {};
2339
2341
  for (const channel of SYNC_CHANNELS) {
2340
2342
  selectionCache[channel] = all[channel];
2341
- out[channel] = view(all[channel]);
2343
+ out[channel] = toSelectionView(all[channel]);
2342
2344
  }
2343
2345
  return out;
2344
2346
  };
@@ -2443,7 +2445,8 @@ function makeRoutes(deps) {
2443
2445
  transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir);
2444
2446
  }
2445
2447
  const channel = channelOf(cfg);
2446
- const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection());
2448
+ const selection = selectionCache[channel] ?? defaultSyncSelection();
2449
+ const sections = effectiveSections(selection);
2447
2450
  return new SyncEngine({
2448
2451
  ctx: host,
2449
2452
  transport,
@@ -2454,11 +2457,10 @@ function makeRoutes(deps) {
2454
2457
  zipDir: tmpDir,
2455
2458
  msg,
2456
2459
  ...(sections === undefined ? {} : { sections }),
2457
- ...(engineOpts.optInSections === undefined || engineOpts.optInSections.length === 0
2458
- ? {}
2459
- : { optInSections: engineOpts.optInSections }),
2460
- // m-retention:远端快照裁剪与本地备份产物共用同一份 GFS 保留策略(缺省 = 最近 10 个,
2461
- // 与改造前逐字等价);用户改完策略即时生效(每次 prune 都重读)。
2460
+ // issue #132:开关开 = 授权(手动/自动同判据);self 守卫防同步把自己删掉
2461
+ deletePlugins: selection.deletePlugins, selfPluginName: PLUGIN_NPM_PACKAGE,
2462
+ ...(engineOpts.optInSections?.length ? { optInSections: engineOpts.optInSections } : {}),
2463
+ // m-retention:远端裁剪与本地备份共用 GFS 策略(缺省最近 10 个,每次 prune 重读 ⇒ 改完即时生效)。
2462
2464
  retentionPolicy: () => retentionPolicyProvider(),
2463
2465
  });
2464
2466
  };
@@ -3505,8 +3507,7 @@ export function apply(ctx, config) {
3505
3507
  namespaces: async () => (await ctx.settings.describe({ redactSecrets: true })).map((d) => String(d.ns)),
3506
3508
  // Sessions 分区默认关(含敏感内容):挂载 adapter 供 Custom Export 显式勾选(§3.3/§15)。
3507
3509
  includeSessions: true,
3508
- // 导出 plugins 分区时不列本插件自身,避免备份中的自引用条目。
3509
- selfPluginName: PLUGIN_NAME,
3510
+ selfPluginName: PLUGIN_NAME, // 导出 plugins 分区时不列本插件自身,避免备份里的自引用条目
3510
3511
  // pluginFiles 扩展:额外白名单文件 + 约定配置目录(都相对 ~/.dsh 根),支持导出更多插件配置。
3511
3512
  pluginFiles: config?.pluginFiles,
3512
3513
  pluginFilesDir: config?.pluginFilesDir,