dsh-config-manager 0.6.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 (112) 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 +14 -2
  5. package/lib/client.js +722 -647
  6. package/lib/core/backup.d.ts +9 -1
  7. package/lib/core/backup.js +21 -0
  8. package/lib/core/local-plugin-host.d.ts +9 -0
  9. package/lib/core/local-plugin-host.js +174 -1
  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 +8 -0
  13. package/lib/core/messages.js +18 -0
  14. package/lib/core/model-tools.js +2 -0
  15. package/lib/core/phase4-crash-child.js +1 -1
  16. package/lib/core/plugin-cli.d.ts +11 -0
  17. package/lib/core/plugin-cli.js +30 -0
  18. package/lib/core/restore-wal.d.ts +2 -0
  19. package/lib/core/restore-wal.js +11 -6
  20. package/lib/core/restore.d.ts +15 -2
  21. package/lib/core/restore.js +65 -3
  22. package/lib/core/run-registry.d.ts +10 -0
  23. package/lib/core/run-registry.js +17 -0
  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 -2
  27. package/lib/index.js +24 -21
  28. package/lib/routes/import.js +6 -1
  29. package/lib/routes/route-support.d.ts +7 -1
  30. package/lib/routes/route-support.js +36 -5
  31. package/lib/routes/sync.js +8 -2
  32. package/lib/sync/autosync-config.d.ts +9 -1
  33. package/lib/sync/autosync-config.js +10 -2
  34. package/lib/sync/autosync-scheduler.js +18 -6
  35. package/lib/sync/git/git-transport.d.ts +31 -1
  36. package/lib/sync/git/git-transport.js +119 -23
  37. package/lib/sync/merge-preview-view.d.ts +78 -0
  38. package/lib/sync/merge-preview-view.js +46 -0
  39. package/lib/sync/merge.d.ts +2 -1
  40. package/lib/sync/merge.js +9 -4
  41. package/lib/sync/plugin-removal-apply.d.ts +95 -0
  42. package/lib/sync/plugin-removal-apply.js +158 -0
  43. package/lib/sync/plugin-removals.d.ts +90 -0
  44. package/lib/sync/plugin-removals.js +167 -0
  45. package/lib/sync/sync-config.d.ts +34 -3
  46. package/lib/sync/sync-config.js +38 -5
  47. package/lib/sync/sync-engine.d.ts +34 -43
  48. package/lib/sync/sync-engine.js +50 -42
  49. package/lib/sync/sync-selection.d.ts +8 -0
  50. package/lib/sync/sync-selection.js +6 -0
  51. package/lib/sync/workspace-merge.d.ts +8 -1
  52. package/lib/ui/restore-plan-view.js +1 -0
  53. package/lib/ui/sync-settings-view.d.ts +14 -0
  54. package/lib/ui/sync-settings-view.js +5 -0
  55. package/package.json +1 -1
  56. package/src/adapters/test-helpers.ts +10 -0
  57. package/src/cli/actions.ts +1 -1
  58. package/src/client/common/info-hint-guard.test.ts +2 -1
  59. package/src/client/run-store.test.ts +8 -6
  60. package/src/client/run-store.ts +9 -5
  61. package/src/client/sync/ChannelConfigDialog.tsx +15 -1
  62. package/src/client/sync/SyncPanel.tsx +16 -0
  63. package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
  64. package/src/client/sync/sync-api.ts +2 -0
  65. package/src/client/sync/sync-locales.ts +10 -0
  66. package/src/client/sync/sync-view.ts +6 -0
  67. package/src/core/backup.ts +21 -1
  68. package/src/core/local-plugin-host.test.ts +31 -2
  69. package/src/core/local-plugin-host.ts +175 -2
  70. package/src/core/messages-core.ts +6 -0
  71. package/src/core/messages.ts +18 -0
  72. package/src/core/model-tools.ts +2 -0
  73. package/src/core/phase4-crash-child.ts +1 -1
  74. package/src/core/plugin-cli.ts +37 -0
  75. package/src/core/restore-plugin-install.test.ts +116 -0
  76. package/src/core/restore-wal.ts +12 -6
  77. package/src/core/restore.ts +79 -4
  78. package/src/core/run-registry-runs.test.ts +26 -1
  79. package/src/core/run-registry.ts +18 -0
  80. package/src/core/smoke.test.ts +5 -0
  81. package/src/core/snapshot-diff.test.ts +1 -1
  82. package/src/core/snapshot-diff.ts +2 -1
  83. package/src/core/types.ts +31 -0
  84. package/src/index.sync.test.ts +27 -0
  85. package/src/index.ts +30 -28
  86. package/src/routes/import.ts +6 -1
  87. package/src/routes/route-support.ts +34 -5
  88. package/src/routes/sync.ts +8 -2
  89. package/src/security/security.test.ts +1 -0
  90. package/src/sync/autosync-config.ts +10 -2
  91. package/src/sync/autosync-scheduler.test.ts +61 -1
  92. package/src/sync/autosync-scheduler.ts +17 -5
  93. package/src/sync/git/git-transport.test.ts +117 -0
  94. package/src/sync/git/git-transport.ts +131 -23
  95. package/src/sync/merge-preview-view.ts +97 -0
  96. package/src/sync/merge.test.ts +17 -15
  97. package/src/sync/merge.ts +10 -3
  98. package/src/sync/plugin-removal-apply.ts +198 -0
  99. package/src/sync/plugin-removals.test.ts +221 -0
  100. package/src/sync/plugin-removals.ts +208 -0
  101. package/src/sync/sync-config.test.ts +59 -1
  102. package/src/sync/sync-config.ts +51 -5
  103. package/src/sync/sync-engine.test.ts +251 -1
  104. package/src/sync/sync-engine.ts +84 -83
  105. package/src/sync/sync-selection.test.ts +29 -7
  106. package/src/sync/sync-selection.ts +13 -0
  107. package/src/sync/workspace-merge.ts +9 -0
  108. package/src/ui/restore-plan-view.test.ts +1 -1
  109. package/src/ui/restore-plan-view.ts +1 -0
  110. package/src/ui/snapshots-view.test.ts +1 -1
  111. package/src/ui/sync-settings-view.test.ts +21 -0
  112. package/src/ui/sync-settings-view.ts +19 -0
@@ -0,0 +1,198 @@
1
+ /**
2
+ * issue #132:跟随远端删除插件的**编排层**(判据 → 卸载 → 告警 → undo 线索)。
3
+ *
4
+ * 为什么从 sync-engine 下沉:引擎已顶到文件体量棘轮(tests/file-size-ratchet.test.ts),
5
+ * 而这部分只依赖「三方载荷 + 本机已装清单 + 卸载函数 + msg」,不碰引擎内部状态;
6
+ * 独立成模块后可单独测,也不会把引擎继续堆高。判据本体仍留在 ./plugin-removals.ts(纯函数、零 IO)。
7
+ *
8
+ * 三条语义在此定型,改之前先读 issue #132 的裁决:
9
+ * 1. 开关关闭 = **不删但也绝不装作没有候选**:逐项发 warning 说明「开着会删谁」;
10
+ * 2. 卸载失败(含 desktop 保留档案被 CLI 拒)逐项进报告 + warning,不阻断其余项、不回滚整轮;
11
+ * 3. undo 线索只写「真的删成功」的那些,写不进去只告警(报告里的 reinstallTarget 仍是人工兜底)。
12
+ */
13
+ import { registerMessageCatalog } from '../core/engine-locale.ts';
14
+ import { pluginInstallTarget } from '../core/plugin-cli.ts';
15
+ import type { MsgFunc } from '../core/messages.ts';
16
+ import type { SnapshotPluginRemoval } from '../core/types.ts';
17
+ import type { SectionData, SectionId } from '../schema/types.ts';
18
+ import { planPluginRemovals } from './plugin-removals.ts';
19
+ import type { PluginRemovalEntry, PluginRemovalPlan } from './plugin-removals.ts';
20
+
21
+ const zh = {
22
+ 'sync.pluginRemoveDone': '已跟随远端删除插件 {name}@{version}(可随时用 "{name}@{version}" 重装)',
23
+ 'sync.pluginRemoveFailed': '删除插件 {name} 失败:{reason}(其余项继续,失败项下一轮会重新判定)',
24
+ 'sync.pluginRemoveConflict': '插件 {name} 远端已删除,但本机改过(本机 {local},共同祖先 {ancestor}):未删除,请人工确认',
25
+ 'sync.pluginRemoveSkipped': '插件 {name} 在远端已删除,但"跟随删除插件"未开启:已保留(开启后会删除)',
26
+ 'sync.pluginRemoveUndoUnrecorded': '插件已经删除,但没能写进本次回滚快照的 undo 记录({names}):恢复这份快照不会自动装回它们,需要时请手动执行 dsh plugin add',
27
+ } as const;
28
+
29
+ const en: Record<keyof typeof zh, string> = {
30
+ 'sync.pluginRemoveDone': 'Removed plugin {name}@{version} to follow the remote (reinstall anytime with "{name}@{version}")',
31
+ 'sync.pluginRemoveFailed': 'Could not remove plugin {name}: {reason} (the remaining items continue; this one is re-evaluated next round)',
32
+ 'sync.pluginRemoveConflict': 'Plugin {name} was deleted remotely but changed locally (local {local}, common ancestor {ancestor}): not removed, needs a human decision',
33
+ 'sync.pluginRemoveSkipped': 'Plugin {name} was deleted remotely, but "delete plugins to follow the remote" is off: kept (it will be removed once enabled)',
34
+ 'sync.pluginRemoveUndoUnrecorded': 'The plugin(s) were removed, but the undo record could not be written into this rollback snapshot ({names}): restoring that snapshot will not reinstall them — run dsh plugin add manually if needed',
35
+ };
36
+
37
+ registerMessageCatalog({ id: 'sync-plugin-removal', zh, en });
38
+
39
+ /** 一条插件卸载结果(reinstallTarget 供 undo 与人工补装使用)。 */
40
+ export interface PluginRemovalReportItem {
41
+ name: string;
42
+ version: string;
43
+ /** 重装目标:`name@version`(版本未知时退回裸包名) */
44
+ reinstallTarget: string;
45
+ ok: boolean;
46
+ /** 失败原因(已由 CLI 分类器给出可操作文案);ok=true 时缺省 */
47
+ message?: string;
48
+ }
49
+
50
+ /** 预览侧的删除视图(确认页据此单列「将删除:X@1.2.3」,用户可整轮取消)。 */
51
+ export interface PluginRemovalPreviewView {
52
+ pluginRemovals: { name: string; version: string }[];
53
+ pluginRemovalConflicts: { name: string; ancestorVersion: string; localVersion: string }[];
54
+ pluginRemovalSkipped: { name: string; reason: string }[];
55
+ }
56
+
57
+ /** 判据输入侧的「已装插件」最小形状(PluginInfo 与 PluginEntry 都能直接传)。 */
58
+ type InstalledPlugin = { name: string; version: string; enabled?: boolean; spec?: string; bundlesOnly?: boolean };
59
+
60
+ /**
61
+ * 把某个分区载荷里的插件清单抽成判据要的形状(不认识 = undefined)。
62
+ *
63
+ * 为什么直接从「本轮合并的三方输入」读而不是再 export 一次:那三个载荷就是本轮合并的真实输入,
64
+ * 再 export 会拿到「已经写了一半」的状态,判据与合并结论就会打架。
65
+ */
66
+ export function pluginEntriesOf(data: SectionData | undefined): PluginRemovalEntry[] | undefined {
67
+ if (data === null || typeof data !== 'object') return undefined;
68
+ const obj = data as { version?: unknown; plugins?: unknown };
69
+ if (obj.version !== 1 || !Array.isArray(obj.plugins)) return undefined;
70
+ const out: PluginRemovalEntry[] = [];
71
+ for (const raw of obj.plugins) {
72
+ if (raw === null || typeof raw !== 'object') continue;
73
+ const p = raw as { name?: unknown; version?: unknown; spec?: unknown; bundlesOnly?: unknown };
74
+ if (typeof p.name !== 'string' || p.name === '') continue;
75
+ out.push({
76
+ name: p.name,
77
+ version: typeof p.version === 'string' ? p.version : '',
78
+ ...(typeof p.spec === 'string' ? { spec: p.spec } : {}),
79
+ ...(p.bundlesOnly === true ? { bundlesOnly: true } : {}),
80
+ });
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /** 三方输入 + 本机已装 → 删除计划(预览与执行共用同一份判据)。 */
86
+ export function pluginRemovalPlanOf(args: {
87
+ ancestor?: SectionData;
88
+ remote?: SectionData;
89
+ installed: readonly InstalledPlugin[];
90
+ enabled: boolean;
91
+ selfName?: string;
92
+ }): PluginRemovalPlan {
93
+ return planPluginRemovals({
94
+ enabled: args.enabled,
95
+ ancestor: pluginEntriesOf(args.ancestor),
96
+ remote: pluginEntriesOf(args.remote),
97
+ local: args.installed,
98
+ selfName: args.selfName ?? '',
99
+ });
100
+ }
101
+
102
+ /**
103
+ * 执行删除(逐项失败不阻断)。
104
+ *
105
+ * 为什么只在 plugins 分区真的被应用时才动:分区冲突/跳过 = 本轮还没确定「远端删了它」,
106
+ * 此时删本机插件等于拿未裁决的远端差异动用户机器。
107
+ */
108
+ export async function applyPluginRemovalStep(args: {
109
+ appliedIds: readonly SectionId[];
110
+ plan: PluginRemovalPlan | undefined;
111
+ enabled: boolean;
112
+ uninstall: (name: string) => Promise<unknown>;
113
+ msg: MsgFunc;
114
+ }): Promise<{ removals: PluginRemovalReportItem[]; warnings: string[] }> {
115
+ const removals: PluginRemovalReportItem[] = [];
116
+ const warnings: string[] = [];
117
+ if (!args.appliedIds.includes('plugins')) return { removals, warnings };
118
+ const plan = args.plan;
119
+ if (plan === undefined) return { removals, warnings };
120
+ for (const c of plan.conflicts) {
121
+ warnings.push(args.msg('sync.pluginRemoveConflict', {
122
+ name: c.name, local: c.localVersion, ancestor: c.ancestorVersion,
123
+ }));
124
+ }
125
+ if (!args.enabled) {
126
+ // 开关关:把「打开后会删什么」如实说出来(不删,但也绝不装作没有候选)
127
+ for (const k of plan.kept) {
128
+ if (k.reason === 'switch-off') warnings.push(args.msg('sync.pluginRemoveSkipped', { name: k.name }));
129
+ }
130
+ return { removals, warnings };
131
+ }
132
+ for (const r of plan.removals) {
133
+ // 重装目标与导入侧同一决策(core/plugin-cli.ts 的 pluginInstallTarget):github:/git+/file:/link:
134
+ // 这类来源只靠 name@version 装不回同一份代码,必须带祖先记录的 spec。
135
+ const reinstallTarget = pluginInstallTarget(r.name, {
136
+ ...(r.version === '' ? {} : { version: r.version }),
137
+ ...(r.spec === undefined ? {} : { spec: r.spec }),
138
+ });
139
+ try {
140
+ await args.uninstall(r.name);
141
+ removals.push({ name: r.name, version: r.version, reinstallTarget, ok: true });
142
+ warnings.push(args.msg('sync.pluginRemoveDone', { name: r.name, version: r.version }));
143
+ } catch (error) {
144
+ const reason = error instanceof Error ? error.message : String(error);
145
+ removals.push({ name: r.name, version: r.version, reinstallTarget, ok: false, message: reason });
146
+ warnings.push(args.msg('sync.pluginRemoveFailed', { name: r.name, reason }));
147
+ }
148
+ }
149
+ return { removals, warnings };
150
+ }
151
+
152
+ /**
153
+ * 把「本轮删掉哪些插件」写进本次回滚快照(undo 线索)。
154
+ *
155
+ * 写不进去不中止同步(分区已落地且已重导出),但必须留一条可见告警 ——
156
+ * 报告里的 reinstallTarget 仍可人工执行,静默丢失 undo 线索才是真问题。
157
+ */
158
+ export async function recordPluginRemovalUndo(args: {
159
+ removals: readonly PluginRemovalReportItem[];
160
+ snapshotId: string;
161
+ record?: (id: string, entries: SnapshotPluginRemoval[]) => Promise<void>;
162
+ msg: MsgFunc;
163
+ }): Promise<string[]> {
164
+ const removed = args.removals.filter((r) => r.ok);
165
+ if (removed.length === 0) return [];
166
+ const names = removed.map((r) => r.reinstallTarget).join(', ');
167
+ const entries = removed.map((r) => ({ name: r.name, version: r.version, target: r.reinstallTarget }));
168
+ if (args.record === undefined) return [args.msg('sync.pluginRemoveUndoUnrecorded', { names })];
169
+ try {
170
+ await args.record(args.snapshotId, entries);
171
+ return [];
172
+ } catch (error) {
173
+ const reason = error instanceof Error ? error.message : String(error);
174
+ return [args.msg('sync.pluginRemoveUndoUnrecorded', { names }), reason];
175
+ }
176
+ }
177
+
178
+ /**
179
+ * 预览侧的删除视图:确认页必须能单列「将删除:X@1.2.3」让用户整轮取消,
180
+ * 也必须如实说明「开关关着,所以没删」与「远端删了但本机改过」两种不删的原因。
181
+ *
182
+ * plugins 分区本轮不可应用(conflict / skip)时不列删除项:那时「远端删了它」还没被用户确认。
183
+ */
184
+ export function pluginRemovalPreviewOf(args: {
185
+ plan: PluginRemovalPlan | undefined;
186
+ sections: readonly { id: SectionId; decision: string }[];
187
+ }): PluginRemovalPreviewView | undefined {
188
+ if (args.plan === undefined) return undefined;
189
+ const section = args.sections.find((s) => s.id === 'plugins');
190
+ const applied = section !== undefined && section.decision !== 'conflict' && section.decision !== 'skip';
191
+ return {
192
+ pluginRemovals: applied ? args.plan.removals.map((r) => ({ name: r.name, version: r.version })) : [],
193
+ pluginRemovalConflicts: args.plan.conflicts.map((c) => ({
194
+ name: c.name, ancestorVersion: c.ancestorVersion, localVersion: c.localVersion,
195
+ })),
196
+ pluginRemovalSkipped: args.plan.kept.map((k) => ({ name: k.name, reason: k.reason })),
197
+ };
198
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * #132 跟随远端删除插件:两个纯函数的行为规格。
3
+ *
4
+ * 接缝(seam):
5
+ * 1. planPluginRemovals —— 「哪些已装插件该被删」的唯一判据(开关、祖先、远端、本机三方);
6
+ * 2. mergePluginsSection —— plugins 分区的按名三方合并(否则通用 JSON 合并对数组两侧各改即冲突,
7
+ * 会把「远端删 X + 本机新装 Y」误报成整分区冲突,让删除永远进不了自动应用)。
8
+ *
9
+ * 两个函数都是纯函数、零 I/O:引擎与 UI 都只读它们的返回值。
10
+ */
11
+ import { test } from 'node:test';
12
+ import assert from 'node:assert/strict';
13
+
14
+ import { mergePluginsSection, planPluginRemovals } from './plugin-removals.ts';
15
+ import type { PluginEntry, PluginsSection } from '../schema/types.ts';
16
+
17
+ function entry(name: string, version: string, extra: Partial<PluginEntry> = {}): PluginEntry {
18
+ return { name, version, isBundle: false, inBundles: [], enabled: true, ...extra };
19
+ }
20
+
21
+ const SELF = 'dsh-config-manager';
22
+
23
+ /* ------------------------------------------------------------------ 计划:删除判定 */
24
+
25
+ test('planPluginRemovals: 开关关闭 → 一个都不删,候选降级为 switch-off', () => {
26
+ const plan = planPluginRemovals({
27
+ enabled: false,
28
+ ancestor: [entry('alpha', '1.2.0')],
29
+ remote: [],
30
+ local: [entry('alpha', '1.2.0')],
31
+ selfName: SELF,
32
+ });
33
+ assert.deepEqual(plan.removals, []);
34
+ assert.deepEqual(plan.kept, [{ name: 'alpha', reason: 'switch-off' }]);
35
+ });
36
+
37
+ test('planPluginRemovals: 祖先有、远端没有、本机未改 → 删(issue 行为表 A→B)', () => {
38
+ const plan = planPluginRemovals({
39
+ enabled: true,
40
+ ancestor: [entry('alpha', '1.2.0'), entry('beta', '0.4.0')],
41
+ remote: [entry('beta', '0.4.0')],
42
+ local: [entry('alpha', '1.2.0'), entry('beta', '0.4.0')],
43
+ selfName: SELF,
44
+ });
45
+ assert.deepEqual(plan.removals, [{ name: 'alpha', version: '1.2.0' }]);
46
+ assert.deepEqual(plan.conflicts, []);
47
+ });
48
+
49
+ test('planPluginRemovals: 本机新装的插件(祖先没有)绝不删', () => {
50
+ const plan = planPluginRemovals({
51
+ enabled: true,
52
+ ancestor: [entry('alpha', '1.2.0')],
53
+ remote: [],
54
+ local: [entry('alpha', '1.2.0'), entry('mine', '9.9.9')],
55
+ selfName: SELF,
56
+ });
57
+ assert.deepEqual(plan.removals, [{ name: 'alpha', version: '1.2.0' }]);
58
+ assert.equal(plan.removals.some((r) => r.name === 'mine'), false);
59
+ });
60
+
61
+ test('planPluginRemovals: 本机版本已变(本地升级)→ 报冲突、不删(issue 行为表 B 升级 X)', () => {
62
+ const plan = planPluginRemovals({
63
+ enabled: true,
64
+ ancestor: [entry('alpha', '1.2.0')],
65
+ remote: [],
66
+ local: [entry('alpha', '1.3.0')],
67
+ selfName: SELF,
68
+ });
69
+ assert.deepEqual(plan.removals, []);
70
+ assert.deepEqual(plan.conflicts, [{ name: 'alpha', reason: 'version-changed', ancestorVersion: '1.2.0', localVersion: '1.3.0' }]);
71
+ });
72
+
73
+ test('planPluginRemovals: bundlesOnly 条目永不删(它由 DSH 自身安装位置解析,不是本 profile 的依赖)', () => {
74
+ const plan = planPluginRemovals({
75
+ enabled: true,
76
+ ancestor: [entry('host-layer', '', { bundlesOnly: true })],
77
+ remote: [],
78
+ local: [entry('host-layer', '', { bundlesOnly: true })],
79
+ selfName: SELF,
80
+ });
81
+ assert.deepEqual(plan.removals, []);
82
+ assert.deepEqual(plan.kept, [{ name: 'host-layer', reason: 'bundles-only' }]);
83
+ });
84
+
85
+ test('planPluginRemovals: 本插件自己永不删(删了等于把正在跑的宿主插件卸掉)', () => {
86
+ const plan = planPluginRemovals({
87
+ enabled: true,
88
+ ancestor: [entry(SELF, '0.2.0')],
89
+ remote: [],
90
+ local: [entry(SELF, '0.2.0')],
91
+ selfName: SELF,
92
+ });
93
+ assert.deepEqual(plan.removals, []);
94
+ assert.deepEqual(plan.kept, [{ name: SELF, reason: 'self' }]);
95
+ });
96
+
97
+ test('planPluginRemovals: 远端仍装着 → 不删', () => {
98
+ const plan = planPluginRemovals({
99
+ enabled: true,
100
+ ancestor: [entry('alpha', '1.2.0')],
101
+ remote: [entry('alpha', '1.2.0')],
102
+ local: [entry('alpha', '1.2.0')],
103
+ selfName: SELF,
104
+ });
105
+ assert.deepEqual(plan.removals, []);
106
+ assert.deepEqual(plan.kept, [{ name: 'alpha', reason: 'still-in-remote' }]);
107
+ });
108
+
109
+ test('planPluginRemovals: 本机根本没装 → 无需卸载(不产生动作,也不报错)', () => {
110
+ const plan = planPluginRemovals({
111
+ enabled: true,
112
+ ancestor: [entry('alpha', '1.2.0')],
113
+ remote: [],
114
+ local: [],
115
+ selfName: SELF,
116
+ });
117
+ assert.deepEqual(plan.removals, []);
118
+ assert.deepEqual(plan.kept, [{ name: 'alpha', reason: 'not-installed' }]);
119
+ });
120
+
121
+ test('planPluginRemovals: 没有祖先(首次同步)→ 一律不删(无法区分「对方删了」与「本机独有」)', () => {
122
+ const plan = planPluginRemovals({
123
+ enabled: true,
124
+ ancestor: undefined,
125
+ remote: [],
126
+ local: [entry('alpha', '1.2.0')],
127
+ selfName: SELF,
128
+ });
129
+ assert.deepEqual(plan.removals, []);
130
+ assert.deepEqual(plan.kept, []);
131
+ });
132
+
133
+ /* ------------------------------------------------------------------ 合并:按名三方 */
134
+
135
+ /** 钩子只在开关打开时参与;单测里显式开启(关闭路径另有用例)。 */
136
+ const ON = { deletePlugins: true };
137
+
138
+ function section(plugins: PluginEntry[], extra: Partial<PluginsSection> = {}): PluginsSection {
139
+ return { version: 1, plugins, patch: [], ...extra };
140
+ }
141
+
142
+ test('mergePluginsSection: 远端删 X、本机新装 Y → 合并结果只留 Y,不报冲突', () => {
143
+ const res = mergePluginsSection(
144
+ section([entry('alpha', '1.2.0'), entry('y', '2.0.0')]),
145
+ section([]),
146
+ section([entry('alpha', '1.2.0')]),
147
+ ON,
148
+ );
149
+ assert.ok(res !== undefined);
150
+ assert.deepEqual(res.conflicts, []);
151
+ assert.deepEqual((res.merged as PluginsSection).plugins.map((p) => p.name), ['y']);
152
+ });
153
+
154
+ test('mergePluginsSection: 本机升级 X、远端删 X → modify-delete 冲突(不静默删也不静默留)', () => {
155
+ const res = mergePluginsSection(
156
+ section([entry('alpha', '1.3.0')]),
157
+ section([]),
158
+ section([entry('alpha', '1.2.0')]),
159
+ ON,
160
+ );
161
+ assert.ok(res !== undefined);
162
+ assert.equal(res.conflicts.length, 1);
163
+ assert.equal(res.conflicts[0]!.path, 'plugins.alpha');
164
+ assert.equal(res.conflicts[0]!.reason, 'modify-delete');
165
+ });
166
+
167
+ test('mergePluginsSection: 两侧同版本 → 保留,两侧同删 → 消失', () => {
168
+ const same = mergePluginsSection(
169
+ section([entry('alpha', '1.2.0')]),
170
+ section([entry('alpha', '1.2.0')]),
171
+ undefined,
172
+ ON,
173
+ );
174
+ assert.deepEqual((same!.merged as PluginsSection).plugins.map((p) => p.name), ['alpha']);
175
+ const both = mergePluginsSection(section([]), section([]), section([entry('alpha', '1.2.0')]), ON);
176
+ assert.deepEqual((both!.merged as PluginsSection).plugins, []);
177
+ });
178
+
179
+ test('mergePluginsSection: 无祖先时本机独有/远端独有都保留(不按删除解释)', () => {
180
+ const res = mergePluginsSection(section([entry('mine', '1.0.0')]), section([entry('theirs', '1.0.0')]), undefined, ON);
181
+ assert.deepEqual(res!.conflicts, []);
182
+ assert.deepEqual((res!.merged as PluginsSection).plugins.map((p) => p.name).sort(), ['mine', 'theirs']);
183
+ });
184
+
185
+ test('mergePluginsSection: 两侧把同一插件改到不同版本 → both-modified 冲突', () => {
186
+ const res = mergePluginsSection(
187
+ section([entry('alpha', '1.3.0')]),
188
+ section([entry('alpha', '1.4.0')]),
189
+ section([entry('alpha', '1.2.0')]),
190
+ ON,
191
+ );
192
+ assert.equal(res!.conflicts.length, 1);
193
+ assert.equal(res!.conflicts[0]!.reason, 'both-modified');
194
+ });
195
+
196
+ test('mergePluginsSection: 插件列表以外的字段(patch 行等)两侧不必相同 —— 不同即交回通用合并', () => {
197
+ const res = mergePluginsSection(
198
+ section([entry('alpha', '1.2.0')], { pnpmWorkspace: 'onlyBuiltDependencies: [a]\n' }),
199
+ section([entry('alpha', '1.2.0')], { pnpmWorkspace: 'onlyBuiltDependencies: [b]\n' }),
200
+ section([entry('alpha', '1.2.0')]),
201
+ ON,
202
+ );
203
+ assert.equal(res, undefined, 'patch/pnpmWorkspace 的口径由通用路径负责,这里不自造第二套');
204
+ });
205
+
206
+ test('mergePluginsSection: 形状不认识 → undefined(畸形数据交通用路径的形状闸门)', () => {
207
+ assert.equal(mergePluginsSection({ version: 2 } as unknown as PluginsSection, section([]), undefined, ON), undefined);
208
+ });
209
+
210
+ test('mergePluginsSection: 开关关着 → 钩子不参与(undefined = 通用合并,行为与 #132 之前逐字一致)', () => {
211
+ assert.equal(
212
+ mergePluginsSection(
213
+ section([entry('alpha', '1.2.0')]),
214
+ section([]),
215
+ section([entry('alpha', '1.2.0')]),
216
+ { deletePlugins: false },
217
+ ),
218
+ undefined,
219
+ '开关关闭时绝不能丢掉本机条目:包还在盘上,下一轮导出会把它当本机独有推回远端 = 复活',
220
+ );
221
+ });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * #132:同步「跟随远端删除插件」的**唯一判据**与 plugins 分区的按名三方合并。
3
+ *
4
+ * 为什么必须单独一个模块:
5
+ * 1. 删除判定是纯逻辑(开关 × 祖先 × 远端 × 本机),散进引擎里既测不了也说不清;
6
+ * 2. plugins 分区不能走通用 JSON 合并 —— `merge.ts` 的 `mergeJsonValues` 对数组一律「两侧都改
7
+ * 且不逐字相等 → 冲突」,而本分区的日常形态恰恰是「A 机卸载了 X、B 机新装了 Y」,通用路径
8
+ * 会把它报成整分区冲突,于是删除永远进不了自动应用(issue #132 的行为表 A→B 走不通)。
9
+ *
10
+ * 删除判据(缺一不可,全部满足才删):
11
+ * - 开关打开(`SyncSelection.deletePlugins`,缺省关);
12
+ * - **祖先**里有它(A 机那轮同步见过的状态)——没有祖先就没有「谁删了它」的证据;
13
+ * - **远端**没有它(= 有人在另一台机器上卸载了);
14
+ * - **本机装着**(卸载才有意义);
15
+ * - 本机版本**仍等于祖先版本**(本地改过 = 用户在自己这台机器上动过它,绝不替用户做决定,
16
+ * 报 `version-changed` 冲突交人裁决);
17
+ * - 不是本插件自己、不是 bundlesOnly 条目(后者由 DSH 自身安装位置解析,`dsh plugin remove`
18
+ * 对它无意义,见 `core/plugin-cli.ts` 的 `isBundlesOnlyEntry`)。
19
+ *
20
+ * 纯函数、零 I/O:引擎调用它拿计划,UI 调用它拿「将删除」清单。
21
+ */
22
+ import type { PluginEntry, PluginsSection, SectionData } from '../schema/types.ts';
23
+ import type { MergeConflict } from './merge.ts';
24
+ import type { GranularMergeOutcome } from './workspace-merge.ts';
25
+ import { isBundlesOnlyEntry } from '../core/plugin-cli.ts';
26
+
27
+ /** 一条「该卸载」的结论(version = 祖先/本机一致的版本,用于报告与回滚重装目标)。 */
28
+ export interface PluginRemoval {
29
+ name: string;
30
+ version: string;
31
+ /** 祖先条目里的安装源(github:/git+/file:/link: 等);重装目标要用它,否则装不回同一来源 */
32
+ spec?: string;
33
+ }
34
+
35
+ /** 未删的原因:每一条都要能对用户解释(报告里逐项列出,绝不静默跳过)。 */
36
+ export type PluginRemovalKeptReason = 'still-in-remote' | 'self' | 'bundles-only' | 'not-installed' | 'switch-off';
37
+
38
+ export interface PluginRemovalConflict {
39
+ name: string;
40
+ reason: 'version-changed';
41
+ ancestorVersion: string;
42
+ localVersion: string;
43
+ }
44
+
45
+ export interface PluginRemovalPlan {
46
+ /** 该执行 `dsh plugin remove` 的插件(顺序 = 祖先顺序,便于报告比对) */
47
+ removals: PluginRemoval[];
48
+ /** 本机改过、远端删了 → 交人裁决(不删也不静默保留) */
49
+ conflicts: PluginRemovalConflict[];
50
+ /** 考察过但不删的条目及原因 */
51
+ kept: { name: string; reason: PluginRemovalKeptReason }[];
52
+ }
53
+
54
+ /**
55
+ * 判据只需要这几个字段:`PluginEntry` 与宿主的 `PluginInfo`(listInstalled 的返回值)都能直接传入,
56
+ * 不必为了调用它先拼一个完整的分区条目。
57
+ */
58
+ export interface PluginRemovalEntry {
59
+ name: string;
60
+ version: string;
61
+ spec?: string;
62
+ bundlesOnly?: boolean;
63
+ }
64
+
65
+ export interface PluginRemovalInput {
66
+ /** 同步选择里的开关(缺省关);关 = 一个都不删 */
67
+ enabled: boolean;
68
+ /** 共同祖先快照里的插件清单(undefined = 没有祖先副本) */
69
+ ancestor: readonly PluginRemovalEntry[] | undefined;
70
+ /** 远端快照里的插件清单(undefined = 远端没有该分区) */
71
+ remote: readonly PluginRemovalEntry[] | undefined;
72
+ /** 本机当前已装(plugins 分区导出的口径) */
73
+ local: readonly PluginRemovalEntry[];
74
+ /** 本插件自己的包名(永不删) */
75
+ selfName: string | undefined;
76
+ }
77
+
78
+ function byName<T extends { name: string }>(list: readonly T[] | undefined): Map<string, T> {
79
+ const map = new Map<string, T>();
80
+ for (const p of list ?? []) {
81
+ if (p !== null && typeof p === 'object' && typeof p.name === 'string' && p.name !== '') map.set(p.name, p);
82
+ }
83
+ return map;
84
+ }
85
+
86
+ /** 判定「该不该删」。调用方只在 `applied` 含 plugins 时才真正执行。 */
87
+ export function planPluginRemovals(input: PluginRemovalInput): PluginRemovalPlan {
88
+ const plan: PluginRemovalPlan = { removals: [], conflicts: [], kept: [] };
89
+ if (input.ancestor === undefined) return plan; // 没有祖先:无删除语义(无法区分「对方删了」与「本机独有」)
90
+ const remote = byName(input.remote);
91
+ const local = byName(input.local);
92
+ for (const a of input.ancestor) {
93
+ const name = a.name;
94
+ if (typeof name !== 'string' || name === '') continue;
95
+ if (remote.has(name)) { plan.kept.push({ name, reason: 'still-in-remote' }); continue; }
96
+ if (input.selfName !== undefined && name === input.selfName) { plan.kept.push({ name, reason: 'self' }); continue; }
97
+ const l = local.get(name);
98
+ if (isBundlesOnlyEntry(a) || (l !== undefined && isBundlesOnlyEntry(l))) {
99
+ plan.kept.push({ name, reason: 'bundles-only' });
100
+ continue;
101
+ }
102
+ if (l === undefined) { plan.kept.push({ name, reason: 'not-installed' }); continue; }
103
+ if (!input.enabled) { plan.kept.push({ name, reason: 'switch-off' }); continue; }
104
+ if (l.version !== a.version) {
105
+ plan.conflicts.push({ name, reason: 'version-changed', ancestorVersion: a.version, localVersion: l.version });
106
+ continue;
107
+ }
108
+ plan.removals.push({ name, version: a.version, ...(a.spec === undefined ? {} : { spec: a.spec }) });
109
+ }
110
+ return plan;
111
+ }
112
+
113
+ /* --------------------------------------------------------------- 分区级三方合并 */
114
+
115
+ /** 形状闸门:不认识就交回通用路径(畸形数据由通用路径拒绝,这里不另造一套判定)。 */
116
+ function asPlugins(data: SectionData | undefined): PluginsSection | undefined {
117
+ if (data === null || typeof data !== 'object') return undefined;
118
+ const obj = data as { version?: unknown; plugins?: unknown };
119
+ if (obj.version !== 1 || !Array.isArray(obj.plugins)) return undefined;
120
+ return data as PluginsSection;
121
+ }
122
+
123
+ /** 决定「同一个插件是否还是同一个东西」的身份字段(version + 来源 spec + bundlesOnly 形态)。 */
124
+ function entryKey(e: PluginEntry): string {
125
+ return [e.version ?? '', e.spec ?? '', e.bundlesOnly === true ? '1' : '0'].join('\u0000');
126
+ }
127
+
128
+ /** 插件列表以外的字段(patch 行 / pnpm-workspace 原文 / 本地 tarball / patch 文件)必须两侧相等才介入。 */
129
+ function sameShell(l: PluginsSection, r: PluginsSection): boolean {
130
+ const pick = (s: PluginsSection): string => JSON.stringify({
131
+ patch: s.patch ?? [],
132
+ pnpmWorkspace: s.pnpmWorkspace ?? null,
133
+ localTarballs: s.localTarballs ?? [],
134
+ patchFiles: s.patchFiles ?? [],
135
+ });
136
+ return pick(l) === pick(r);
137
+ }
138
+
139
+ /**
140
+ * plugins 分区的按名三方合并(`merge.ts` 的 `GRANULAR_MERGES.plugins`)。
141
+ *
142
+ * 逐名规则与 git 同口径,祖先只用于判断「谁动了它」,绝不猜:
143
+ * - 两侧都有:身份相同 → 保留;某一侧与祖先相同 → 取另一侧;两侧都变(或没有祖先)→ both-modified 冲突;
144
+ * - 只有本机:有祖先且与祖先相同 → 跟随远端删除(真删除);无祖先 → 本机独有,保留;有祖先且不同 →
145
+ * modify-delete 冲突(用户在 A 机卸载、B 机却升级过它,不能替用户选);
146
+ * - 只有远端:有祖先且与祖先相同 → 本机删除,跟随(不复活);无祖先 → 远端独有,采纳;有祖先且不同 →
147
+ * delete-modify 冲突;
148
+ * - 两侧都没有:消失。
149
+ *
150
+ * 插件列表以外的字段不一致时返回 `undefined`:patch 行/pnpm-workspace 有各自的既有口径,
151
+ * 在这里再造一套合并只会和通用路径打架(通用路径会整分区处理,其中包含 plugins 数组的旧行为)。
152
+ */
153
+ export function mergePluginsSection(
154
+ local: SectionData,
155
+ remote: SectionData,
156
+ ancestor: SectionData | undefined,
157
+ hooks: { deletePlugins?: boolean } = {},
158
+ ): GranularMergeOutcome | undefined {
159
+ // 开关关着 → 钩子不参与(交回通用合并 = 与 #132 之前逐字一致)。若照常「跟随远端删除」,
160
+ // 合并结果会丢掉本机条目:插件包还在盘上,下一轮导出会把它当「本机独有」推回远端 = 复活。
161
+ if (hooks.deletePlugins !== true) return undefined;
162
+ const l = asPlugins(local);
163
+ const r = asPlugins(remote);
164
+ if (l === undefined || r === undefined) return undefined;
165
+ const a = ancestor === undefined ? undefined : asPlugins(ancestor);
166
+ if (ancestor !== undefined && a === undefined) return undefined;
167
+ if (!sameShell(l, r)) return undefined;
168
+
169
+ const aMap = byName(a?.plugins);
170
+ const rMap = byName(r.plugins);
171
+ const merged: PluginEntry[] = [];
172
+ const conflicts: MergeConflict[] = [];
173
+ let mergePoints = 0;
174
+ const conflict = (path: string, reason: 'both-modified' | 'modify-delete' | 'delete-modify', lp: PluginEntry | undefined, rp: PluginEntry | undefined, ap: PluginEntry | undefined): void => {
175
+ conflicts.push({ path, kind: 'key', reason, autoMergeAttempted: false, local: lp, remote: rp, ancestor: ap });
176
+ };
177
+
178
+ for (const lp of l.plugins) {
179
+ const name = lp.name;
180
+ const rp = rMap.get(name);
181
+ const ap = aMap.get(name);
182
+ if (rp !== undefined) {
183
+ if (entryKey(lp) === entryKey(rp)) { merged.push(lp); continue; }
184
+ const lChanged = ap === undefined || entryKey(lp) !== entryKey(ap);
185
+ const rChanged = ap === undefined || entryKey(rp) !== entryKey(ap);
186
+ if (lChanged && rChanged) { conflict(`plugins.${name}`, 'both-modified', lp, rp, ap); continue; }
187
+ if (lChanged) { merged.push(lp); mergePoints += 1; continue; }
188
+ merged.push(rp);
189
+ mergePoints += 1;
190
+ continue;
191
+ }
192
+ // 只有本机有
193
+ if (ap === undefined) { merged.push(lp); mergePoints += 1; continue; } // 本机独有
194
+ if (entryKey(lp) === entryKey(ap)) { mergePoints += 1; continue; } // 本机未改、远端删 → 跟随删除
195
+ conflict(`plugins.${name}`, 'modify-delete', lp, undefined, ap);
196
+ }
197
+ // 只有远端有的
198
+ for (const rp of r.plugins) {
199
+ const name = rp.name;
200
+ if (l.plugins.some((p) => p.name === name)) continue;
201
+ const ap = aMap.get(name);
202
+ if (ap === undefined) { merged.push(rp); mergePoints += 1; continue; } // 远端独有
203
+ if (entryKey(rp) === entryKey(ap)) { mergePoints += 1; continue; } // 远端未改、本机删 → 跟随删除
204
+ conflict(`plugins.${name}`, 'delete-modify', undefined, rp, ap);
205
+ }
206
+ if (conflicts.length > 0) return { merged: l as SectionData, conflicts, mergePoints };
207
+ return { merged: { ...l, plugins: merged } as SectionData, conflicts: [], mergePoints };
208
+ }