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
@@ -34,6 +34,7 @@ const SAVED_TICK_MS = 2400
34
34
  /** 通道配置弹窗的表单字段补丁(onFormChange 入参:git/webdav + 云端点两组)。 */
35
35
  export type ChannelFormPatch = {
36
36
  repoUrl?: string
37
+ gitSubdir?: string
37
38
  token?: string
38
39
  webdavUrl?: string
39
40
  webdavUsername?: string
@@ -91,7 +92,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
91
92
  }) {
92
93
  const channel = form.channel
93
94
  const {
94
- repoUrl, token, webdavUrl, webdavUsername, webdavPassword,
95
+ repoUrl, gitSubdir, token, webdavUrl, webdavUsername, webdavPassword,
95
96
  s3Provider, s3Endpoint, s3Region, s3Bucket, s3Prefix, s3AccessKeyId, s3PathStyle, s3Secret,
96
97
  gistId, gistApiBaseUrl, gistFilePrefix, gistToken,
97
98
  } = form
@@ -162,6 +163,19 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
162
163
  }}
163
164
  />
164
165
  </div>
166
+ <div className={css.field}>
167
+ <span className={css.fieldLabel}>{t('config.gitSubdir')} <InfoHint text={t('config.gitSubdirHint')} label={t('common.infoHint')} /></span>
168
+ <input aria-label={t('config.gitSubdir')}
169
+ type="text"
170
+ className={css.input}
171
+ value={gitSubdir}
172
+ placeholder={t('config.gitSubdirPlaceholder')}
173
+ disabled={busy}
174
+ onChange={(e: ChangeEvent<HTMLInputElement>) => {
175
+ onFormChange({ gitSubdir: e.target.value }) // 改动自动保存(防抖;空 = 仓库根)
176
+ }}
177
+ />
178
+ </div>
165
179
  <div className={css.field}>
166
180
  <span className={css.fieldLabel}>
167
181
  {t('config.token')}
@@ -132,6 +132,8 @@ interface SelectionPatch {
132
132
  sessionsInclude?: string[]
133
133
  encrypt?: boolean
134
134
  includeSecrets?: boolean
135
+ /** 跟随远端删除插件(issue 132;破坏性,缺省关) */
136
+ deletePlugins?: boolean
135
137
  /** 非空 = 写入本机凭据库(长期复用) */
136
138
  encryptPassword?: string
137
139
  decryptPassword?: string
@@ -148,6 +150,8 @@ interface SyncUiState {
148
150
  channel: SyncChannel
149
151
  /** git 通道表单 */
150
152
  repoUrl: string
153
+ /** 仓库内子目录前缀(空 = 仓库根;issue 131) */
154
+ gitSubdir: string
151
155
  /** 仅内存:成功后清空(已写入 DSH credentials),绝不持久化 */
152
156
  token: string
153
157
  /** webdav 通道表单 */
@@ -232,6 +236,7 @@ const initial: SyncUiState = {
232
236
  // 用户最近选择的通道优先(localStorage 记住);无则缺省 git,由 loadStatus 按配置回填
233
237
  channel: readStoredChannel() ?? 'git',
234
238
  repoUrl: '',
239
+ gitSubdir: '',
235
240
  token: '',
236
241
  webdavUrl: '',
237
242
  webdavUsername: '',
@@ -291,6 +296,7 @@ function initFromStore(): SyncUiState {
291
296
  // 避免升级后把用户此前记住的 webdav 通道冲掉
292
297
  channel: resolveInitialChannel(s.channel, readStoredChannel()),
293
298
  repoUrl: s.repoUrl,
299
+ gitSubdir: s.gitSubdir,
294
300
  token: s.token,
295
301
  webdavUrl: s.webdavUrl,
296
302
  webdavUsername: s.webdavUsername,
@@ -491,6 +497,7 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
491
497
  statusInfo: info,
492
498
  channel: remembered ?? savedChannel,
493
499
  repoUrl: info.repoUrl ?? '',
500
+ gitSubdir: info.subdir ?? '',
494
501
  webdavUrl: info.webdav?.url ?? '',
495
502
  webdavUsername: info.webdav?.username ?? '',
496
503
  catalog,
@@ -609,6 +616,7 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
609
616
  const formOf = (s: SyncUiState): SyncFormSnapshot => ({
610
617
  channel: s.channel,
611
618
  repoUrl: s.repoUrl,
619
+ gitSubdir: s.gitSubdir,
612
620
  token: s.token,
613
621
  webdavUrl: s.webdavUrl,
614
622
  webdavUsername: s.webdavUsername,
@@ -963,6 +971,12 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
963
971
  void saveSelection(channel, linked.selectionPatch)
964
972
  }
965
973
 
974
+ /** 「跟随远端删除插件」开关(issue 132;勾上 = 显式授权手动与自动都删,执行在宿主 applyMergePlan)。 */
975
+ const setDeletePlugins = (channel: SyncChannel, next: boolean): void => {
976
+ patchChannelOf(channel, { deletePlugins: next })
977
+ void saveSelection(channel, { deletePlugins: next })
978
+ }
979
+
966
980
  /** 当前通道导出密钥开关(持久化)。勾选时自动联动选中加密(密钥绝不明文进同步通道)。 */
967
981
  const setIncludeSecrets = (channel: SyncChannel, next: boolean): void => {
968
982
  // t42:勾「导出密钥」自动打开加密(密钥绝不明文上行)——规则在 ui/sync-settings-view.ts
@@ -1424,12 +1438,14 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
1424
1438
  sections={chState.syncSections}
1425
1439
  sessionsLimit={chState.sessionsLimit}
1426
1440
  sessionsInclude={chState.sessionsInclude}
1441
+ deletePlugins={chState.deletePlugins}
1427
1442
  sessionNode={sessionPickerNode}
1428
1443
  sessionPending={sessionInvPending}
1429
1444
  sessionFailed={sessionInvFailedRef.current}
1430
1445
  onToggleSection={(id, checked) => { toggleSyncSection(state.channel, id, checked) }}
1431
1446
  onSessionsLimit={(value) => { setSessionsLimit(state.channel, value) }}
1432
1447
  onSessionsInclude={(ids) => { setSessionsInclude(state.channel, ids) }}
1448
+ onToggleDeletePlugins={(next) => { setDeletePlugins(state.channel, next) }}
1433
1449
  onClose={() => { setSectionPickerOpen(false) }}
1434
1450
  />
1435
1451
  {/* v3:页面级的加密/解密/快照列表卡已移入各自的通道卡(见 renderChannelCard)。 */}
@@ -32,7 +32,7 @@ import css from '../config-manager.module.css'
32
32
  * (与导出选择器一致的弹窗语义),因此底部只有「完成」—— 没有「取消」
33
33
  * (取消会让用户以为改动被丢弃)。
34
34
  */
35
- export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalog, sections, sessionsLimit, sessionsInclude, sessionNode, sessionPending, sessionFailed, onToggleSection, onSessionsLimit, onSessionsInclude, onClose }: {
35
+ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalog, sections, sessionsLimit, sessionsInclude, deletePlugins, sessionNode, sessionPending, sessionFailed, onToggleSection, onSessionsLimit, onSessionsInclude, onToggleDeletePlugins, onClose }: {
36
36
  t: TranslateNS<'config-manager-sync'>
37
37
  /** ui 命名空间的翻译器(UiT):分区描述与分组说明的**字典键**由它解析(英文界面零中文) */
38
38
  uiT: UiT
@@ -45,6 +45,8 @@ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalo
45
45
  sessionsLimit: number
46
46
  /** 显式点名的会话单元 id(非空时优先于 sessionsLimit) */
47
47
  sessionsInclude: readonly string[]
48
+ /** 跟随远端删除插件(issue 132;只在 plugins 分区被勾选时可操作) */
49
+ deletePlugins: boolean
48
50
  /** 会话单元清单(未取到 / 读取失败 → undefined) */
49
51
  sessionNode: SelectionSection | undefined
50
52
  sessionPending: boolean
@@ -53,6 +55,7 @@ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalo
53
55
  onSessionsLimit: (value: number) => void
54
56
  /** 点名结果(空数组 = 回到「最新 N 个」模式) */
55
57
  onSessionsInclude: (ids: string[]) => void
58
+ onToggleDeletePlugins: (next: boolean) => void
56
59
  onClose: () => void
57
60
  }) {
58
61
  /** 弹窗内的两个视图:分区目录 / 会话逐项勾选(同一 Modal,不嵌套第二个遮罩) */
@@ -178,6 +181,19 @@ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalo
178
181
  </div>
179
182
  </div>
180
183
  )}
184
+ {/* issue 132:插件专属的「跟随远端删除」。放在 Checkbox **之外**(同 sessions
185
+ 参数的理由:Checkbox 内部是 label,嵌进去点开关会连带切换分区勾选)。
186
+ 只在 plugins 已被勾选时出现 —— 没勾这个分区,这条开关没有任何作用对象。 */}
187
+ {s.id === 'plugins' && sections.includes('plugins') && (
188
+ <div className={css.controlRow}>
189
+ <Checkbox
190
+ checked={deletePlugins}
191
+ onChange={onToggleDeletePlugins}
192
+ label={<span className={css.categoryName}>{t('mode.deletePlugins')}</span>}
193
+ />
194
+ <InfoHint text={t('mode.deletePluginsHint')} label={t('common.infoHint')} />
195
+ </div>
196
+ )}
181
197
  </div>
182
198
  ))}
183
199
  </div>
@@ -68,6 +68,8 @@ export interface SyncStatusResponse {
68
68
  configured: boolean;
69
69
  /** git 通道:已配置的仓库地址(不含 token,可回显;与当前通道无关,配置过即返回) */
70
70
  repoUrl?: string;
71
+ /** git 通道:仓库内子目录前缀('' / 缺省 = 仓库根;issue 131,供表单回填) */
72
+ subdir?: string;
71
73
  /** git 通道:DSH credentials 中是否已存在 token(describe 只报状态,值永不返回) */
72
74
  credentialConfigured: boolean;
73
75
  credentialWritable: boolean;
@@ -14,6 +14,9 @@ export const zh = {
14
14
  'config.title': '仓库配置',
15
15
  'config.repoUrl': '仓库地址',
16
16
  'config.repoUrlHint': 'Git 私有仓库地址(https / ssh / 本地路径)。认证 token 请使用下方凭据字段,不要拼入地址。',
17
+ 'config.gitSubdir': '仓库内子目录',
18
+ 'config.gitSubdirHint': '留空 = 直接用仓库根目录(旧行为)。填了就把同步内容放进该子目录(如「DSH备份」或「tools/dsh」):多个工具共用一个私有仓库时各自独立。切换子目录不会搬动已有快照 —— 换前缀前先重建工作副本。',
19
+ 'config.gitSubdirPlaceholder': 'DSH备份(可选)',
17
20
  'config.token': '认证 token',
18
21
  'config.tokenHint': '将安全写入 DSH credentials(引用名 {ref}),不会写入同步文件或日志。留空表示沿用已保存的凭据。',
19
22
  'config.tokenSaved': '凭据已配置',
@@ -184,6 +187,8 @@ export const zh = {
184
187
  'mode.hint': '同步范围 = 勾选的分区集合(默认已勾选推荐分区,可随时改)。',
185
188
  'mode.selectedCount': '已勾选 {n} / {total}',
186
189
  'mode.sectionsHint': '默认可同步的是可移植分区;平台相关分区(MCP 服务器)与设备相关分区(插件文件、凭据状态、历史会话)只有你在这里主动勾选才参与同步。',
190
+ 'mode.deletePlugins': '跟随远端删除插件',
191
+ 'mode.deletePluginsHint': '远端快照里已经没有、本机也没改过的插件会被卸载(判断依据是共同祖先里还有它 —— 那只可能是别处删掉了)。卸载只发生在插件分区真正被应用的那一轮;失败逐项提示、其余同步照常完成。desktop 保留档案与宿主自己不会被删。',
187
192
  'mode.atLeastOne': '请至少勾选一个同步分区',
188
193
  'mode.sectionPortable': '可移植',
189
194
  'mode.sectionRecommended': '推荐',
@@ -476,6 +481,9 @@ export const en: Record<keyof typeof zh, string> = {
476
481
  'config.title': 'Repository',
477
482
  'config.repoUrl': 'Repository URL',
478
483
  'config.repoUrlHint': 'Private Git repository URL (https / ssh / local path). Use the credential field below for the auth token; never embed it in the URL.',
484
+ 'config.gitSubdir': 'Subdirectory in repo',
485
+ 'config.gitSubdirHint': 'Blank = use the repository root (previous behavior). When set, sync content goes into that subdirectory (e.g. "DSH-backup" or "tools/dsh"), so several tools can share one private repo independently. Changing it does not move existing snapshots — rebuild the working copy before switching prefixes.',
486
+ 'config.gitSubdirPlaceholder': 'DSH-backup (optional)',
479
487
  'config.token': 'Auth token',
480
488
  'config.tokenHint': 'Securely written into DSH credentials (ref {ref}); never written into sync files or logs. Leave blank to reuse the saved credential.',
481
489
  'config.tokenSaved': 'Credential configured',
@@ -636,6 +644,8 @@ export const en: Record<keyof typeof zh, string> = {
636
644
  'mode.hint': 'Sync scope = the ticked set of sections (recommended sections are ticked by default and can be changed any time).',
637
645
  'mode.selectedCount': '{n} / {total} selected',
638
646
  'mode.sectionsHint': 'Portable sections sync by default; platform-dependent sections (MCP servers) and device-specific sections (plugin files, credentials status, sessions) only participate when you explicitly tick them here.',
647
+ 'mode.deletePlugins': 'Delete plugins to follow the remote',
648
+ 'mode.deletePluginsHint': 'Plugins that are gone from the remote snapshot and unmodified locally get uninstalled (the evidence is the common ancestor still listing them — only another device could have removed them). Removal runs only in the round where the plugins section is actually applied; failures are reported per item and the rest of the sync still completes. The reserved desktop profile and the host itself are never removed.',
639
649
  'mode.atLeastOne': 'Select at least one section to sync',
640
650
  'mode.sectionPortable': 'Portable',
641
651
  'mode.sectionRecommended': 'Recommended',
@@ -349,6 +349,11 @@ export interface ChannelSyncState {
349
349
  encrypt: boolean
350
350
  /** 手动推送默认导出真实凭据值(持久化开关;必须同时 encrypt) */
351
351
  includeSecrets: boolean
352
+ /**
353
+ * 跟随远端删除插件(issue 132;持久化开关,缺省关)。
354
+ * 勾上即授权手动合并与自动同步都执行 `dsh plugin remove`。
355
+ */
356
+ deletePlugins: boolean
352
357
  /** 加密密码输入框(仅内存;已保存的密码在 DSH 凭据库里,不回显) */
353
358
  encryptPassword: string
354
359
  /** 加密密码确认(仅内存) */
@@ -398,6 +403,7 @@ export function defaultChannelSyncState(): ChannelSyncState {
398
403
  sessionsInclude: [],
399
404
  encrypt: false,
400
405
  includeSecrets: false,
406
+ deletePlugins: false,
401
407
  encryptPassword: '',
402
408
  encryptPasswordConfirm: '',
403
409
  decryptPassword: '',
@@ -20,7 +20,7 @@ import { MCP_CONNECTOR_STORE_REL } from './mcp-connector-store.ts';
20
20
  import type { SectionId } from '../schema/types.ts';
21
21
  import type {
22
22
  ConfigAdapter, FileSystemFacade, HostContext, HostFileBackup, ImportPlan, PlanItem, Snapshot,
23
- SnapshotEntry, SnapshotManifest, SnapshotStatus, SnapshotStore, SnapshotTarget,
23
+ SnapshotEntry, SnapshotManifest, SnapshotPluginRemoval, SnapshotStatus, SnapshotStore, SnapshotTarget,
24
24
  } from './types.ts';
25
25
 
26
26
  /**
@@ -960,6 +960,26 @@ export class FileSnapshotStore implements SnapshotStore {
960
960
  snapshot.status = status;
961
961
  await atomicWriteFile(file, JSON.stringify(snapshot, null, 2));
962
962
  }
963
+
964
+ /**
965
+ * 记录本轮跟删的插件(issue #132 undo 线索):只重写 snapshot.json 的 pluginRemovals 字段。
966
+ *
967
+ * 为什么不像 save() 那样走 finalizeSnapshot:那条路会重算 manifest.blobHashes(本次没有 blob
968
+ * 可写 → 空 map → 磁盘校验直接判失败)并重跑 verify。这里只补一个**不在 metadataHash 覆盖面内**
969
+ * 的字段,manifest 与 blob 一字不动,快照的 READY/完整性语义不受影响。
970
+ */
971
+ async recordPluginRemovals(id: string, removals: SnapshotPluginRemoval[]): Promise<void> {
972
+ if (removals.length === 0) return;
973
+ const file = path.join(this.snapshotDir(id), 'snapshot.json');
974
+ const snapshot = parseJsonSafe(await fs.readFile(file, 'utf8')) as Snapshot;
975
+ // 同日多次应用:保留既有记录(append 而不是覆盖),undo 才能把每一轮删的都装回来
976
+ const merged = [...(snapshot.pluginRemovals ?? [])];
977
+ for (const r of removals) {
978
+ if (!merged.some((m) => m.name === r.name)) merged.push(r);
979
+ }
980
+ snapshot.pluginRemovals = merged;
981
+ await atomicWriteFile(file, JSON.stringify(snapshot, null, 2));
982
+ }
963
983
  }
964
984
 
965
985
  /* ---------------- Phase 4:manifest / verifySnapshot(F1) ---------------- */
@@ -29,6 +29,8 @@ async function fixture(t: { after: (fn: () => Promise<void>) => void }, opts: {
29
29
  tarballBytes?: number;
30
30
  oversizeTtlMs?: number;
31
31
  maxTarballBytes?: number;
32
+ /** 内容缓存上限(字节;0 = 关闭) */
33
+ packedCacheMaxBytes?: number;
32
34
  } = {}): Promise<Fixture> {
33
35
  const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'dshcm-packhost-'));
34
36
  t.after(async () => { await fsp.rm(root, { recursive: true, force: true }); });
@@ -54,6 +56,7 @@ async function fixture(t: { after: (fn: () => Promise<void>) => void }, opts: {
54
56
  exec,
55
57
  maxTarballBytes: opts.maxTarballBytes ?? 1024,
56
58
  ...(opts.oversizeTtlMs === undefined ? {} : { oversizeTtlMs: opts.oversizeTtlMs }),
59
+ ...(opts.packedCacheMaxBytes === undefined ? {} : { packedCacheMaxBytes: opts.packedCacheMaxBytes }),
57
60
  });
58
61
  return {
59
62
  hook,
@@ -115,14 +118,40 @@ test('oversizeTtlMs=0:关闭缓存,两轮都真打(测试与排障用)',
115
118
  assert.equal(fx.calls(), 2);
116
119
  });
117
120
 
118
- test('未超限:正常产出 packed,不进负缓存(两轮都打包)', async (t) => {
121
+ test('未超限:正常产出 packed;源没变时第二轮走内容缓存,不再 npm pack', async (t) => {
119
122
  const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024 });
120
123
  const first = await fx.hook(fx.plugins, ctx);
121
124
  assert.equal(first.packed.length, 1);
122
125
  assert.equal(first.oversize.length, 0);
123
126
  assert.equal(first.warnings.length, 0);
127
+
128
+ // 2026-11-09:内容缓存上线后,源没变的第二轮直接复用 tarball 字节(此前是每轮都真打)。
129
+ const second = await fx.hook(fx.plugins, ctx);
130
+ assert.equal(fx.calls(), 1, '源没变 → 复用缓存,不再 spawn npm pack');
131
+ assert.equal(second.packed.length, 1, '缓存命中同样要产出 packed(备份缺它会把插件丢掉)');
132
+ assert.deepEqual(second.packed[0]?.data, first.packed[0]?.data, '复用的必须是同一份字节');
133
+ assert.equal(second.packed[0]?.rewrittenSpec, first.packed[0]?.rewrittenSpec);
134
+ });
135
+
136
+ test('内容缓存:源目录里改一个文件(lib/ 里那种不改目录 mtime 的改动)→ 必须重新打包', async (t) => {
137
+ const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024 });
138
+ await fsp.mkdir(path.join(fx.sourceDir, 'lib'), { recursive: true });
139
+ await fsp.writeFile(path.join(fx.sourceDir, 'lib', 'index.js'), 'export const a = 1\n');
124
140
  await fx.hook(fx.plugins, ctx);
125
- assert.equal(fx.calls(), 2);
141
+ assert.equal(fx.calls(), 1);
142
+
143
+ const file = path.join(fx.sourceDir, 'lib', 'index.js');
144
+ const future = new Date(Date.now() + 5000);
145
+ await fsp.utimes(file, future, future);
146
+ await fx.hook(fx.plugins, ctx);
147
+ assert.equal(fx.calls(), 2, '内容指纹按文件级 rel/size/mtime 算,改文件必须重打包(不能把旧 tarball 当当前内容)');
148
+ });
149
+
150
+ test('内容缓存:packedCacheMaxBytes=0 → 关闭,两轮都真打', async (t) => {
151
+ const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024, packedCacheMaxBytes: 0 });
152
+ await fx.hook(fx.plugins, ctx);
153
+ await fx.hook(fx.plugins, ctx);
154
+ assert.equal(fx.calls(), 2, '关闭缓存时行为与改造前一致');
126
155
  });
127
156
 
128
157
  test('无本地源插件:零 spawn、零目录创建', async (t) => {
@@ -9,11 +9,12 @@
9
9
  */
10
10
  import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
+ import { createHash } from 'node:crypto';
12
13
  import { spawn } from 'node:child_process';
13
14
 
14
15
  import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.ts';
15
16
  import { quoteCmdArg } from './plugin-cli.ts';
16
- import type { OversizeLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
17
+ import type { OversizeLocalPlugin, PackedLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
17
18
  import type { HostContext } from './types.ts';
18
19
  import { engineMsg } from './messages-core.ts';
19
20
 
@@ -106,6 +107,15 @@ export interface LocalPluginPackHookOptions {
106
107
  sourceFingerprint?: (absPath: string) => Promise<string | null>;
107
108
  /** tarball 体积上限(缺省 MAX_LOCAL_TARBALL_BYTES;测试用小值验证超限负缓存) */
108
109
  maxTarballBytes?: number;
110
+ /**
111
+ * 内容缓存上限(字节;缺省 PACKED_CACHE_MAX_BYTES,**0 = 关闭**)。
112
+ * 命中判据 = 源目录的**内容指纹**(递归 rel/size/mtime)未变:命中即复用上次的 tarball 字节,跳过 npm pack。
113
+ */
114
+ packedCacheMaxBytes?: number;
115
+ /** 内容缓存条目上限(缺省 PACKED_CACHE_MAX_ENTRIES)。 */
116
+ packedCacheMaxEntries?: number;
117
+ /** 内容指纹(测试注入;缺省 deepSourceFingerprint)。 */
118
+ contentFingerprint?: (absPath: string) => Promise<string | null>;
109
119
  }
110
120
 
111
121
  /**
@@ -140,6 +150,69 @@ async function defaultSourceFingerprint(absPath: string): Promise<string | null>
140
150
  return null;
141
151
  }
142
152
  }
153
+ /** 内容缓存上限(缺省 128 MiB):只缓存真的打过的 tarball 字节。 */
154
+ const PACKED_CACHE_MAX_BYTES = 128 * 1024 * 1024;
155
+
156
+ /** 内容缓存条目上限(防「一堆小插件」把 Map 撑大)。 */
157
+ const PACKED_CACHE_MAX_ENTRIES = 64;
158
+
159
+ /** 内容指纹的遍历上限:超过就不缓存(宁可不省,也不拿可能过期的字节去备份)。 */
160
+ const CONTENT_FP_MAX_ENTRIES = 20_000;
161
+
162
+ /**
163
+ * 内容指纹(**正缓存**用):递归列出目录内每个文件的相对路径 + 字节数 + mtime。
164
+ *
165
+ * 为什么不用上面的 defaultSourceFingerprint:它只取「目录 mtime + package.json」,
166
+ * 在 lib/ 里改一行**不会**改目录 mtime —— 拿它做正缓存,会把旧 tarball 当成当前内容上传进备份。
167
+ * 负缓存能容忍这种粗糙(最坏是少备份一次、30 分钟内重试),正缓存不能容忍(最坏是备份里是旧代码)。
168
+ *
169
+ * 成本实测(2026-11-07,真机):8810 文件 3.6 s、51502 文件 14.9 s —— 仍比一次 210 MB 插件的
170
+ * 44.7 s npm pack 便宜一个量级;超过 CONTENT_FP_MAX_ENTRIES 或遇到链接/特殊文件一律返回 null
171
+ * (调用方据此**不缓存**,直接照常打包)。
172
+ */
173
+ async function deepSourceFingerprint(absPath: string): Promise<string | null> {
174
+ let st;
175
+ try {
176
+ st = await fsp.stat(absPath);
177
+ } catch {
178
+ return null;
179
+ }
180
+ if (st.isFile()) return 'file:' + st.size + ':' + Math.trunc(st.mtimeMs);
181
+ if (!st.isDirectory()) return null;
182
+
183
+ const hash = createHash('sha256');
184
+ let entries = 0;
185
+ const walk = async (dir: string, rel: string): Promise<boolean> => {
186
+ let list;
187
+ try {
188
+ list = await fsp.readdir(dir, { withFileTypes: true });
189
+ } catch {
190
+ return false;
191
+ }
192
+ list.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
193
+ for (const entry of list) {
194
+ // 与 npm pack 同口径:node_modules 不进产物;.git 不参与内容身份
195
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
196
+ const abs = path.join(dir, entry.name);
197
+ const relPath = rel === '' ? entry.name : rel + '/' + entry.name;
198
+ if (entry.isDirectory()) {
199
+ if (!(await walk(abs, relPath))) return false;
200
+ continue;
201
+ }
202
+ if (!entry.isFile()) return false; // 链接 / 设备文件:不猜它指向什么,放弃缓存
203
+ const s = await fsp.stat(abs).catch(() => null);
204
+ if (s === null) return false;
205
+ entries += 1;
206
+ if (entries > CONTENT_FP_MAX_ENTRIES) return false;
207
+ hash.update(relPath + '\u0000' + s.size + '\u0000' + Math.trunc(s.mtimeMs) + '\n');
208
+ }
209
+ return true;
210
+ };
211
+ if (!(await walk(absPath, ''))) return null;
212
+ hash.update('entries:' + entries);
213
+ return 'deep:' + hash.digest('hex');
214
+ }
215
+
143
216
  export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): LocalPluginPackHook {
144
217
  const exec = opts.exec ?? defaultExec;
145
218
  const oversizeTtlMs = opts.oversizeTtlMs ?? OVERSIZE_NEGATIVE_TTL_MS;
@@ -152,6 +225,42 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
152
225
  */
153
226
  const oversizeCache = new Map<string, { fingerprint: string; at: number; oversize: OversizeLocalPlugin }>();
154
227
 
228
+ /**
229
+ * 内容缓存(正缓存):解析后的源路径 → 上次打出的 tarball 字节 + 当时的内容指纹。
230
+ *
231
+ * 与超限负缓存的区别:负缓存存「结论」,这里存**产物本身**,命中即跳过 npm pack。
232
+ * 命中判据是 deepSourceFingerprint(文件级 rel/size/mtime),不是目录 mtime —— 见该函数注释。
233
+ * 上限双保险:总字节数 + 条目数,超出按「最久未用」淘汰;单条超过上限则根本不入缓存。
234
+ */
235
+ const packedMaxBytes = opts.packedCacheMaxBytes ?? PACKED_CACHE_MAX_BYTES;
236
+ const packedMaxEntries = opts.packedCacheMaxEntries ?? PACKED_CACHE_MAX_ENTRIES;
237
+ const contentFp = opts.contentFingerprint ?? deepSourceFingerprint;
238
+ const packedCache = new Map<string, { fingerprint: string; entry: PackedLocalPlugin; bytes: number; usedAt: number }>();
239
+ let packedCacheBytes = 0;
240
+ const evictPacked = (): void => {
241
+ while (packedCache.size > packedMaxEntries || packedCacheBytes > packedMaxBytes) {
242
+ let oldestKey: string | null = null;
243
+ let oldestAt = Number.POSITIVE_INFINITY;
244
+ for (const [key, value] of packedCache) {
245
+ if (value.usedAt < oldestAt) {
246
+ oldestAt = value.usedAt;
247
+ oldestKey = key;
248
+ }
249
+ }
250
+ if (oldestKey === null) return;
251
+ const removed = packedCache.get(oldestKey);
252
+ if (removed !== undefined) packedCacheBytes -= removed.bytes;
253
+ packedCache.delete(oldestKey);
254
+ }
255
+ };
256
+ /** 按入参顺序输出打包结果(缓存命中与本轮打包混在一起时,保持确定性顺序)。 */
257
+ const orderPacked = (input: readonly { name: string }[], packed: readonly PackedLocalPlugin[]): PackedLocalPlugin[] => {
258
+ const byName = new Map(packed.map((p) => [p.packageName, p] as const));
259
+ return input.map((p) => byName.get(p.name)).filter((p): p is PackedLocalPlugin => p !== undefined);
260
+ };
261
+ const rewrittenOf = (packed: readonly PackedLocalPlugin[]): Record<string, string> =>
262
+ Object.fromEntries(packed.map((p) => [p.packageName, p.rewrittenSpec]));
263
+
155
264
  const hasLocalSpec = (p: { spec?: string }): boolean =>
156
265
  p.spec !== undefined && /^\s*(link|file):/i.test(p.spec);
157
266
 
@@ -209,6 +318,46 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
209
318
  return { packed: [], rewritten: {}, warnings: cacheWarnings, oversize: cacheOversize };
210
319
  }
211
320
 
321
+ // —— 内容缓存命中分流:源内容没变的那几个直接复用上次的 tarball,其余才真的打包 ——
322
+ const hitPacked: PackedLocalPlugin[] = [];
323
+ const toPack: { name: string; version: string; spec?: string }[] = [];
324
+ if (packedMaxBytes > 0) {
325
+ for (const p of kept) {
326
+ const spec = p.spec;
327
+ if (spec === undefined || !hasLocalSpec(p)) {
328
+ toPack.push(p);
329
+ continue;
330
+ }
331
+ const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
332
+ const hit = packedCache.get(abs);
333
+ if (hit === undefined) {
334
+ toPack.push(p);
335
+ continue;
336
+ }
337
+ const fp = await contentFp(abs).catch(() => null);
338
+ if (fp === null || fp !== hit.fingerprint) {
339
+ packedCacheBytes -= hit.bytes;
340
+ packedCache.delete(abs);
341
+ toPack.push(p);
342
+ continue;
343
+ }
344
+ hit.usedAt = Date.now();
345
+ hitPacked.push(hit.entry);
346
+ }
347
+ } else {
348
+ toPack.push(...kept);
349
+ }
350
+
351
+ if (!toPack.some(hasLocalSpec)) {
352
+ // 全部命中:不建临时目录、不 spawn 一次 npm。
353
+ return {
354
+ packed: orderPacked(plugins, hitPacked),
355
+ rewritten: rewrittenOf(hitPacked),
356
+ warnings: cacheWarnings,
357
+ oversize: cacheOversize,
358
+ };
359
+ }
360
+
212
361
  const tmpRoot = path.join(opts.dataDir, 'tmp');
213
362
  let packDir: string;
214
363
  try {
@@ -227,8 +376,12 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
227
376
  }
228
377
 
229
378
  try {
379
+ const specOfName = new Map<string, string>();
380
+ for (const p of toPack) {
381
+ if (p.spec !== undefined && hasLocalSpec(p)) specOfName.set(p.name, p.spec);
382
+ }
230
383
  const result = await packLocalPlugins({
231
- plugins: kept.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
384
+ plugins: toPack.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
232
385
  homeDir: opts.homeDir,
233
386
  profileDir,
234
387
  packDir,
@@ -257,8 +410,28 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
257
410
  }
258
411
  }
259
412
  }
413
+ // 内容缓存记账:本轮真打出来的 tarball 按「源内容指纹」入缓存;超限/算不出指纹的跳过(不猜)。
414
+ if (packedMaxBytes > 0) {
415
+ for (const entry of result.packed) {
416
+ const spec = specOfName.get(entry.packageName);
417
+ if (spec === undefined) continue;
418
+ const bytes = entry.data.byteLength;
419
+ if (bytes > packedMaxBytes) continue;
420
+ const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
421
+ const fp = await contentFp(abs).catch(() => null);
422
+ if (fp === null) continue;
423
+ const prev = packedCache.get(abs);
424
+ if (prev !== undefined) packedCacheBytes -= prev.bytes;
425
+ packedCache.set(abs, { fingerprint: fp, entry, bytes, usedAt: Date.now() });
426
+ packedCacheBytes += bytes;
427
+ }
428
+ evictPacked();
429
+ }
430
+ const allPacked = [...hitPacked, ...result.packed];
260
431
  return {
261
432
  ...result,
433
+ packed: orderPacked(plugins, allPacked),
434
+ rewritten: { ...result.rewritten, ...rewrittenOf(hitPacked) },
262
435
  oversize: [...cacheOversize, ...result.oversize],
263
436
  warnings: [...cacheWarnings, ...result.warnings],
264
437
  };
@@ -363,6 +363,9 @@ export const zh = {
363
363
  'core.pluginCli.installFailed': '安装 {pkg} 失败({code}):{message}',
364
364
  'core.pluginCli.noOutput': '无输出',
365
365
  'core.pluginCli.installFailedWithTail': 'dsh plugin 安装 {pkg} 失败(exit {exitCode}):{tail}',
366
+ 'core.pluginCli.uninstallTimeout': '卸载 {pkg} 超时(进程已终止):请稍后重试 / remove {pkg} timed out (process killed): retry later',
367
+ 'core.pluginCli.uninstallFailed': '卸载 {pkg} 失败({code}):{message}',
368
+ 'core.pluginCli.uninstallFailedWithTail': 'dsh plugin remove {pkg} 失败(exit {exitCode}):{tail}',
366
369
 
367
370
  // ---------- migration-consult ----------
368
371
  'core.consult.compatNoManifest': '无法评估兼容性:manifest 缺失',
@@ -725,6 +728,9 @@ export const en: Record<keyof typeof zh, string> = {
725
728
  'core.pluginCli.installFailed': 'install {pkg} failed ({code}): {message}',
726
729
  'core.pluginCli.noOutput': 'no output',
727
730
  'core.pluginCli.installFailedWithTail': 'dsh plugin install {pkg} failed (exit {exitCode}): {tail}',
731
+ 'core.pluginCli.uninstallTimeout': 'remove {pkg} timed out (process killed): retry later',
732
+ 'core.pluginCli.uninstallFailed': 'remove {pkg} failed ({code}): {message}',
733
+ 'core.pluginCli.uninstallFailedWithTail': 'dsh plugin remove {pkg} failed (exit {exitCode}): {tail}',
728
734
 
729
735
  // ---------- migration-consult ----------
730
736
  'core.consult.compatNoManifest': 'cannot assess compatibility: the manifest is missing',
@@ -170,6 +170,11 @@ export const zh = {
170
170
  'restore.uninstallFailedExit': 'dsh plugin remove {name} 失败(exit {code}):{tail}',
171
171
  'restore.noOutput': '无输出',
172
172
  'restore.pluginRemoveFailed': '卸载失败',
173
+ 'restore.pluginInstall': '装回跟远端删除过的插件 {name}@{version}',
174
+ 'restore.pluginInstallAlreadyPresent': '插件 {name} 已在本机,无需装回',
175
+ 'restore.pluginInstallFailed': '重装失败',
176
+ 'restore.installFailedCode': 'dsh plugin add {name} 失败({code}):{message}',
177
+ 'restore.installFailedExit': 'dsh plugin add {name} 失败(exit {code}):{tail}',
173
178
  'restore.unknownAction': '未知动作 {kind}: {description}',
174
179
  'restore.missingTargetBlob': '恢复动作缺少 target/blobPath',
175
180
  'restore.missingTarget': '恢复动作缺少 target',
@@ -441,6 +446,10 @@ export const zh = {
441
446
  'sync.git.adoptNotSyncRepo': '远端仓库顶层出现了快照布局以外的内容({entries}):它看起来不是本插件的同步仓库,已拒绝合并(不会把别的仓库内容搬进工作副本)。',
442
447
  'sync.git.adoptMergeConflict': '合并远端 {branch} 时发生冲突:已撤销这次合并(merge --abort),工作副本回到操作前的状态。请手工解决冲突后重试,或改用「重新克隆工作副本」。',
443
448
  'sync.workdirModeInvalidFull': '重建工作副本的模式非法: {mode}(只允许 relink(重指向地址)、adopt(采纳远端历史)或 reclone(重新克隆))',
449
+ // issue #131:git 通道的仓库内子目录前缀(多工具共用一个备份仓库时各占一个目录)。
450
+ 'sync.git.subdirInvalid': '同步子目录前缀不合法:{subdir}(不得以 / 开头或结尾,不得含反斜杠、空段、. 段、.. 段或 .git 段)',
451
+ 'sync.git.subdirRoot': '仓库根',
452
+ 'sync.git.subdirChanged': '工作副本的同步布局是「{stored}」,当前配置是「{expected}」:sparse-checkout 只在首次克隆时生效,旧工作副本里没有新前缀的目录树 —— 照常同步会表现为「远端没有快照」。请在「同步 → 通道配置」里重建工作副本(重新克隆)后再同步。',
444
453
 
445
454
  'sync.git.cmdFailed': 'git {args} 失败 (exit {code}): {err}',
446
455
  // 本机提交身份缺失(真机 issue:commit exit 128 ⇒ 交易 NEEDS_ATTENTION ⇒ 被误升 SAFE MODE)。
@@ -687,6 +696,11 @@ export const en: Record<keyof typeof zh, string> = {
687
696
  'restore.uninstallFailedExit': 'dsh plugin remove {name} failed (exit {code}): {tail}',
688
697
  'restore.noOutput': 'no output',
689
698
  'restore.pluginRemoveFailed': 'Uninstall failed',
699
+ 'restore.pluginInstall': 'Reinstall plugin {name}@{version} (removed earlier to follow the remote)',
700
+ 'restore.pluginInstallAlreadyPresent': 'Plugin {name} is already installed here; nothing to reinstall',
701
+ 'restore.pluginInstallFailed': 'Reinstall failed',
702
+ 'restore.installFailedCode': 'dsh plugin add {name} failed ({code}): {message}',
703
+ 'restore.installFailedExit': 'dsh plugin add {name} failed (exit {code}): {tail}',
690
704
  'restore.unknownAction': 'Unknown action {kind}: {description}',
691
705
  'restore.missingTargetBlob': 'Restore action is missing target/blobPath',
692
706
  'restore.missingTarget': 'Restore action is missing target',
@@ -957,6 +971,10 @@ export const en: Record<keyof typeof zh, string> = {
957
971
  'sync.git.adoptNotSyncRepo': 'The remote repository root contains entries outside the snapshot layout ({entries}): it does not look like this plugin\'s sync repository, so the merge was refused (another repository\'s content is never pulled into the working copy).',
958
972
  'sync.git.adoptMergeConflict': 'Merging remote {branch} produced conflicts: the merge was aborted (merge --abort) and the working copy is back to its previous state. Resolve the conflicts manually and retry, or use "clone the working copy again".',
959
973
  'sync.workdirModeInvalidFull': 'Invalid working-copy rebuild mode: {mode} (only relink (re-point the address), adopt (merge the remote history) or reclone (clone again) are allowed).',
974
+ // issue #131: in-repo subdirectory prefix for the git channel (several tools sharing one backup repository).
975
+ 'sync.git.subdirInvalid': 'Invalid sync subdirectory prefix: {subdir} (must not start or end with /, and must not contain a backslash, an empty segment, a . segment, a .. segment, or a .git segment)',
976
+ 'sync.git.subdirRoot': 'repository root',
977
+ 'sync.git.subdirChanged': 'This working copy uses the sync layout "{stored}" but the current config is "{expected}": sparse-checkout only applies on the first clone, so the old working copy has no tree for the new prefix — syncing would look like "the remote has no snapshots". Rebuild the working copy (clone again) under Sync → Channel configuration, then sync again.',
960
978
 
961
979
  'sync.git.cmdFailed': 'git {args} failed (exit {code}): {err}',
962
980
  // Missing local commit identity (real-world issue: commit exit 128 → NEEDS_ATTENTION → wrongly escalated to SAFE MODE).
@@ -459,6 +459,8 @@ export function createModelTools(deps: ModelToolsDeps) {
459
459
  hostFileRestores: plan.summary.hostFileRestores,
460
460
  hostFileRemoves: plan.summary.hostFileRemoves,
461
461
  pluginRemoves: plan.summary.pluginRemoves,
462
+ // issue #132:undo 会反向装回跟删过的插件,计数单独给出(agent 不必自己数 actions)
463
+ pluginInstalls: plan.summary.pluginInstalls,
462
464
  fileRestores: plan.summary.fileRestores,
463
465
  fileRemoves: plan.summary.fileRemoves,
464
466
  credentialHints: plan.summary.credentialHints,
@@ -53,7 +53,7 @@ async function main(): Promise<void> {
53
53
  describe: async (ref: string) => ({ value: { theme: 'dark' }, revision: 1, secrets: [] }),
54
54
  },
55
55
  credentials: { describe: async () => ({ configured: false }) },
56
- plugins: { listInstalled: async () => [] },
56
+ plugins: { listInstalled: async () => [], uninstall: async () => ({ needsRestart: true }) },
57
57
  workspace: { listRecords: async () => [] },
58
58
  patchFile: { readPatchLines: async () => [] },
59
59
  log: { warn: () => {} },