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
@@ -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';
@@ -190,6 +195,8 @@ export declare const zh: {
190
195
  readonly 'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})';
191
196
  readonly 'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写';
192
197
  readonly 'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉';
198
+ readonly 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)';
199
+ readonly 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动';
193
200
  readonly 'host.fsPathEscape': '路径越界: {path}';
194
201
  readonly 'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)';
195
202
  readonly 'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)';
@@ -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',
@@ -179,6 +184,8 @@ export const zh = {
179
184
  'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})',
180
185
  'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写',
181
186
  'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉',
187
+ 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)',
188
+ 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动',
182
189
  'host.fsPathEscape': '路径越界: {path}',
183
190
  'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)',
184
191
  'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)',
@@ -655,6 +662,11 @@ export const en = {
655
662
  'restore.uninstallFailedExit': 'dsh plugin remove {name} failed (exit {code}): {tail}',
656
663
  'restore.noOutput': 'no output',
657
664
  'restore.pluginRemoveFailed': 'Uninstall failed',
665
+ 'restore.pluginInstall': 'Reinstall plugin {name}@{version} (removed earlier to follow the remote)',
666
+ 'restore.pluginInstallAlreadyPresent': 'Plugin {name} is already installed here; nothing to reinstall',
667
+ 'restore.pluginInstallFailed': 'Reinstall failed',
668
+ 'restore.installFailedCode': 'dsh plugin add {name} failed ({code}): {message}',
669
+ 'restore.installFailedExit': 'dsh plugin add {name} failed (exit {code}): {tail}',
658
670
  'restore.unknownAction': 'Unknown action {kind}: {description}',
659
671
  'restore.missingTargetBlob': 'Restore action is missing target/blobPath',
660
672
  'restore.missingTarget': 'Restore action is missing target',
@@ -687,6 +699,8 @@ export const en = {
687
699
  'host.patchUnsupported': 'dsh-config-manager only manages {user} and the profile {profile} (received {file})',
688
700
  'host.patchUnreadable': 'Cannot read patch layer {file} ({reason}): its patch rows are not exported or synced, and the file is left untouched',
689
701
  'host.patchRefuseClobber': 'Refusing to rewrite patch layer {file}: it cannot be parsed ({reason}), and rewriting would delete every row that could not be read',
702
+ 'host.patchRefusePromote': 'Refusing to write patch layer {file}: it would turn {ids} from insert (add) into top-level rows (override); the file is untouched (top-level rows override by id and are dropped entirely when not found)',
703
+ 'host.patchSemanticDrift': 'Structure self-check failed after serializing patch layer {file} ({detail}): the write was refused and the file is untouched',
690
704
  'host.fsPathEscape': 'Path outside home directory: {path}',
691
705
  'host.activationRowFailed': 'Plugin {pkg} is installed, but writing the activation row into the profile patch failed: {reason} (the plugin may be inactive until restart; retrying the install after fixing is idempotent)',
692
706
  'host.syncTokenWriteFailed': 'Failed to write the token into DSH credentials: {reason} (configure {ref} in DSH credential management, then retry)',
@@ -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,
@@ -0,0 +1,65 @@
1
+ /**
2
+ * patch 文档的**结构重建**(issue #133)。
3
+ *
4
+ * 为什么需要独立一层:`cordis.patch.yml` 的两种形态语义**不等价**(宿主 dsh-app-boot 的
5
+ * readProfilePatches 合并循环):
6
+ * - 顶层 `- id: X` → 按 id **覆盖**已存在的条目;id 查不到时打 `patch: entry "X" not found` 丢弃;
7
+ * - `- insert:` 块成员 → **新增**条目(`data.push(...clone)`,唯一的新增路径)。
8
+ * 此前重建时把所有行(含 insert 成员)统一输出成顶层行,于是「只能靠 insert 新增」的条目
9
+ * (典型是 MCP server)在 DSH 侧全部失效 —— 一条 update 就够触发。
10
+ *
11
+ * 本模块只做**结构**:不读文件、不碰 YAML(core 层零依赖),输入是已解析的文档 + 变更清单,
12
+ * 输出是重建后的条目数组与两套 id。序列化与自检在宿主门面(DshPatchFileFacade)里做。
13
+ *
14
+ * 三条不变量:
15
+ * ① 原本是 insert 成员的 id,重建后仍在 insert 块里(update 不改变归属);
16
+ * ② 新增条目(`action:'insert'` 且文档里没有)落进 insert 块,而不是顶层行;
17
+ * ③ 任一 id 不得同时出现在顶层与 insert 两处 —— 计划阶段就抛错(防御性,正常路径不可达)。
18
+ */
19
+ export interface PatchLineChange {
20
+ lineId: string;
21
+ raw: unknown;
22
+ action: 'insert' | 'update' | 'remove';
23
+ }
24
+ export interface PatchDocumentPlan {
25
+ /** 重建后的文档条目(顺序尽量贴原文档:顶层行原位、insert 块原位、新增项追加在尾部) */
26
+ items: unknown[];
27
+ /** 落在 insert 块里的 id(按输出顺序) */
28
+ insertIds: string[];
29
+ /** 落在顶层行里的 id(按输出顺序) */
30
+ topLevelIds: string[];
31
+ }
32
+ /** 计划会把 insert 成员提升成顶层行:调用方必须放弃这次写入(零写入)。 */
33
+ export declare class PatchPromoteRefusedError extends Error {
34
+ readonly ids: string[];
35
+ constructor(ids: string[]);
36
+ }
37
+ /** 读出文档里的 insert 成员 id 与顶层行 id(自检与测试共用;不判重、保持文档顺序)。 */
38
+ export declare function describePatchDocument(doc: unknown): {
39
+ insertIds: string[];
40
+ topLevelIds: string[];
41
+ };
42
+ /**
43
+ * 重建成 patch 文档条目。
44
+ *
45
+ * `doc` 是已解析的原文档(非数组视为空文档);顺序按原布局保留,新增项追加在尾部。
46
+ */
47
+ export declare function planPatchDocument(doc: unknown, changes: readonly PatchLineChange[]): PatchDocumentPlan;
48
+ /**
49
+ * 计划布局与观察到的布局是否一致(写后自检用,issue #133)。
50
+ * 一致返回 `null`;不一致返回一句可直接进错误文案的差异说明(只含 id,不含值)。
51
+ */
52
+ export declare function describePatchLayoutDrift(planned: {
53
+ insertIds: readonly string[];
54
+ topLevelIds: readonly string[];
55
+ }, observed: {
56
+ insertIds: readonly string[];
57
+ topLevelIds: readonly string[];
58
+ }): string | null;
59
+ /**
60
+ * 跨层提升检查(issue #133):`topLevelIds` 里哪些是**另一层文档**的 `- insert:` 成员。
61
+ *
62
+ * 命中就意味着「把新增改写成覆盖」——目标作用域里那条通常不存在,宿主会 `not found` 丢弃。
63
+ * `otherDoc` 读不到或解析不了时调用方传 `undefined`,本函数返回空(守卫只做加强)。
64
+ */
65
+ export declare function promotedTopLevelIds(otherDoc: unknown, topLevelIds: readonly string[]): string[];
@@ -0,0 +1,161 @@
1
+ /** 计划会把 insert 成员提升成顶层行:调用方必须放弃这次写入(零写入)。 */
2
+ export class PatchPromoteRefusedError extends Error {
3
+ ids;
4
+ constructor(ids) {
5
+ super('patch rebuild would promote insert members to top-level rows: ' + ids.join(', '));
6
+ this.name = 'PatchPromoteRefusedError';
7
+ this.ids = ids;
8
+ }
9
+ }
10
+ function entryId(value) {
11
+ if (value === null || typeof value !== 'object')
12
+ return null;
13
+ const id = value['id'];
14
+ return typeof id === 'string' && id !== '' ? id : null;
15
+ }
16
+ function blockMembers(value) {
17
+ if (value === null || typeof value !== 'object')
18
+ return null;
19
+ const insert = value['insert'];
20
+ if (!Array.isArray(insert))
21
+ return null;
22
+ return insert.filter((entry) => entry !== null && typeof entry === 'object');
23
+ }
24
+ /** 读出文档里的 insert 成员 id 与顶层行 id(自检与测试共用;不判重、保持文档顺序)。 */
25
+ export function describePatchDocument(doc) {
26
+ const insertIds = [];
27
+ const topLevelIds = [];
28
+ if (!Array.isArray(doc))
29
+ return { insertIds, topLevelIds };
30
+ for (const item of doc) {
31
+ const members = blockMembers(item);
32
+ if (members !== null) {
33
+ for (const member of members) {
34
+ const id = entryId(member);
35
+ if (id !== null)
36
+ insertIds.push(id);
37
+ }
38
+ continue;
39
+ }
40
+ const id = entryId(item);
41
+ if (id !== null)
42
+ topLevelIds.push(id);
43
+ }
44
+ return { insertIds, topLevelIds };
45
+ }
46
+ /**
47
+ * 重建成 patch 文档条目。
48
+ *
49
+ * `doc` 是已解析的原文档(非数组视为空文档);顺序按原布局保留,新增项追加在尾部。
50
+ */
51
+ export function planPatchDocument(doc, changes) {
52
+ const state = new Map();
53
+ const layout = [];
54
+ if (Array.isArray(doc)) {
55
+ for (const item of doc) {
56
+ const members = blockMembers(item);
57
+ if (members !== null) {
58
+ const ids = [];
59
+ for (const member of members) {
60
+ const id = entryId(member);
61
+ if (id === null)
62
+ continue;
63
+ ids.push(id);
64
+ if (!state.has(id))
65
+ state.set(id, { raw: member, inInsert: true });
66
+ }
67
+ if (ids.length > 0)
68
+ layout.push({ kind: 'block', ids });
69
+ continue;
70
+ }
71
+ const id = entryId(item);
72
+ if (id === null)
73
+ continue;
74
+ layout.push({ kind: 'row', id });
75
+ if (!state.has(id))
76
+ state.set(id, { raw: item, inInsert: false });
77
+ }
78
+ }
79
+ for (const change of changes) {
80
+ if (change.action === 'remove') {
81
+ state.delete(change.lineId);
82
+ continue;
83
+ }
84
+ const previous = state.get(change.lineId);
85
+ // 归属只由**原文档**决定:更新一条既有 insert 成员不会把它搬到顶层;新增才按动作分流
86
+ const inInsert = previous !== undefined ? previous.inInsert : change.action === 'insert';
87
+ state.set(change.lineId, { raw: change.raw, inInsert });
88
+ }
89
+ const items = [];
90
+ const insertIds = [];
91
+ const topLevelIds = [];
92
+ const emitted = new Set();
93
+ const emitRow = (id) => {
94
+ const slot = state.get(id);
95
+ if (slot === undefined || emitted.has(id))
96
+ return;
97
+ emitted.add(id);
98
+ items.push(slot.raw);
99
+ topLevelIds.push(id);
100
+ };
101
+ const emitBlock = (ids) => {
102
+ const members = ids.filter((id) => {
103
+ const slot = state.get(id);
104
+ return slot !== undefined && slot.inInsert && !emitted.has(id);
105
+ });
106
+ if (members.length === 0)
107
+ return;
108
+ for (const id of members)
109
+ emitted.add(id);
110
+ items.push({ insert: members.map((id) => state.get(id).raw) });
111
+ insertIds.push(...members);
112
+ };
113
+ for (const slot of layout) {
114
+ if (slot.kind === 'row')
115
+ emitRow(slot.id);
116
+ else
117
+ emitBlock(slot.ids);
118
+ }
119
+ // 新写入、且原文档布局里没有的 id:insert 动作进块,update 动作保持旧的 upsert 语义(顶层行)
120
+ for (const [id, slot] of state) {
121
+ if (emitted.has(id))
122
+ continue;
123
+ if (slot.inInsert)
124
+ continue;
125
+ emitRow(id);
126
+ }
127
+ emitBlock([...state.keys()].filter((id) => !emitted.has(id)));
128
+ // 不变量③:同一 id 不得两种身份并存(正常路径不可达;坏了就拒写,别写出一份语义分裂的文件)
129
+ const promoted = insertIds.filter((id) => topLevelIds.includes(id));
130
+ if (promoted.length > 0)
131
+ throw new PatchPromoteRefusedError(promoted);
132
+ return { items, insertIds, topLevelIds };
133
+ }
134
+ /**
135
+ * 计划布局与观察到的布局是否一致(写后自检用,issue #133)。
136
+ * 一致返回 `null`;不一致返回一句可直接进错误文案的差异说明(只含 id,不含值)。
137
+ */
138
+ export function describePatchLayoutDrift(planned, observed) {
139
+ const same = planned.insertIds.length === observed.insertIds.length
140
+ && planned.topLevelIds.length === observed.topLevelIds.length
141
+ && planned.insertIds.every((id, i) => id === observed.insertIds[i])
142
+ && planned.topLevelIds.every((id, i) => id === observed.topLevelIds[i]);
143
+ if (same)
144
+ return null;
145
+ const fmt = (label, ids) => label + '=[' + ids.join(', ') + ']';
146
+ return 'planned ' + fmt('insert', planned.insertIds) + ' ' + fmt('top-level', planned.topLevelIds)
147
+ + '; got ' + fmt('insert', observed.insertIds) + ' ' + fmt('top-level', observed.topLevelIds);
148
+ }
149
+ /**
150
+ * 跨层提升检查(issue #133):`topLevelIds` 里哪些是**另一层文档**的 `- insert:` 成员。
151
+ *
152
+ * 命中就意味着「把新增改写成覆盖」——目标作用域里那条通常不存在,宿主会 `not found` 丢弃。
153
+ * `otherDoc` 读不到或解析不了时调用方传 `undefined`,本函数返回空(守卫只做加强)。
154
+ */
155
+ export function promotedTopLevelIds(otherDoc, topLevelIds) {
156
+ if (topLevelIds.length === 0)
157
+ return [];
158
+ const insertMembers = new Set(describePatchDocument(otherDoc).insertIds);
159
+ return topLevelIds.filter((id) => insertMembers.has(id));
160
+ }
161
+ //# sourceMappingURL=patch-document.js.map
@@ -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
  /** 失败清单 */