dsh-config-manager 0.8.1 → 0.9.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 (368) hide show
  1. package/lib/adapters/mcp.js +42 -13
  2. package/lib/adapters/messages.d.ts +1 -0
  3. package/lib/adapters/messages.js +2 -0
  4. package/lib/adapters/patch-key-guard.d.ts +23 -0
  5. package/lib/adapters/patch-key-guard.js +13 -0
  6. package/lib/adapters/plugin-data.d.ts +19 -5
  7. package/lib/adapters/plugin-data.js +76 -22
  8. package/lib/adapters/plugins.d.ts +14 -1
  9. package/lib/adapters/plugins.js +147 -4
  10. package/lib/cli/actions.d.ts +7 -105
  11. package/lib/cli/actions.js +16 -172
  12. package/lib/cli/control-state.d.ts +54 -0
  13. package/lib/cli/control-state.js +107 -0
  14. package/lib/cli/index.js +14 -0
  15. package/lib/cli/write-gates.d.ts +61 -0
  16. package/lib/cli/write-gates.js +110 -0
  17. package/lib/client.d.ts +122 -50
  18. package/lib/client.js +12676 -12091
  19. package/lib/core/backup.d.ts +0 -4
  20. package/lib/core/backup.js +21 -4
  21. package/lib/core/boot-rescue.d.ts +1 -1
  22. package/lib/core/boot-rescue.js +12 -1
  23. package/lib/core/boot-safety.js +37 -2
  24. package/lib/core/conflict-decisions.js +2 -1
  25. package/lib/core/exporter.js +22 -1
  26. package/lib/core/journal.d.ts +54 -4
  27. package/lib/core/journal.js +158 -35
  28. package/lib/core/local-plugin-host.d.ts +29 -0
  29. package/lib/core/local-plugin-host.js +55 -48
  30. package/lib/core/messages.d.ts +7 -0
  31. package/lib/core/messages.js +14 -0
  32. package/lib/core/migration-history.js +16 -9
  33. package/lib/core/model-tools.d.ts +2 -2
  34. package/lib/core/model-tools.js +14 -2
  35. package/lib/core/patch-secret-guard.d.ts +49 -0
  36. package/lib/core/patch-secret-guard.js +164 -0
  37. package/lib/core/reconcile.d.ts +8 -0
  38. package/lib/core/reconcile.js +18 -3
  39. package/lib/core/reinstall.d.ts +2 -0
  40. package/lib/core/reinstall.js +6 -2
  41. package/lib/core/restore.js +31 -6
  42. package/lib/core/section-sanitize.d.ts +32 -0
  43. package/lib/core/section-sanitize.js +13 -0
  44. package/lib/core/snapshot-diff.d.ts +30 -0
  45. package/lib/core/snapshot-diff.js +56 -20
  46. package/lib/core/startup-barrier.js +8 -2
  47. package/lib/core/types.d.ts +22 -0
  48. package/lib/core/update-check.js +51 -2
  49. package/lib/foreign/kernel.js +9 -2
  50. package/lib/foreign/read-claude-plugins.js +29 -11
  51. package/lib/foreign/read-dsh.js +31 -2
  52. package/lib/foreign/read-trae.d.ts +11 -0
  53. package/lib/foreign/read-trae.js +124 -4
  54. package/lib/foreign/session-ir.js +50 -9
  55. package/lib/foreign/session-read.d.ts +8 -0
  56. package/lib/foreign/session-read.js +26 -0
  57. package/lib/foreign/session-source.d.ts +12 -4
  58. package/lib/foreign/session-source.js +5 -3
  59. package/lib/foreign/trae-sqlcipher.d.ts +127 -0
  60. package/lib/foreign/trae-sqlcipher.js +519 -0
  61. package/lib/foreign/trae.js +3 -1
  62. package/lib/foreign/truth-table.js +3 -2
  63. package/lib/foreign/types.d.ts +9 -1
  64. package/lib/index.d.ts +1 -1
  65. package/lib/index.js +1 -1
  66. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  67. package/lib/profiles/dsh-profile-io.js +27 -0
  68. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  69. package/lib/profiles/dsh-profile-manager.js +45 -4
  70. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  71. package/lib/profiles/dsh-profile-runtime.js +16 -3
  72. package/lib/profiles/process-control.d.ts +18 -1
  73. package/lib/profiles/process-control.js +25 -1
  74. package/lib/routes/profiles.js +2 -1
  75. package/lib/routes/sync.js +13 -1
  76. package/lib/schema/types.d.ts +11 -0
  77. package/lib/security/redaction.js +22 -6
  78. package/lib/sync/autosync-repeat.d.ts +27 -0
  79. package/lib/sync/autosync-repeat.js +23 -0
  80. package/lib/sync/autosync-scheduler.d.ts +34 -1
  81. package/lib/sync/autosync-scheduler.js +151 -43
  82. package/lib/sync/baseline-heal.js +7 -0
  83. package/lib/sync/baseline-record.d.ts +67 -0
  84. package/lib/sync/baseline-record.js +74 -0
  85. package/lib/sync/blob-store.js +13 -0
  86. package/lib/sync/content-diff.d.ts +39 -0
  87. package/lib/sync/content-diff.js +46 -0
  88. package/lib/sync/git/git-transport.d.ts +32 -1
  89. package/lib/sync/git/git-transport.js +146 -26
  90. package/lib/sync/github-auth.d.ts +17 -1
  91. package/lib/sync/github-auth.js +37 -1
  92. package/lib/sync/merge-apply-plan.d.ts +38 -0
  93. package/lib/sync/merge-apply-plan.js +76 -0
  94. package/lib/sync/messages.d.ts +1 -0
  95. package/lib/sync/messages.js +2 -0
  96. package/lib/sync/pending-merge.d.ts +34 -0
  97. package/lib/sync/pending-merge.js +53 -0
  98. package/lib/sync/s3/s3-transport.d.ts +14 -2
  99. package/lib/sync/s3/s3-transport.js +72 -48
  100. package/lib/sync/sync-engine.d.ts +23 -40
  101. package/lib/sync/sync-engine.js +115 -132
  102. package/lib/sync/sync-history.d.ts +7 -0
  103. package/lib/sync/sync-state.d.ts +28 -0
  104. package/lib/sync/sync-state.js +20 -0
  105. package/lib/sync/transport.d.ts +12 -3
  106. package/lib/sync/transport.js +13 -4
  107. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  108. package/lib/sync/webdav/webdav-transport.js +81 -40
  109. package/lib/ui/commands.js +5 -11
  110. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  111. package/lib/ui/dsh-profiles-view.js +9 -5
  112. package/lib/ui/foreign-view.d.ts +19 -0
  113. package/lib/ui/foreign-view.js +24 -0
  114. package/lib/ui/i18n.d.ts +7 -1
  115. package/lib/ui/i18n.js +17 -2
  116. package/lib/ui/menu-placement.js +1 -1
  117. package/lib/ui/migration-consult-view.d.ts +11 -0
  118. package/lib/ui/migration-consult-view.js +15 -0
  119. package/lib/ui/overview-view.d.ts +7 -0
  120. package/lib/ui/overview-view.js +3 -0
  121. package/lib/ui/report.d.ts +9 -0
  122. package/lib/ui/report.js +17 -4
  123. package/lib/ui/selection-model.d.ts +8 -0
  124. package/lib/ui/selection-model.js +16 -0
  125. package/lib/utils/patch-yaml.d.ts +39 -1
  126. package/lib/utils/patch-yaml.js +82 -2
  127. package/lib/utils/paths.d.ts +13 -0
  128. package/lib/utils/paths.js +35 -0
  129. package/lib/utils/workdir-lock.js +18 -3
  130. package/package.json +2 -1
  131. package/src/adapters/mcp.test.ts +29 -0
  132. package/src/adapters/mcp.ts +43 -12
  133. package/src/adapters/messages.ts +2 -0
  134. package/src/adapters/patch-key-guard.ts +29 -0
  135. package/src/adapters/plugin-data.test.ts +126 -0
  136. package/src/adapters/plugin-data.ts +97 -26
  137. package/src/adapters/plugins.test.ts +288 -0
  138. package/src/adapters/plugins.ts +141 -4
  139. package/src/cli/actions.test.ts +74 -1
  140. package/src/cli/actions.ts +27 -246
  141. package/src/cli/control-state.ts +143 -0
  142. package/src/cli/index.ts +18 -0
  143. package/src/cli/web/web.test.ts +27 -0
  144. package/src/cli/write-gates.ts +149 -0
  145. package/src/client/about/AboutPanel.tsx +7 -6
  146. package/src/client/about/release-notes-view.test.ts +17 -0
  147. package/src/client/about/release-notes-view.ts +49 -24
  148. package/src/client/chat/ChatEntryView.tsx +2 -2
  149. package/src/client/chat/rollback-entry-view.ts +6 -1
  150. package/src/client/common/CommandPalette.tsx +6 -3
  151. package/src/client/common/ConfirmDialog.tsx +29 -12
  152. package/src/client/common/ContentPicker.tsx +13 -12
  153. package/src/client/common/Modal.tsx +12 -5
  154. package/src/client/common/MoreMenu.tsx +4 -1
  155. package/src/client/common/RunsCenter.tsx +103 -32
  156. package/src/client/common/Select.tsx +2 -2
  157. package/src/client/common/floating-bounds.ts +1 -1
  158. package/src/client/common/floating-units.test.ts +1 -2
  159. package/src/client/common/plan-text-redaction.test.ts +188 -3
  160. package/src/client/common/runs-center-guard.test.ts +60 -0
  161. package/src/client/common/runs-center-view.test.ts +128 -0
  162. package/src/client/common/runs-center-view.ts +96 -0
  163. package/src/client/common/section-title-action.test.ts +66 -0
  164. package/src/client/common/ui.tsx +93 -30
  165. package/src/client/config-manager.module.css +1507 -272
  166. package/src/client/consult/ConsultCard.tsx +7 -6
  167. package/src/client/environment/EnvironmentPanel.tsx +20 -21
  168. package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
  169. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  170. package/src/client/export/ExportView.tsx +7 -16
  171. package/src/client/history/HistoryPanel.tsx +88 -28
  172. package/src/client/history/history-locales.ts +3 -3
  173. package/src/client/home/BackupScheduleCard.tsx +35 -30
  174. package/src/client/home/HomePanel.tsx +45 -10
  175. package/src/client/import/ConflictList.tsx +13 -13
  176. package/src/client/import/ForeignImportView.tsx +32 -13
  177. package/src/client/import/ImportWizardView.tsx +2 -3
  178. package/src/client/import/PathMappingForm.tsx +4 -4
  179. package/src/client/import/PathPickerDialog.tsx +2 -1
  180. package/src/client/import/foreign-import-view-guard.test.ts +1 -1
  181. package/src/client/import/import-wizard-steps.tsx +51 -39
  182. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  183. package/src/client/import/use-import-wizard-controller.ts +116 -22
  184. package/src/client/library/ArtifactRow.tsx +2 -2
  185. package/src/client/library/BackupInspectView.tsx +19 -15
  186. package/src/client/library/LibraryActions.tsx +56 -16
  187. package/src/client/library/LibraryPanel.tsx +7 -7
  188. package/src/client/library/RestorePlanView.tsx +13 -8
  189. package/src/client/locales/about.ts +0 -2
  190. package/src/client/locales/backup.ts +10 -12
  191. package/src/client/locales/common.ts +2 -0
  192. package/src/client/locales/export.ts +5 -12
  193. package/src/client/locales/foreign.ts +11 -2
  194. package/src/client/locales/import.ts +3 -2
  195. package/src/client/locales/overview.ts +4 -0
  196. package/src/client/locales/profiles.ts +32 -4
  197. package/src/client/locales/restore.ts +0 -2
  198. package/src/client/locales/sessions.ts +0 -2
  199. package/src/client/locales/shell.ts +2 -2
  200. package/src/client/market/MarketPanel.tsx +38 -20
  201. package/src/client/market/MyConfigsList.tsx +34 -32
  202. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  203. package/src/client/market/MyConfigsView.tsx +5 -5
  204. package/src/client/market/MyConfigsWizard.tsx +7 -12
  205. package/src/client/market/market-locales.ts +0 -6
  206. package/src/client/market/my-configs-split.test.ts +2 -1
  207. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  208. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  209. package/src/client/recovery/RecoveryPanel.tsx +31 -16
  210. package/src/client/recovery/RollbackCard.tsx +58 -16
  211. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  212. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  213. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  214. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  215. package/src/client/recovery/recovery-locales.ts +12 -8
  216. package/src/client/run-store.test.ts +30 -0
  217. package/src/client/run-store.ts +21 -1
  218. package/src/client/sync/AddChannelCard.tsx +65 -0
  219. package/src/client/sync/AutosyncCard.tsx +182 -108
  220. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  221. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  222. package/src/client/sync/MergePreviewView.tsx +3 -5
  223. package/src/client/sync/PushReportSections.tsx +35 -0
  224. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  225. package/src/client/sync/SyncConfirmView.tsx +3 -3
  226. package/src/client/sync/SyncLogList.tsx +16 -5
  227. package/src/client/sync/SyncPanel.tsx +153 -159
  228. package/src/client/sync/SyncProbeRow.tsx +5 -7
  229. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  230. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  231. package/src/client/sync/SyncSettingsDialog.tsx +304 -0
  232. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  233. package/src/client/sync/WorkDirCard.tsx +2 -4
  234. package/src/client/sync/config-clear-guard.test.ts +94 -0
  235. package/src/client/sync/config-clear-guard.ts +98 -0
  236. package/src/client/sync/config-dirty.test.ts +91 -0
  237. package/src/client/sync/config-dirty.ts +88 -0
  238. package/src/client/sync/history-model.test.ts +2 -0
  239. package/src/client/sync/history-model.ts +3 -0
  240. package/src/client/sync/merge-request.ts +20 -0
  241. package/src/client/sync/sync-api.ts +12 -0
  242. package/src/client/sync/sync-locales.ts +87 -47
  243. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  244. package/src/client/sync/sync-view.test.ts +20 -0
  245. package/src/client/sync/sync-view.ts +42 -4
  246. package/src/core/backup.test.ts +61 -1
  247. package/src/core/backup.ts +21 -4
  248. package/src/core/boot-rescue.test.ts +35 -0
  249. package/src/core/boot-rescue.ts +13 -2
  250. package/src/core/boot-safety.test.ts +25 -0
  251. package/src/core/boot-safety.ts +37 -2
  252. package/src/core/conflict-decisions.ts +2 -1
  253. package/src/core/exporter.ts +21 -1
  254. package/src/core/journal.test.ts +183 -0
  255. package/src/core/journal.ts +163 -25
  256. package/src/core/local-plugin-host.test.ts +68 -2
  257. package/src/core/local-plugin-host.ts +31 -4
  258. package/src/core/messages.ts +14 -0
  259. package/src/core/migration-history.test.ts +27 -0
  260. package/src/core/migration-history.ts +12 -4
  261. package/src/core/model-tools.test.ts +67 -0
  262. package/src/core/model-tools.ts +16 -4
  263. package/src/core/patch-secret-guard.test.ts +110 -0
  264. package/src/core/patch-secret-guard.ts +176 -0
  265. package/src/core/reconcile.ts +32 -4
  266. package/src/core/reinstall.ts +8 -2
  267. package/src/core/restore.ts +32 -7
  268. package/src/core/section-sanitize.ts +37 -0
  269. package/src/core/snapshot-diff.test.ts +73 -1
  270. package/src/core/snapshot-diff.ts +66 -21
  271. package/src/core/startup-barrier.test.ts +64 -0
  272. package/src/core/startup-barrier.ts +8 -2
  273. package/src/core/types.ts +27 -1
  274. package/src/core/update-check.test.ts +40 -0
  275. package/src/core/update-check.ts +53 -2
  276. package/src/foreign/claude-code.test.ts +5 -0
  277. package/src/foreign/claude-plugins.test.ts +57 -0
  278. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  279. package/src/foreign/dsh.test.ts +23 -0
  280. package/src/foreign/file-budget.test.ts +7 -1
  281. package/src/foreign/kernel.ts +9 -2
  282. package/src/foreign/read-claude-plugins.ts +32 -11
  283. package/src/foreign/read-dsh.ts +33 -2
  284. package/src/foreign/read-trae.ts +117 -5
  285. package/src/foreign/session-ir.test.ts +67 -0
  286. package/src/foreign/session-ir.ts +54 -14
  287. package/src/foreign/session-read.ts +23 -0
  288. package/src/foreign/session-source.ts +15 -5
  289. package/src/foreign/trae-sqlcipher.test.ts +360 -0
  290. package/src/foreign/trae-sqlcipher.ts +564 -0
  291. package/src/foreign/trae.test.ts +188 -0
  292. package/src/foreign/trae.ts +3 -1
  293. package/src/foreign/truth-table.ts +4 -2
  294. package/src/foreign/types.ts +10 -1
  295. package/src/index.ts +1 -1
  296. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  297. package/src/profiles/dsh-profile-io.ts +29 -0
  298. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  299. package/src/profiles/dsh-profile-manager.ts +53 -5
  300. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  301. package/src/profiles/dsh-profile-runtime.ts +17 -3
  302. package/src/profiles/process-control.test.ts +97 -0
  303. package/src/profiles/process-control.ts +28 -1
  304. package/src/routes/profiles.ts +2 -1
  305. package/src/routes/sync.ts +13 -1
  306. package/src/schema/types.ts +16 -1
  307. package/src/security/redaction.test.ts +31 -0
  308. package/src/security/redaction.ts +23 -6
  309. package/src/sync/autosync-repeat.test.ts +58 -0
  310. package/src/sync/autosync-repeat.ts +55 -0
  311. package/src/sync/autosync-scheduler.test.ts +417 -0
  312. package/src/sync/autosync-scheduler.ts +154 -41
  313. package/src/sync/baseline-heal.ts +6 -0
  314. package/src/sync/baseline-record.ts +135 -0
  315. package/src/sync/blob-store.test.ts +16 -0
  316. package/src/sync/blob-store.ts +13 -0
  317. package/src/sync/content-diff.test.ts +95 -0
  318. package/src/sync/content-diff.ts +79 -0
  319. package/src/sync/git/git-transport.test.ts +151 -4
  320. package/src/sync/git/git-transport.ts +143 -27
  321. package/src/sync/github-auth.test.ts +26 -1
  322. package/src/sync/github-auth.ts +37 -1
  323. package/src/sync/merge-apply-plan.ts +117 -0
  324. package/src/sync/messages.ts +2 -0
  325. package/src/sync/pending-merge.ts +77 -0
  326. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  327. package/src/sync/s3/s3-transport.ts +76 -42
  328. package/src/sync/sync-config.test.ts +39 -12
  329. package/src/sync/sync-device-identity.test.ts +3 -0
  330. package/src/sync/sync-engine.test.ts +465 -12
  331. package/src/sync/sync-engine.ts +130 -135
  332. package/src/sync/sync-history.ts +7 -0
  333. package/src/sync/sync-state.ts +48 -0
  334. package/src/sync/transport.test.ts +13 -1
  335. package/src/sync/transport.ts +12 -4
  336. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  337. package/src/sync/webdav/webdav-transport.ts +86 -34
  338. package/src/ui/commands.test.ts +11 -0
  339. package/src/ui/commands.ts +5 -14
  340. package/src/ui/dsh-profiles-view.test.ts +16 -0
  341. package/src/ui/dsh-profiles-view.ts +11 -5
  342. package/src/ui/foreign-view.test.ts +36 -0
  343. package/src/ui/foreign-view.ts +46 -0
  344. package/src/ui/i18n.ts +17 -2
  345. package/src/ui/menu-placement.ts +1 -1
  346. package/src/ui/migration-consult-view.test.ts +20 -1
  347. package/src/ui/migration-consult-view.ts +17 -0
  348. package/src/ui/overview-view.ts +10 -0
  349. package/src/ui/report.test.ts +25 -1
  350. package/src/ui/report.ts +15 -4
  351. package/src/ui/selection-model.test.ts +15 -1
  352. package/src/ui/selection-model.ts +18 -0
  353. package/src/utils/js-yaml4.d.ts +35 -0
  354. package/src/utils/patch-yaml.test.ts +207 -1
  355. package/src/utils/patch-yaml.ts +98 -2
  356. package/src/utils/paths.test.ts +14 -1
  357. package/src/utils/paths.ts +35 -0
  358. package/src/utils/workdir-lock.test.ts +69 -0
  359. package/src/utils/workdir-lock.ts +17 -3
  360. package/lib/ui/path-mapping.d.ts +0 -38
  361. package/lib/ui/path-mapping.js +0 -75
  362. package/src/client/common/InfoHint.tsx +0 -289
  363. package/src/client/common/info-hint-guard.test.ts +0 -1119
  364. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  365. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  366. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  367. package/src/ui/path-mapping.test.ts +0 -67
  368. package/src/ui/path-mapping.ts +0 -103
@@ -233,19 +233,61 @@ export interface JournalIo {
233
233
  exists(p: string): Promise<boolean>;
234
234
  }
235
235
 
236
+ /** 只有「确实不存在」才算空目录;权限/路径类型(EACCES / ENOTDIR)等错误必须抛给调用方(P3-5)。 */
237
+ function isEnoent(err: unknown): boolean {
238
+ return (err as NodeJS.ErrnoException | null)?.code === 'ENOENT';
239
+ }
240
+
236
241
  const defaultIo: JournalIo = {
237
242
  async mkdir(d, o) { await fs.mkdir(d, o); },
238
243
  async readFileText(p) { return (await fs.readFile(p, 'utf8')).toString(); },
239
244
  async writeAll(t, c) { await atomicWriteFile(t, c, { mode: 0o600, symlink: 'reject' }); },
240
245
  async rename(a, b) { await fs.rename(a, b); },
241
- async readdirNames(d) { try { return await fs.readdir(d); } catch { return []; } },
242
- async readdirEntries(d) { try { return await fs.readdir(d, { withFileTypes: true }); } catch { return []; } },
246
+ // P3-5:旧实现 catch 一切 → 读不出的目录被当作空目录,上层(尤其快照引用集合)把
247
+ // 「读不到 ≠ 没有引用」误读成「没有引用」。ENOENT 才是「真没有」。
248
+ async readdirNames(d) {
249
+ try { return await fs.readdir(d); } catch (err) {
250
+ if (isEnoent(err)) return [];
251
+ throw err;
252
+ }
253
+ },
254
+ async readdirEntries(d) {
255
+ try { return await fs.readdir(d, { withFileTypes: true }); } catch (err) {
256
+ if (isEnoent(err)) return [];
257
+ throw err;
258
+ }
259
+ },
243
260
  async lstat(p) { try { return await fs.lstat(p); } catch { return null; } },
244
261
  async statMtimeMs(p) { try { return (await fs.stat(p)).mtimeMs; } catch { return null; } },
245
262
  async rm(p, o) { await fs.rm(p, o); },
246
263
  async exists(p) { try { await fs.access(p); return true; } catch { return false; } },
247
264
  };
248
265
 
266
+ /** 引用集合的取证式扫描结果(P3-5)。`complete === false` 时 referenced 只是下界。 */
267
+ export interface JournalReferenceScan {
268
+ /** 可解析 journal 引用的 snapshotId(不完整时是下界) */
269
+ referenced: Set<string>;
270
+ /** 读不到/解析不了的 journal 位置(相对 transactions 的 posix 形式) */
271
+ unreadable: string[];
272
+ /** true = 三个目录都读到、每条 journal 都可解析,referenced 可当完整集合使用 */
273
+ complete: boolean;
274
+ }
275
+
276
+ /**
277
+ * 引用集合读不完整(P3-5):有 journal 但读不出/解析不了,或 journal 目录读不到。
278
+ * 调用方必须 fail-closed —— 快照删除(409 recovery-reference-unreadable)与自动 prune
279
+ * (放弃本轮清理)都依赖「读不到 ≠ 没有引用」。`unreadable` 是相对路径,供日志定位。
280
+ */
281
+ export class JournalReferenceUnreadableError extends Error {
282
+ readonly code = 'journal-reference-unreadable';
283
+ readonly unreadable: string[];
284
+ constructor(unreadable: string[]) {
285
+ super('journal reference set is unreadable (unreadable is not the same as no reference): ' + unreadable.join(', '));
286
+ this.name = 'JournalReferenceUnreadableError';
287
+ this.unreadable = unreadable;
288
+ }
289
+ }
290
+
249
291
  export interface JournalStoreOptions {
250
292
  transactionsDir: string;
251
293
  io?: JournalIo;
@@ -262,6 +304,18 @@ export function isJournalBasename(name: string): boolean {
262
304
  return !name.startsWith(TMP_PREFIX);
263
305
  }
264
306
 
307
+ /**
308
+ * recovery-history 文件名的时间键:`<epochMs>-<randomHex>.<marker>.json`(appendRecoveryHistory 的命名口径)。
309
+ * 该目录没有记录内时间字段,文件名前缀就是唯一时间来源;带不出 epoch 毫秒 → null
310
+ *(retention 判不了新旧,不参与删除)。
311
+ */
312
+ function historyEntryAt(name: string): number | null {
313
+ const m = /^(\d+)-/.exec(name);
314
+ if (m === null) return null;
315
+ const at = Number(m[1]);
316
+ return Number.isSafeInteger(at) ? at : null;
317
+ }
318
+
265
319
  /**
266
320
  * 原子写半成品判据(**有意保守宽判**,t65 / t60-O3)。
267
321
  *
@@ -492,7 +546,7 @@ export class JournalStore {
492
546
  /**
493
547
  * 收集已被「可恢复 / 未收敛 journal」引用的 snapshotId(Phase 4 F3 prune 保护):
494
548
  * 扫描 active/ + quarantine/ + completed/ 下的 journal,凡「快照仍可能被 recovery/人工恢复用到」
495
- * 且 snapshotId 合法 → 收集。返回 Set<string>。该集合用于 FileSnapshotStore.prune 豁免 ——
549
+ * 且 snapshotId 合法 → 收集。该集合用于 FileSnapshotStore.prune 豁免 ——
496
550
  * 引用的 recovery snapshot 绝不可被自动淘汰。
497
551
  *
498
552
  * 什么算「已消费」(不保护):
@@ -501,23 +555,64 @@ export class JournalStore {
501
555
  * 审计 P0-3:**半回滚态**(ROLLED_BACK + full === false)与 NEEDS_ATTENTION / ROLLING_BACK /
502
556
  * RECOVERING 仍需 recovery 或人工恢复 —— 它们会被规整进 completed/,所以 completed/ 必须一起扫,
503
557
  * 否则「已回滚但没回滚干净」的回滚点会在 10 次快照后被静默淘汰(而它正是用户唯一的退路)。
558
+ *
559
+ * 审计 P3-5:**读不到 ≠ 没有引用**。旧实现把目录读不到折成空、把单条读不出/解析不了折成跳过,
560
+ * 于是「有 journal 但读不出」与「没有 journal」在上层无法区分:deleteSnapshot 的
561
+ * recovery-reference-unreadable 保守分支永远不可达,快照会被真删。这里改为:
562
+ * - 目录 ENOENT(真没有)→ 空;其余目录错误 → 记进 unreadable(不折叠);
563
+ * - 单条 journal 读不出(非 ENOENT)/解析不了 → 记进 unreadable;
564
+ * - 有任何 unreadable ⇒ 集合不完整,listReferencedSnapshotIds 显式抛错(调用方 fail-closed)。
565
+ * 需要区分「具体哪条读不出」的诊断面用 scanSnapshotReferences()。
504
566
  */
505
567
  async listReferencedSnapshotIds(): Promise<Set<string>> {
506
- const out = new Set<string>();
507
- const dirs = [this.activeDir(), this.quarantineDir(), this.completedDir()];
508
- for (const dir of dirs) {
509
- for (const name of await this.io.readdirNames(dir)) {
568
+ const scan = await this.scanSnapshotReferences();
569
+ if (!scan.complete) throw new JournalReferenceUnreadableError(scan.unreadable);
570
+ return scan.referenced;
571
+ }
572
+
573
+ /** 引用集合的**取证式**扫描:既给出可用的 snapshotId,也如实给出读不出的位置(P3-5)。
574
+ * `complete === false` 时 `referenced` 只是下界,调用方必须按 fail-closed 处理。 */
575
+ async scanSnapshotReferences(): Promise<JournalReferenceScan> {
576
+ const referenced = new Set<string>();
577
+ const unreadable: string[] = [];
578
+ for (const dir of [this.activeDir(), this.quarantineDir(), this.completedDir()]) {
579
+ let names: string[];
580
+ try {
581
+ names = await this.io.readdirNames(dir);
582
+ } catch (err) {
583
+ if (isEnoent(err)) continue; // 目录确实不存在 = 没有 journal
584
+ unreadable.push(this.referenceLabel(dir));
585
+ continue;
586
+ }
587
+ for (const name of names) {
510
588
  if (!isJournalBasename(name)) continue;
511
- const text = await this.io.readFileText(path.join(dir, name)).catch(() => null);
512
- if (text === null) continue;
589
+ const file = path.join(dir, name);
590
+ let text: string;
591
+ try {
592
+ text = await this.io.readFileText(file);
593
+ } catch (err) {
594
+ if (isEnoent(err)) continue; // 扫描与读取之间被移走/删除:此刻已没有这条 journal
595
+ unreadable.push(this.referenceLabel(file));
596
+ continue;
597
+ }
513
598
  const j = parseSafe(text);
514
- if (j === null) continue;
599
+ if (j === null) {
600
+ // 解析不了 = 无法证明它没引用某个快照(可能是更高 schemaVersion 的 journal)→ 不完整
601
+ unreadable.push(this.referenceLabel(file));
602
+ continue;
603
+ }
515
604
  if (j.state === 'COMMITTED') continue; // 已消费,不保护
516
605
  if (j.state === 'ROLLED_BACK' && j.rollback.full === true) continue; // 完整回滚:已回到导入前状态
517
- if (typeof j.snapshotId === 'string' && j.snapshotId !== '') out.add(j.snapshotId);
606
+ if (typeof j.snapshotId === 'string' && j.snapshotId !== '') referenced.add(j.snapshotId);
518
607
  }
519
608
  }
520
- return out;
609
+ return { referenced, unreadable, complete: unreadable.length === 0 };
610
+ }
611
+
612
+ /** 诊断用位置标签(相对 transactions 的 posix 形式;绝不带绝对路径进日志/响应)。 */
613
+ private referenceLabel(p: string): string {
614
+ const rel = path.relative(this.transactionsDir, p);
615
+ return (rel === '' ? '.' : rel).split(path.sep).join('/');
521
616
  }
522
617
 
523
618
  // ---------- SAFE MODE ----------
@@ -558,22 +653,65 @@ export class JournalStore {
558
653
 
559
654
  // ---------- retention ----------
560
655
 
561
- /** 保留策略:completed 保留 N,recovery-history 保留 M。删最旧。幂等。 */
562
- async retention(completedLimit = 50, historyLimit = 200): Promise<void> {
563
- const completed = (await this.io.readdirNames(this.completedDir()))
564
- .filter(isJournalBasename).sort();
565
- await this.pruneOldest(this.completedDir(), completed, completedLimit);
566
-
567
- const hist = (await this.io.readdirNames(this.recoveryHistoryDir())).sort();
568
- await this.pruneOldest(this.recoveryHistoryDir(), hist, historyLimit);
656
+ /**
657
+ * 保留策略:completed 保留 N,recovery-history 保留 M;**按真实时间删最旧**,幂等。
658
+ *
659
+ * 排序键(唯一来源,注释即实现):
660
+ * - completed/:journal 记录内的 `updatedAt`(落盘/状态推进时刻)。刻意不用 mtime ——
661
+ * completed 文件名是 randomBytes UUID,与时间无关;而复制/恢复会重写 mtime,
662
+ * 旧实现按文件名字典序「删最旧」,实际可能删掉最新的那条(审计 P3-7)。
663
+ * - recovery-history/:文件名前缀的 epoch 毫秒(appendRecoveryHistory 的命名口径;
664
+ * 该目录没有记录内时间字段)。
665
+ *
666
+ * 判不了新旧的文件(读不出 / 解析不了 / 文件名带不出时间)**既不计入上限也不删**:
667
+ * 宁可暂时超出上限,也不拿一个未知年龄的 journal 当「最旧」删掉。
668
+ */
669
+ async retention(completedLimit = 50, historyLimit = 200): Promise<{ completed: number; history: number }> {
670
+ const completedNames = (await this.io.readdirNames(this.completedDir())).filter(isJournalBasename);
671
+ const completed = await this.pruneOldestByAge(
672
+ this.completedDir(), completedNames, completedLimit, (name) => this.completedJournalAt(name),
673
+ );
674
+ const historyNames = await this.io.readdirNames(this.recoveryHistoryDir());
675
+ const history = await this.pruneOldestByAge(
676
+ this.recoveryHistoryDir(), historyNames, historyLimit, async (name) => historyEntryAt(name),
677
+ );
678
+ return { completed, history };
679
+ }
680
+
681
+ /** completed journal 的时间键:记录内 updatedAt;读不出/解析不了 → null(判不了新旧)。 */
682
+ private async completedJournalAt(name: string): Promise<number | null> {
683
+ try {
684
+ const j = parseSafe(await this.io.readFileText(path.join(this.completedDir(), name)));
685
+ if (j === null) return null;
686
+ const at = Date.parse(j.updatedAt);
687
+ return Number.isFinite(at) ? at : null;
688
+ } catch {
689
+ return null; // 读不出 / 并发消失:判不了新旧就不删
690
+ }
569
691
  }
570
692
 
571
- private async pruneOldest(dir: string, names: string[], limit: number): Promise<void> {
572
- if (names.length <= limit) return;
573
- const toRemove = names.slice(0, names.length - limit);
574
- for (const n of toRemove) {
575
- await this.io.rm(path.join(dir, n), { force: true }).catch(() => undefined);
693
+ /** 按时间键升序删除超出上限的最旧项;键为 null 的项不参与计数、绝不被删。返回删除条数。 */
694
+ private async pruneOldestByAge(
695
+ dir: string, names: string[], limit: number, atOf: (name: string) => Promise<number | null>,
696
+ ): Promise<number> {
697
+ const keyed: { name: string; at: number }[] = [];
698
+ for (const name of names) {
699
+ const at = await atOf(name);
700
+ if (at !== null) keyed.push({ name, at });
576
701
  }
702
+ if (keyed.length <= limit) return 0;
703
+ // 同一时刻用文件名做稳定次序,保证幂等(不依赖 readdir 顺序)
704
+ keyed.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
705
+ let removed = 0;
706
+ for (const item of keyed.slice(0, keyed.length - limit)) {
707
+ try {
708
+ await this.io.rm(path.join(dir, item.name), { force: true });
709
+ removed += 1;
710
+ } catch {
711
+ /* 单条删失败不中断其余,留待下一次 */
712
+ }
713
+ }
714
+ return removed;
577
715
  }
578
716
  }
579
717
 
@@ -11,8 +11,10 @@ import fsp from 'node:fs/promises';
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
 
14
- import { createLocalPluginPackHook } from './local-plugin-host.ts';
15
- import type { LocalPluginPackHook } from './local-plugin-host.ts';
14
+ import { EventEmitter } from 'node:events';
15
+
16
+ import { createLocalPluginPackHook, createPackExec } from './local-plugin-host.ts';
17
+ import type { LocalPluginPackHook, PackExecDeps } from './local-plugin-host.ts';
16
18
  import type { PackExec } from './local-plugin-pack.ts';
17
19
 
18
20
  const TARBALL = 'local-pkg-0.1.0.tgz';
@@ -161,3 +163,67 @@ test('无本地源插件:零 spawn、零目录创建', async (t) => {
161
163
  assert.deepEqual(res.warnings, []);
162
164
  assert.deepEqual(res.oversize, []);
163
165
  });
166
+ /* ---------------- 审计 P2-3:pack 超时必须终止整棵进程树 ---------------- */
167
+
168
+ /** 假子进程:够 defaultExec 用的最小面(on/stdout/stderr/kill + pid),不碰真进程。 */
169
+ function fakeChild(pid: number): {
170
+ child: EventEmitter & { pid: number; stdout: EventEmitter; stderr: EventEmitter };
171
+ kills: (string | undefined)[];
172
+ } {
173
+ const child = new EventEmitter() as EventEmitter & {
174
+ pid: number; stdout: EventEmitter; stderr: EventEmitter; kill: (signal?: string) => boolean;
175
+ };
176
+ child.pid = pid;
177
+ child.stdout = new EventEmitter();
178
+ child.stderr = new EventEmitter();
179
+ const kills: (string | undefined)[] = [];
180
+ child.kill = (signal?: string) => { kills.push(signal); return true };
181
+ return { child, kills };
182
+ }
183
+
184
+ test('P2-3 回归:npm pack 超时 → 终止整棵树,而不是只 kill() 掉包装进程', async () => {
185
+ // 旧实现超时只 `child.kill()`:Windows 上死的是 cmd.exe 包装进程,npm/pnpm 孙进程成孤儿
186
+ // 继续往 packDir 写,而调用方 finally 已经 rm 掉 packDir(审计 P2-3 repro 实测孙进程存活)。
187
+ const { child, kills } = fakeChild(4321);
188
+ const treesKilled: number[] = [];
189
+ // 用数组收集而非外部 let:闭包内赋值不会被 TS 的控制流分析看到(会被窄化成 never)
190
+ const spawns: { file: string; opts: Record<string, unknown> }[] = [];
191
+ const exec = createPackExec({
192
+ spawn: ((file: string, _args: readonly string[], opts: Record<string, unknown>) => {
193
+ spawns.push({ file, opts });
194
+ return child;
195
+ }) as unknown as PackExecDeps['spawn'],
196
+ killTree: (c) => { treesKilled.push(c.pid ?? -1) },
197
+ });
198
+
199
+ const pending = exec('npm', ['pack'], { cwd: os.tmpdir(), timeoutMs: 5 });
200
+ child.stderr.emit('data', 'npm ERR! partial output');
201
+ const res = await pending;
202
+
203
+ assert.equal(res.code, 1);
204
+ assert.match(res.stderr, /超时|timed out/, '超时失败仍要回结构化结果(不 reject)');
205
+ assert.match(res.stderr, /npm ERR! partial output/, '已收集的 stderr 要带出来,供调用方定位');
206
+ assert.deepEqual(treesKilled, [4321], '超时必须走整树终止(killTree),pid 是子进程 pid');
207
+ assert.deepEqual(kills, [], '不得只 kill() 包装进程:孙进程会成孤儿继续写已删目录');
208
+ assert.equal(spawns[0]?.opts.detached, process.platform !== 'win32',
209
+ 'POSIX 必须 detached 自成进程组,killTree 的负 pid 才杀得到整棵树');
210
+ });
211
+
212
+ test('P2-3:正常退出不误杀(close 先到 → 清定时器、不调 killTree)', async () => {
213
+ const { child, kills } = fakeChild(4322);
214
+ const treesKilled: number[] = [];
215
+ const exec = createPackExec({
216
+ spawn: (() => child) as unknown as PackExecDeps['spawn'],
217
+ killTree: (c) => { treesKilled.push(c.pid ?? -1) },
218
+ });
219
+
220
+ const pending = exec('npm', ['pack'], { cwd: os.tmpdir(), timeoutMs: 5_000 });
221
+ child.stdout.emit('data', 'local-pkg-0.1.0.tgz\n');
222
+ child.emit('close', 0);
223
+ const res = await pending;
224
+
225
+ assert.equal(res.code, 0);
226
+ assert.equal(res.stdout, 'local-pkg-0.1.0.tgz\n');
227
+ assert.deepEqual(treesKilled, [], '正常结束不得终止任何进程树');
228
+ assert.deepEqual(kills, []);
229
+ });
@@ -11,9 +11,10 @@ import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
12
  import { createHash } from 'node:crypto';
13
13
  import { spawn } from 'node:child_process';
14
+ import type { ChildProcess } from 'node:child_process';
14
15
 
15
16
  import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.ts';
16
- import { quoteCmdArg } from './plugin-cli.ts';
17
+ import { killTree, quoteCmdArg } from './plugin-cli.ts';
17
18
  import type { OversizeLocalPlugin, PackedLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
18
19
  import type { HostContext } from './types.ts';
19
20
  import { engineMsg } from './messages-core.ts';
@@ -49,18 +50,39 @@ const COMSPEC = process.env.ComSpec ?? 'cmd.exe';
49
50
  * 失败**不 reject**(把退出码交回调用方判定),只有 spawn 本身失败才 reject——
50
51
  * 这样「npm 报错」与「npm 不存在」能被分开处理(前者是插件问题,后者是环境问题)。
51
52
  */
52
- const defaultExec: PackExec = (file, args, opts) =>
53
+ /** createPackExec 的注入面(测试用:假子进程 + 记录「整树终止」发生了没有) */
54
+ export interface PackExecDeps {
55
+ spawn?: typeof spawn;
56
+ /** 终止整棵进程树(缺省 core/plugin-cli.ts 的 killTree:Windows taskkill /t /f,POSIX 杀进程组) */
57
+ killTree?: (child: ChildProcess) => void;
58
+ }
59
+
60
+ /**
61
+ * 造一个真实 `npm pack` 执行器;默认导出实例给生产用,测试可注入 spawn / killTree。
62
+ *
63
+ * 超时为什么要整棵树:调用方只 `child.kill()` 时,Windows 死掉的只是 cmd.exe 包装进程,
64
+ * npm/pnpm 孙进程成孤儿继续写 tarball,而 `finally` 已经 rm 掉 packDir(审计 P2-3:
65
+ * 孤儿随后在已删除目录里写、或写出一份没人收的产物)。killTree 与 plugin-cli 的
66
+ * `dsh plugin` 子进程用同一实现(Windows taskkill /T /F;POSIX 负 pid 杀进程组 ——
67
+ * 因此 POSIX 上必须 `detached: true` 让子进程自成进程组,否则 -pid 会打到自己的组)。
68
+ */
69
+ export function createPackExec(deps: PackExecDeps = {}): PackExec {
70
+ const spawnImpl = deps.spawn ?? spawn;
71
+ const killTreeImpl = deps.killTree ?? killTree;
72
+ return (file, args, opts) =>
53
73
  new Promise<PackExecResult>((resolve, reject) => {
54
74
  const useShim = process.platform === 'win32';
55
75
  const [bin, argv] = useShim
56
76
  ? [COMSPEC, ['/d', '/s', '/c', `"${[file, ...args].map(quoteCmdArg).join(' ')}"`]]
57
77
  : [file, [...args]];
58
78
 
59
- const child = spawn(bin, argv, {
79
+ const child = spawnImpl(bin, argv, {
60
80
  cwd: opts.cwd,
61
81
  windowsHide: true,
62
82
  windowsVerbatimArguments: useShim,
63
83
  shell: false, // 显式关闭:Windows 路径已由 cmd.exe 自行处理
84
+ // POSIX:自成进程组,超时才能用负 pid 杀掉整棵树(Windows 忽略该选项,taskkill /T 自己找树)
85
+ detached: process.platform !== 'win32',
64
86
  });
65
87
 
66
88
  let stdout = '';
@@ -70,7 +92,8 @@ const defaultExec: PackExec = (file, args, opts) =>
70
92
  const timer = setTimeout(() => {
71
93
  if (settled) return;
72
94
  settled = true;
73
- child.kill();
95
+ // 整棵树:只 kill() 包装进程会让 npm/pnpm 孙进程成孤儿(见上)
96
+ killTreeImpl(child);
74
97
  resolve({ stdout, stderr: engineMsg('core.localPluginHost.packTimeout', { stderr, timeoutMs }), code: 1 });
75
98
  }, timeoutMs);
76
99
  timer.unref?.();
@@ -90,6 +113,10 @@ const defaultExec: PackExec = (file, args, opts) =>
90
113
  resolve({ stdout, stderr, code });
91
114
  });
92
115
  });
116
+ }
117
+
118
+ /** 生产用的默认执行器(真实 spawn + 真实整树终止) */
119
+ const defaultExec: PackExec = createPackExec();
93
120
 
94
121
  export interface LocalPluginPackHookOptions {
95
122
  /** $DSH_HOME 绝对路径 */
@@ -25,6 +25,7 @@ export const zh = {
25
25
  'export.sectionFailed': '分区 {adapter} 导出失败: {reason}',
26
26
  'export.credentialsReadFailed': '读取凭据文件失败,跳过秘密导出: {reason}',
27
27
  'export.vaultRefreshed': '凭据明文未进入备份,已镜像到本机 vault({count} 个文件,恢复时可回填)',
28
+ 'export.pluginDataSensitiveSkipped': '打包时剔除 {count} 个凭据文件(首个:{sample})——第三方插件数据分区永不携带凭据明文',
28
29
  'export.vaultRefreshSkipped': 'vault 镜像跳过 {rel}: {reason}',
29
30
  'export.vaultRefreshFailed': 'vault 镜像刷新失败(不影响导出): {reason}',
30
31
  'export.sessionsLimited': '会话按数量筛选:只带最新 {count} 个(共 {total} 个;单位 = 会话目录,同一会话的日志一起走)',
@@ -307,6 +308,8 @@ export const zh = {
307
308
  'adapter.patchLineCreate': '写入 patch 行 {lineId}',
308
309
  'adapter.patchLineSame': 'patch 行 {lineId} 已一致',
309
310
  'adapter.patchLineDiff': 'patch 行 {lineId} 与目标不同',
311
+ 'adapter.patchKeyParseFail': 'patch 行 {ref} 在 {path} 处含会让 DSH 整份文件解析失败的键名:先给该键改成合法名字,再导入',
312
+ 'adapter.patchKeyAmbiguous': 'patch 行 {ref} 在 {path} 处的键名 {key} 会被 DSH 读成数字 / 布尔 / null:给键名加引号(\'{key}\':)后重新导入',
310
313
  'adapter.promptSame': '提示词 {name} 已一致',
311
314
  'adapter.promptDiff': '提示词 {name} 与目标不同',
312
315
  'adapter.promptDiffWithLine': '提示词 {name} 与目标不同(目标位于行 {line})',
@@ -344,6 +347,9 @@ export const zh = {
344
347
  'adapter.pwPatchesUnsupported': 'patchedDependencies 为单行 flow 写法,无法安全剔除缺失条目;若目标机没有对应 patch 文件,pnpm 可能拒绝安装:{line}',
345
348
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml 已写入,但移除了 {count} 条 patchedDependencies 声明(目标机没有对应 patch 文件):{names}',
346
349
  'adapter.patchWritten': 'patch 行 {ref} 已写入,重启后生效',
350
+ 'adapter.patchSecretsKept': '{ref} 已写入,但保留本机原有内容:{paths}(备份里这些字段被脱敏清空,未用空值覆盖本机;如需清空请对该行显式确认“使用备份配置”)',
351
+ 'adapter.patchSecretsCleared': '{ref} 已按备份写入,字段 {paths} 现为空(已显式确认该行使用备份配置)',
352
+ 'adapter.patchLocalReadFailed': 'patch 行 {ref} 未写入:读不出本机现值({reason});无法确认这次写入不会覆盖本机原有内容,已跳过这一行',
347
353
  'adapter.credentialValueMissing': '凭据值未提供(需补录)',
348
354
  'adapter.promptWarningNoWrite': '提示项,无需写入',
349
355
  'adapter.promptMissing': '导入数据缺少提示词 {id}',
@@ -481,6 +487,7 @@ export const zh = {
481
487
  'sync.pruneListFailed': '远端快照裁剪失败:无法列出远端快照,{reason}',
482
488
  'sync.pruneDeleteFailed': '远端快照裁剪失败:删除快照 {id} 失败,{reason}',
483
489
  'sync.gcSkipped': '本轮已放弃回收远端孤立文件({code}):本轮不做回收,快照本身不受影响',
490
+ 'sync.latestSkippedEncrypted': '加密快照不生成远端 latest/ 视图(密文无明文镜像):latest/ 保持上一次明文快照的内容,需要明文视图请推一次非加密快照',
484
491
 
485
492
  // ---------- 配置市场(m-market:只读公开仓库目录读取 + 校验) ----------
486
493
  'market.invalidItemId': '非法市场条目 id: {id}(仅允许字母数字开头,字符限 . _ -)',
@@ -553,6 +560,7 @@ export const en: Record<keyof typeof zh, string> = {
553
560
  'export.sectionFailed': 'Section {adapter} export failed: {reason}',
554
561
  'export.credentialsReadFailed': 'Failed to read the credentials file; secrets export skipped: {reason}',
555
562
  'export.vaultRefreshed': 'Credential plaintext did not enter the backup; mirrored to the local vault ({count} file(s), available for restore backfill)',
563
+ 'export.pluginDataSensitiveSkipped': 'Dropped {count} credential file(s) at packaging time (first: {sample}) — third-party plugin data never carries credential plaintext',
556
564
  'export.vaultRefreshSkipped': 'Vault mirror skipped {rel}: {reason}',
557
565
  'export.vaultRefreshFailed': 'Vault mirror refresh failed (export unaffected): {reason}',
558
566
  'export.sessionsLimited': 'Sessions filtered by count: only the latest {count} are included ({total} total; the unit is a session directory, so all logs of one session travel together)',
@@ -835,6 +843,8 @@ export const en: Record<keyof typeof zh, string> = {
835
843
  'adapter.patchLineCreate': 'Write patch row {lineId}',
836
844
  'adapter.patchLineSame': 'Patch row {lineId} is already identical',
837
845
  'adapter.patchLineDiff': 'Patch row {lineId} differs from the target',
846
+ 'adapter.patchKeyParseFail': 'Patch row {ref} has a key at {path} that makes DSH fail to parse the whole file; rename that key before importing',
847
+ 'adapter.patchKeyAmbiguous': 'Key {key} in patch row {ref} (at {path}) is read as a number / boolean / null by DSH; quote it (\'{key}\':) and import again',
838
848
  'adapter.promptSame': 'Prompt {name} is already identical',
839
849
  'adapter.promptDiff': 'Prompt {name} differs from the target',
840
850
  'adapter.promptDiffWithLine': 'Prompt {name} differs from the target (target lives at row {line})',
@@ -872,6 +882,9 @@ export const en: Record<keyof typeof zh, string> = {
872
882
  'adapter.pwPatchesUnsupported': 'patchedDependencies uses single-line flow syntax, so missing entries cannot be removed safely; if the target lacks the patch files pnpm may refuse installs: {line}',
873
883
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml written, but {count} patchedDependencies entries were removed (the target has no matching patch file): {names}',
874
884
  'adapter.patchWritten': 'Patch row {ref} written; takes effect after restart',
885
+ 'adapter.patchSecretsKept': '{ref} written, but local values were kept for: {paths} (these fields were redacted to empty in the backup, so the empty values did not overwrite local content; confirm “use backup config” on this row explicitly if you want them cleared)',
886
+ 'adapter.patchSecretsCleared': '{ref} written from the backup; fields {paths} are now empty (you explicitly confirmed using the backup config for this row)',
887
+ 'adapter.patchLocalReadFailed': 'Patch row {ref} not written: the local value could not be read ({reason}), so the write cannot be proven safe and this row was skipped',
875
888
  'adapter.credentialValueMissing': 'Credential value not provided (re-entry required)',
876
889
  'adapter.promptWarningNoWrite': 'Informational item; nothing to write',
877
890
  'adapter.promptMissing': 'Import data is missing prompt {id}',
@@ -1005,6 +1018,7 @@ export const en: Record<keyof typeof zh, string> = {
1005
1018
  'sync.pruneListFailed': 'Remote snapshot pruning failed: could not list remote snapshots, {reason}',
1006
1019
  'sync.pruneDeleteFailed': 'Remote snapshot pruning failed: deleting snapshot {id} failed, {reason}',
1007
1020
  'sync.gcSkipped': 'Skipped reclaiming remote orphan files this round ({code}); snapshots are unaffected',
1021
+ 'sync.latestSkippedEncrypted': 'Encrypted snapshots do not produce the remote latest/ view (ciphertext has no plaintext mirror): latest/ keeps the previous plaintext snapshot content; push a non-encrypted snapshot if you need it refreshed',
1008
1022
 
1009
1023
  // ---------- config marketplace (m-market: read-only public repo directory read + validation) ----------
1010
1024
  'market.invalidItemId': 'Invalid marketplace item id: {id} (must start with an alphanumeric; only . _ - allowed)',
@@ -398,6 +398,33 @@ test('best-effort:注入失败 IO → append 返回 ok:false 不 throw', async
398
398
  assert.ok(res.error);
399
399
  });
400
400
 
401
+ test('P3-6:目录读不出(EACCES/ENOTDIR)必须显式失败,不得谎报「0 条、无损坏」', async (t) => {
402
+ const dir = tmp(t);
403
+ const denies = (code: string): MigrationIo => ({
404
+ async mkdir() { return; },
405
+ async readdirNames() { throw Object.assign(new Error(`${code}: scandir failed`), { code }); },
406
+ async readFileText() { return ''; },
407
+ async writeAll() { return; },
408
+ async rm() { return; },
409
+ async lstat() { return null; },
410
+ async exists() { return false; },
411
+ });
412
+ for (const code of ['EACCES', 'ENOTDIR']) {
413
+ const store = new MigrationStore({ dir: path.join(dir, `denied-${code}`), io: denies(code) });
414
+ await assert.rejects(() => store.read(), new RegExp(code), `read 必须抛 ${code}`);
415
+ await assert.rejects(() => store.count(), new RegExp(code), `count 必须抛 ${code}`);
416
+ await assert.rejects(() => store.retention(10), new RegExp(code), `retention 必须抛 ${code}`);
417
+ }
418
+ });
419
+
420
+ test('P3-6:默认 IO 仍把 ENOENT(目录不存在)当空目录,不算失败', async (t) => {
421
+ const dir = tmp(t);
422
+ const store = new MigrationStore({ dir: path.join(dir, 'missing-dir') });
423
+ assert.deepEqual(await store.read(), { entries: [], corrupted: [], total: 0 });
424
+ assert.equal(await store.count(), 0);
425
+ assert.deepEqual(await store.retention(10), []);
426
+ });
427
+
401
428
  test('best-effort:read 目录不存在 → 空结果不 throw', async (t) => {
402
429
  const dir = tmp(t);
403
430
  const store = new MigrationStore({ dir: path.join(dir, 'no-such-dir') });
@@ -259,7 +259,15 @@ export interface MigrationIo {
259
259
 
260
260
  const defaultIo: MigrationIo = {
261
261
  async mkdir(d, o) { await fs.mkdir(d, o); },
262
- async readdirNames(d) { try { return await fs.readdir(d); } catch { return []; } },
262
+ // 只有「目录不存在」才算空:权限/路径类型错误必须抛给调用方(审计 P3-6)。
263
+ // 旧实现 catch 一切 → 读不出的目录被当作空目录,历史面板显示「共 0 条」、
264
+ // 自动清理也算 0 条直接跳过,用户完全看不出是读取失败。
265
+ async readdirNames(d) {
266
+ try { return await fs.readdir(d); } catch (err) {
267
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
268
+ throw err;
269
+ }
270
+ },
263
271
  async readFileText(p) { return (await fs.readFile(p, 'utf8')).toString(); },
264
272
  async writeAll(t, c) { await atomicWriteFile(t, c, { mode: 0o600, symlink: 'reject' }); },
265
273
  async rm(p, o) { await fs.rm(p, o); },
@@ -473,7 +481,7 @@ export class MigrationStore {
473
481
  * 调用方据此区分「共 N 条,本页只含最近 M 条」。
474
482
  */
475
483
  async read(opts: { limit?: number } = {}): Promise<ReadMigrationResult> {
476
- const names = await this.io.readdirNames(this.dir).catch(() => []);
484
+ const names = await this.io.readdirNames(this.dir);
477
485
  const entries: StoredMigrationHistoryEntry[] = [];
478
486
  const corrupted: string[] = [];
479
487
  const sorted = names.filter(isHistoryBasename).sort();
@@ -498,7 +506,7 @@ export class MigrationStore {
498
506
 
499
507
  /** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
500
508
  async count(): Promise<number> {
501
- const names = await this.io.readdirNames(this.dir).catch(() => []);
509
+ const names = await this.io.readdirNames(this.dir);
502
510
  return names.filter(isHistoryBasename).length;
503
511
  }
504
512
 
@@ -507,7 +515,7 @@ export class MigrationStore {
507
515
  * 返回本次删除的文件名。
508
516
  */
509
517
  async retention(limit = DEFAULT_MIGRATION_RETENTION): Promise<string[]> {
510
- const names = (await this.io.readdirNames(this.dir).catch(() => [])).filter(isHistoryBasename).sort();
518
+ const names = (await this.io.readdirNames(this.dir)).filter(isHistoryBasename).sort();
511
519
  const removed: string[] = [];
512
520
  // 0(或负数)= 不限制:调用方显式关闭自动清理时按「保留全部」处理,绝不当作「删光」。
513
521
  if (!Number.isFinite(limit) || limit <= 0) return removed;
@@ -364,6 +364,73 @@ test('config_sync_push:复用 SyncEngine.push(内存 transport),返回 s
364
364
  }
365
365
  })
366
366
 
367
+ test('config_sync_push:内容未变 → 如实回传 skipped=unchanged(issue #140:不再造重复快照)', async () => {
368
+ const { deps, tmp, transport } = await makeDeps()
369
+ try {
370
+ await writeSyncConfig(deps.syncDir, { schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://github.com/u/r.git' } })
371
+ const tools = createModelTools(deps)
372
+ const first = (await tools.syncPush({ channel: 'git' })) as { ok: boolean; snapshotId: string }
373
+ assert.equal(first.ok, true)
374
+ const uploads = transport.calls.filter((c) => c === 'upload').length
375
+
376
+ const second = (await tools.syncPush({ channel: 'git' })) as {
377
+ ok: boolean; snapshotId: string; skipped?: string; adoptedSnapshotId?: string
378
+ }
379
+ assert.equal(second.ok, true)
380
+ assert.equal(second.skipped, 'unchanged', '模型必须看到「内容没变」,而不是「又推了一版」')
381
+ assert.equal(second.snapshotId, first.snapshotId, '沿用既有快照 id')
382
+ assert.equal(second.adoptedSnapshotId, first.snapshotId)
383
+ assert.equal(transport.calls.filter((c) => c === 'upload').length, uploads, '一次 upload 都不发')
384
+
385
+ const forced = (await tools.syncPush({ channel: 'git', force: true })) as { ok: boolean; skipped?: string }
386
+ assert.equal(forced.skipped, undefined, 'force 覆盖跳过判定')
387
+ assert.equal(transport.calls.filter((c) => c === 'upload').length, uploads + 1, 'force 才真的上传')
388
+ } finally {
389
+ await fs.rm(tmp, { recursive: true, force: true })
390
+ }
391
+ })
392
+
393
+ test('config_sync_push:用户放行的可选分区必须进引擎(issue #138:显式 mcp 不再 skipNonPortable)', async () => {
394
+ const { deps, tmp, transport, ctx } = await makeDeps()
395
+ try {
396
+ await writeSyncConfig(deps.syncDir, { schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://github.com/u/r.git' } })
397
+ // mcp adapter 的数据源:一行 dsh-mcp-client patch(与 sync-engine.test.ts 的 seedMcp 同形)
398
+ ctx.patchFile.lines.set('mcp-citra', {
399
+ lineId: 'mcp-citra',
400
+ raw: {
401
+ id: 'mcp-citra',
402
+ name: 'dsh-mcp-client',
403
+ config: { serverName: 'citra', command: 'npx', args: ['-y', '@sylphx/citra'] },
404
+ },
405
+ })
406
+ // 真实装配口径:宿主把 'auto' 档交给 deps.optInSections;这里故意混入 sessions 验证永久排除。
407
+ const seenOptIn: (readonly SectionId[])[] = []
408
+ const inner = deps.makeSyncEngine
409
+ const tools = createModelTools({
410
+ ...deps,
411
+ makeSyncEngine: (cfg, engineOpts) => {
412
+ seenOptIn.push(engineOpts?.optInSections ?? [])
413
+ return inner(cfg, engineOpts)
414
+ },
415
+ optInSections: () => ['mcp', 'sessions'],
416
+ })
417
+ const out = (await tools.syncPush({ channel: 'git', sections: ['settings', 'mcp'] })) as {
418
+ ok: boolean; sections: string[]; warnings: string[]
419
+ }
420
+ assert.equal(out.ok, true)
421
+ assert.ok(out.sections.includes('mcp'), '显式放行的 mcp 必须进入快照: ' + out.sections.join(','))
422
+ assert.ok(!out.sections.includes('sessions'), 'sessions 永不上行')
423
+ assert.deepEqual(seenOptIn[seenOptIn.length - 1], ['mcp'], '引擎收到的可选分区 = 放行集合 − sessions')
424
+ assert.ok(
425
+ !out.warnings.some((w) => w.includes('mcp')),
426
+ '放行后不得再报 skipNonPortable: ' + out.warnings.join(' | '),
427
+ )
428
+ assert.ok(transport.calls.includes('upload'), 'push 写远端')
429
+ } finally {
430
+ await fs.rm(tmp, { recursive: true, force: true })
431
+ }
432
+ })
433
+
367
434
  test('config_sync_pull:空远端 → 零写入空差异', async () => {
368
435
  const { deps, tmp, transport, ctx } = await makeDeps()
369
436
  try {