dsh-config-manager 0.8.2 → 0.10.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 (418) hide show
  1. package/lib/adapters/mcp.js +51 -15
  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 +204 -6
  10. package/lib/adapters/prompts.js +15 -4
  11. package/lib/adapters/test-helpers.d.ts +15 -1
  12. package/lib/adapters/test-helpers.js +11 -0
  13. package/lib/cli/actions.d.ts +7 -105
  14. package/lib/cli/actions.js +16 -172
  15. package/lib/cli/control-state.d.ts +54 -0
  16. package/lib/cli/control-state.js +107 -0
  17. package/lib/cli/help.d.ts +1 -1
  18. package/lib/cli/help.js +21 -14
  19. package/lib/cli/index.js +132 -104
  20. package/lib/cli/sessions-repair.js +58 -22
  21. package/lib/cli/web/client-script.d.ts +1 -1
  22. package/lib/cli/web/client-script.js +71 -5
  23. package/lib/cli/web/page.d.ts +9 -19
  24. package/lib/cli/web/page.js +277 -173
  25. package/lib/cli/web/routes.js +85 -25
  26. package/lib/cli/write-gates.d.ts +61 -0
  27. package/lib/cli/write-gates.js +110 -0
  28. package/lib/client.d.ts +196 -75
  29. package/lib/client.js +8139 -7487
  30. package/lib/core/backup.d.ts +0 -4
  31. package/lib/core/backup.js +21 -4
  32. package/lib/core/boot-rescue.d.ts +1 -1
  33. package/lib/core/boot-rescue.js +12 -1
  34. package/lib/core/boot-safety.js +37 -2
  35. package/lib/core/conflict-decisions.js +2 -1
  36. package/lib/core/exporter.js +22 -1
  37. package/lib/core/journal.d.ts +54 -4
  38. package/lib/core/journal.js +158 -35
  39. package/lib/core/local-plugin-host.d.ts +29 -0
  40. package/lib/core/local-plugin-host.js +55 -48
  41. package/lib/core/messages.d.ts +17 -0
  42. package/lib/core/messages.js +34 -0
  43. package/lib/core/migration-history.js +16 -9
  44. package/lib/core/model-tools.d.ts +2 -2
  45. package/lib/core/model-tools.js +20 -2
  46. package/lib/core/patch-chain.d.ts +65 -0
  47. package/lib/core/patch-chain.js +100 -0
  48. package/lib/core/patch-document.d.ts +32 -4
  49. package/lib/core/patch-document.js +48 -17
  50. package/lib/core/patch-secret-guard.d.ts +49 -0
  51. package/lib/core/patch-secret-guard.js +164 -0
  52. package/lib/core/reconcile.d.ts +8 -0
  53. package/lib/core/reconcile.js +18 -3
  54. package/lib/core/reinstall.d.ts +2 -0
  55. package/lib/core/reinstall.js +6 -2
  56. package/lib/core/restore.js +31 -6
  57. package/lib/core/section-sanitize.d.ts +32 -0
  58. package/lib/core/section-sanitize.js +13 -0
  59. package/lib/core/snapshot-diff.d.ts +30 -0
  60. package/lib/core/snapshot-diff.js +56 -20
  61. package/lib/core/startup-barrier.js +8 -2
  62. package/lib/core/types.d.ts +38 -1
  63. package/lib/core/update-check.js +51 -2
  64. package/lib/foreign/kernel.js +9 -2
  65. package/lib/foreign/read-claude-plugins.js +29 -11
  66. package/lib/foreign/read-dsh.js +31 -2
  67. package/lib/foreign/session-ir.js +50 -9
  68. package/lib/foreign/session-read.d.ts +8 -0
  69. package/lib/foreign/session-read.js +26 -0
  70. package/lib/index.d.ts +9 -4
  71. package/lib/index.js +42 -47
  72. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  73. package/lib/profiles/dsh-profile-io.js +27 -0
  74. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  75. package/lib/profiles/dsh-profile-manager.js +45 -4
  76. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  77. package/lib/profiles/dsh-profile-runtime.js +16 -3
  78. package/lib/profiles/process-control.d.ts +18 -1
  79. package/lib/profiles/process-control.js +25 -1
  80. package/lib/routes/profiles.js +2 -1
  81. package/lib/routes/sync.js +19 -1
  82. package/lib/schema/types.d.ts +11 -0
  83. package/lib/security/redaction.js +22 -6
  84. package/lib/sync/autosync-repeat.d.ts +27 -0
  85. package/lib/sync/autosync-repeat.js +23 -0
  86. package/lib/sync/autosync-scheduler.d.ts +47 -2
  87. package/lib/sync/autosync-scheduler.js +217 -53
  88. package/lib/sync/baseline-heal.js +7 -0
  89. package/lib/sync/baseline-record.d.ts +67 -0
  90. package/lib/sync/baseline-record.js +74 -0
  91. package/lib/sync/blob-store.js +13 -0
  92. package/lib/sync/content-diff.d.ts +39 -0
  93. package/lib/sync/content-diff.js +46 -0
  94. package/lib/sync/git/git-transport.d.ts +32 -1
  95. package/lib/sync/git/git-transport.js +146 -26
  96. package/lib/sync/github-auth.d.ts +17 -1
  97. package/lib/sync/github-auth.js +37 -1
  98. package/lib/sync/local-changes.d.ts +15 -0
  99. package/lib/sync/local-changes.js +39 -0
  100. package/lib/sync/merge-apply-plan.d.ts +38 -0
  101. package/lib/sync/merge-apply-plan.js +76 -0
  102. package/lib/sync/merge-keyed.d.ts +68 -0
  103. package/lib/sync/merge-keyed.js +124 -0
  104. package/lib/sync/messages.d.ts +1 -0
  105. package/lib/sync/messages.js +2 -0
  106. package/lib/sync/patch-line-identity.d.ts +19 -0
  107. package/lib/sync/patch-line-identity.js +99 -0
  108. package/lib/sync/pending-merge.d.ts +41 -0
  109. package/lib/sync/pending-merge.js +61 -0
  110. package/lib/sync/plugin-removals.d.ts +15 -15
  111. package/lib/sync/plugin-removals.js +134 -83
  112. package/lib/sync/push-skip.d.ts +55 -0
  113. package/lib/sync/push-skip.js +70 -0
  114. package/lib/sync/s3/s3-transport.d.ts +14 -2
  115. package/lib/sync/s3/s3-transport.js +72 -48
  116. package/lib/sync/sync-engine.d.ts +44 -51
  117. package/lib/sync/sync-engine.js +160 -194
  118. package/lib/sync/sync-history.d.ts +7 -0
  119. package/lib/sync/sync-state.d.ts +28 -0
  120. package/lib/sync/sync-state.js +20 -0
  121. package/lib/sync/transport.d.ts +12 -3
  122. package/lib/sync/transport.js +13 -4
  123. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  124. package/lib/sync/webdav/webdav-transport.js +81 -40
  125. package/lib/sync/workspace-merge.d.ts +8 -2
  126. package/lib/ui/artifact-view.d.ts +1 -1
  127. package/lib/ui/commands.js +5 -11
  128. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  129. package/lib/ui/dsh-profiles-view.js +9 -5
  130. package/lib/ui/foreign-view.d.ts +14 -0
  131. package/lib/ui/foreign-view.js +34 -0
  132. package/lib/ui/i18n.d.ts +7 -1
  133. package/lib/ui/i18n.js +15 -2
  134. package/lib/ui/menu-placement.js +1 -1
  135. package/lib/ui/migration-consult-view.d.ts +11 -0
  136. package/lib/ui/migration-consult-view.js +15 -0
  137. package/lib/ui/overview-view.d.ts +7 -0
  138. package/lib/ui/overview-view.js +3 -0
  139. package/lib/ui/report.d.ts +9 -0
  140. package/lib/ui/report.js +17 -4
  141. package/lib/ui/selection-model.d.ts +10 -2
  142. package/lib/ui/selection-model.js +23 -3
  143. package/lib/utils/async-once.d.ts +11 -0
  144. package/lib/utils/async-once.js +15 -0
  145. package/lib/utils/patch-chain-read.d.ts +51 -0
  146. package/lib/utils/patch-chain-read.js +240 -0
  147. package/lib/utils/patch-yaml.d.ts +39 -1
  148. package/lib/utils/patch-yaml.js +82 -2
  149. package/lib/utils/paths.d.ts +13 -0
  150. package/lib/utils/paths.js +35 -0
  151. package/lib/utils/workdir-lock.js +18 -3
  152. package/package.json +3 -2
  153. package/src/adapters/mcp.test.ts +29 -0
  154. package/src/adapters/mcp.ts +52 -14
  155. package/src/adapters/messages.ts +2 -0
  156. package/src/adapters/patch-key-guard.ts +29 -0
  157. package/src/adapters/plugin-data.test.ts +126 -0
  158. package/src/adapters/plugin-data.ts +97 -26
  159. package/src/adapters/plugins.test.ts +403 -0
  160. package/src/adapters/plugins.ts +198 -8
  161. package/src/adapters/prompts.ts +15 -4
  162. package/src/adapters/test-helpers.ts +15 -1
  163. package/src/cli/actions.test.ts +74 -1
  164. package/src/cli/actions.ts +27 -246
  165. package/src/cli/control-state.ts +143 -0
  166. package/src/cli/help.ts +21 -14
  167. package/src/cli/index.ts +123 -107
  168. package/src/cli/sessions-repair.ts +55 -22
  169. package/src/cli/web/client-script.ts +71 -5
  170. package/src/cli/web/page.ts +327 -208
  171. package/src/cli/web/routes.ts +85 -25
  172. package/src/cli/web/web.test.ts +65 -0
  173. package/src/cli/write-gates.ts +149 -0
  174. package/src/client/ConfigManagerSection.tsx +8 -4
  175. package/src/client/about/AboutPanel.tsx +9 -12
  176. package/src/client/about/release-notes-view.test.ts +17 -0
  177. package/src/client/about/release-notes-view.ts +49 -24
  178. package/src/client/api.ts +2 -1
  179. package/src/client/chat/ChatEntryView.tsx +2 -2
  180. package/src/client/chat/rollback-entry-view.ts +6 -1
  181. package/src/client/common/CommandPalette.tsx +6 -3
  182. package/src/client/common/ConfirmDialog.tsx +29 -12
  183. package/src/client/common/ContentPicker.tsx +24 -24
  184. package/src/client/common/Modal.tsx +12 -5
  185. package/src/client/common/MoreMenu.tsx +4 -1
  186. package/src/client/common/RunsCenter.tsx +103 -32
  187. package/src/client/common/Select.tsx +2 -2
  188. package/src/client/common/floating-bounds.ts +1 -1
  189. package/src/client/common/floating-units.test.ts +1 -2
  190. package/src/client/common/plan-text-redaction.test.ts +190 -5
  191. package/src/client/common/runs-center-guard.test.ts +60 -0
  192. package/src/client/common/runs-center-view.test.ts +128 -0
  193. package/src/client/common/runs-center-view.ts +96 -0
  194. package/src/client/common/section-title-action.test.ts +66 -0
  195. package/src/client/common/ui.tsx +93 -30
  196. package/src/client/config-manager.module.css +1515 -270
  197. package/src/client/consult/ConsultCard.tsx +7 -6
  198. package/src/client/environment/EnvironmentPanel.tsx +22 -25
  199. package/src/client/environment/maintenance/DiskUsageCard.tsx +69 -96
  200. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  201. package/src/client/export/ExportView.tsx +7 -16
  202. package/src/client/history/HistoryPanel.tsx +88 -28
  203. package/src/client/history/history-locales.ts +3 -3
  204. package/src/client/home/BackupScheduleCard.tsx +77 -69
  205. package/src/client/home/HomePanel.tsx +47 -12
  206. package/src/client/import/ConflictList.tsx +13 -13
  207. package/src/client/import/ForeignImportView.tsx +67 -9
  208. package/src/client/import/ImportWizardView.tsx +4 -4
  209. package/src/client/import/PathMappingForm.tsx +36 -9
  210. package/src/client/import/PathPickerDialog.tsx +2 -1
  211. package/src/client/import/import-wizard-split.test.ts +1 -1
  212. package/src/client/import/import-wizard-steps.tsx +51 -39
  213. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  214. package/src/client/import/use-import-wizard-controller.ts +116 -22
  215. package/src/client/library/ArtifactRow.tsx +2 -2
  216. package/src/client/library/BackupInspectView.tsx +21 -15
  217. package/src/client/library/LibraryActions.tsx +116 -28
  218. package/src/client/library/LibraryPanel.tsx +14 -15
  219. package/src/client/library/RestorePlanView.tsx +13 -8
  220. package/src/client/locales/about.ts +0 -2
  221. package/src/client/locales/backup.ts +15 -12
  222. package/src/client/locales/common.ts +2 -0
  223. package/src/client/locales/export.ts +5 -12
  224. package/src/client/locales/foreign.ts +4 -2
  225. package/src/client/locales/import.ts +5 -2
  226. package/src/client/locales/overview.ts +4 -0
  227. package/src/client/locales/profiles.ts +32 -4
  228. package/src/client/locales/restore.ts +2 -2
  229. package/src/client/locales/sessions.ts +0 -2
  230. package/src/client/locales/shell.ts +2 -2
  231. package/src/client/market/MarketImportReview.tsx +4 -4
  232. package/src/client/market/MarketPanel.tsx +58 -56
  233. package/src/client/market/MyConfigsList.tsx +34 -32
  234. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  235. package/src/client/market/MyConfigsView.tsx +8 -15
  236. package/src/client/market/MyConfigsWizard.tsx +7 -12
  237. package/src/client/market/market-locales.ts +0 -6
  238. package/src/client/market/my-configs-split.test.ts +2 -1
  239. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  240. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  241. package/src/client/recovery/RecoveryPanel.tsx +35 -22
  242. package/src/client/recovery/RollbackCard.tsx +132 -75
  243. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  244. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  245. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  246. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  247. package/src/client/recovery/recovery-locales.ts +12 -8
  248. package/src/client/recovery/rollback-enabled.ts +29 -0
  249. package/src/client/recovery/use-recovery-write.ts +5 -0
  250. package/src/client/run-store.test.ts +30 -0
  251. package/src/client/run-store.ts +21 -1
  252. package/src/client/sync/AddChannelCard.tsx +65 -0
  253. package/src/client/sync/AutosyncCard.tsx +184 -108
  254. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  255. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  256. package/src/client/sync/MergePreviewView.tsx +5 -7
  257. package/src/client/sync/PushPreviewCard.tsx +2 -1
  258. package/src/client/sync/PushReportSections.tsx +35 -0
  259. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  260. package/src/client/sync/SyncConfirmView.tsx +130 -133
  261. package/src/client/sync/SyncLogList.tsx +29 -14
  262. package/src/client/sync/SyncPanel.tsx +188 -185
  263. package/src/client/sync/SyncProbeRow.tsx +5 -7
  264. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  265. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  266. package/src/client/sync/SyncSettingsDialog.tsx +293 -0
  267. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  268. package/src/client/sync/WorkDirCard.tsx +2 -4
  269. package/src/client/sync/config-clear-guard.test.ts +94 -0
  270. package/src/client/sync/config-clear-guard.ts +98 -0
  271. package/src/client/sync/config-dirty.test.ts +91 -0
  272. package/src/client/sync/config-dirty.ts +88 -0
  273. package/src/client/sync/history-model.test.ts +2 -0
  274. package/src/client/sync/history-model.ts +5 -0
  275. package/src/client/sync/merge-request.ts +20 -0
  276. package/src/client/sync/sync-api.ts +13 -1
  277. package/src/client/sync/sync-locales.ts +95 -47
  278. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  279. package/src/client/sync/sync-push-preview.test.ts +9 -0
  280. package/src/client/sync/sync-view.test.ts +20 -0
  281. package/src/client/sync/sync-view.ts +76 -4
  282. package/src/core/backup.test.ts +61 -1
  283. package/src/core/backup.ts +21 -4
  284. package/src/core/boot-rescue.test.ts +35 -0
  285. package/src/core/boot-rescue.ts +13 -2
  286. package/src/core/boot-safety.test.ts +25 -0
  287. package/src/core/boot-safety.ts +37 -2
  288. package/src/core/conflict-decisions.ts +2 -1
  289. package/src/core/exporter.ts +21 -1
  290. package/src/core/journal.test.ts +183 -0
  291. package/src/core/journal.ts +163 -25
  292. package/src/core/local-plugin-host.test.ts +68 -2
  293. package/src/core/local-plugin-host.ts +31 -4
  294. package/src/core/messages.ts +34 -0
  295. package/src/core/migration-history.test.ts +27 -0
  296. package/src/core/migration-history.ts +12 -4
  297. package/src/core/model-tools.test.ts +67 -0
  298. package/src/core/model-tools.ts +22 -4
  299. package/src/core/patch-chain.test.ts +83 -0
  300. package/src/core/patch-chain.ts +150 -0
  301. package/src/core/patch-document.test.ts +48 -1
  302. package/src/core/patch-document.ts +66 -15
  303. package/src/core/patch-layers.test.ts +1 -1
  304. package/src/core/patch-secret-guard.test.ts +110 -0
  305. package/src/core/patch-secret-guard.ts +176 -0
  306. package/src/core/reconcile.ts +32 -4
  307. package/src/core/reinstall.ts +8 -2
  308. package/src/core/restore.ts +32 -7
  309. package/src/core/section-sanitize.ts +37 -0
  310. package/src/core/smoke.test.ts +2 -1
  311. package/src/core/snapshot-diff.test.ts +73 -1
  312. package/src/core/snapshot-diff.ts +66 -21
  313. package/src/core/startup-barrier.test.ts +64 -0
  314. package/src/core/startup-barrier.ts +8 -2
  315. package/src/core/types.ts +43 -2
  316. package/src/core/update-check.test.ts +40 -0
  317. package/src/core/update-check.ts +53 -2
  318. package/src/foreign/claude-code.test.ts +5 -0
  319. package/src/foreign/claude-plugins.test.ts +57 -0
  320. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  321. package/src/foreign/dsh.test.ts +23 -0
  322. package/src/foreign/kernel.ts +9 -2
  323. package/src/foreign/read-claude-plugins.ts +32 -11
  324. package/src/foreign/read-dsh.ts +33 -2
  325. package/src/foreign/session-ir.test.ts +67 -0
  326. package/src/foreign/session-ir.ts +54 -14
  327. package/src/foreign/session-read.ts +23 -0
  328. package/src/index.facade.test.ts +186 -6
  329. package/src/index.ts +53 -47
  330. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  331. package/src/profiles/dsh-profile-io.ts +29 -0
  332. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  333. package/src/profiles/dsh-profile-manager.ts +53 -5
  334. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  335. package/src/profiles/dsh-profile-runtime.ts +17 -3
  336. package/src/profiles/process-control.test.ts +97 -0
  337. package/src/profiles/process-control.ts +28 -1
  338. package/src/routes/profiles.ts +2 -1
  339. package/src/routes/sync.ts +19 -1
  340. package/src/schema/types.ts +16 -1
  341. package/src/security/redaction.test.ts +31 -0
  342. package/src/security/redaction.ts +23 -6
  343. package/src/security/security.test.ts +1 -1
  344. package/src/sync/autosync-repeat.test.ts +58 -0
  345. package/src/sync/autosync-repeat.ts +55 -0
  346. package/src/sync/autosync-scheduler.test.ts +515 -0
  347. package/src/sync/autosync-scheduler.ts +225 -51
  348. package/src/sync/baseline-heal.ts +6 -0
  349. package/src/sync/baseline-record.ts +135 -0
  350. package/src/sync/blob-store.test.ts +16 -0
  351. package/src/sync/blob-store.ts +13 -0
  352. package/src/sync/content-diff.test.ts +95 -0
  353. package/src/sync/content-diff.ts +79 -0
  354. package/src/sync/git/git-transport.test.ts +151 -4
  355. package/src/sync/git/git-transport.ts +143 -27
  356. package/src/sync/github-auth.test.ts +26 -1
  357. package/src/sync/github-auth.ts +37 -1
  358. package/src/sync/local-changes.ts +40 -0
  359. package/src/sync/merge-apply-plan.ts +117 -0
  360. package/src/sync/merge-keyed.test.ts +167 -0
  361. package/src/sync/merge-keyed.ts +160 -0
  362. package/src/sync/messages.ts +3 -0
  363. package/src/sync/patch-line-identity.test.ts +73 -0
  364. package/src/sync/patch-line-identity.ts +105 -0
  365. package/src/sync/pending-merge.test.ts +41 -0
  366. package/src/sync/pending-merge.ts +85 -0
  367. package/src/sync/plugin-removals.test.ts +199 -39
  368. package/src/sync/plugin-removals.ts +150 -64
  369. package/src/sync/push-skip.test.ts +326 -0
  370. package/src/sync/push-skip.ts +102 -0
  371. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  372. package/src/sync/s3/s3-transport.ts +76 -42
  373. package/src/sync/sync-config.test.ts +39 -12
  374. package/src/sync/sync-device-identity.test.ts +3 -0
  375. package/src/sync/sync-engine.test.ts +465 -12
  376. package/src/sync/sync-engine.ts +189 -193
  377. package/src/sync/sync-history.ts +7 -0
  378. package/src/sync/sync-state.ts +48 -0
  379. package/src/sync/transport.test.ts +13 -1
  380. package/src/sync/transport.ts +12 -4
  381. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  382. package/src/sync/webdav/webdav-transport.ts +86 -34
  383. package/src/sync/workspace-merge.ts +9 -2
  384. package/src/ui/artifact-view.ts +1 -1
  385. package/src/ui/commands.test.ts +11 -0
  386. package/src/ui/commands.ts +5 -14
  387. package/src/ui/dsh-profiles-view.test.ts +16 -0
  388. package/src/ui/dsh-profiles-view.ts +11 -5
  389. package/src/ui/foreign-view.test.ts +49 -0
  390. package/src/ui/foreign-view.ts +47 -0
  391. package/src/ui/i18n.ts +15 -2
  392. package/src/ui/menu-placement.ts +1 -1
  393. package/src/ui/migration-consult-view.test.ts +20 -1
  394. package/src/ui/migration-consult-view.ts +17 -0
  395. package/src/ui/overview-view.ts +10 -0
  396. package/src/ui/report.test.ts +25 -1
  397. package/src/ui/report.ts +15 -4
  398. package/src/ui/selection-model.test.ts +29 -1
  399. package/src/ui/selection-model.ts +25 -4
  400. package/src/utils/async-once.ts +14 -0
  401. package/src/utils/js-yaml4.d.ts +35 -0
  402. package/src/utils/patch-chain-read.test.ts +171 -0
  403. package/src/utils/patch-chain-read.ts +259 -0
  404. package/src/utils/patch-yaml.test.ts +215 -3
  405. package/src/utils/patch-yaml.ts +98 -2
  406. package/src/utils/paths.test.ts +14 -1
  407. package/src/utils/paths.ts +35 -0
  408. package/src/utils/workdir-lock.test.ts +69 -0
  409. package/src/utils/workdir-lock.ts +17 -3
  410. package/lib/ui/path-mapping.d.ts +0 -38
  411. package/lib/ui/path-mapping.js +0 -75
  412. package/src/client/common/InfoHint.tsx +0 -289
  413. package/src/client/common/info-hint-guard.test.ts +0 -1119
  414. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  415. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  416. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  417. package/src/ui/path-mapping.test.ts +0 -67
  418. 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} 个;单位 = 会话目录,同一会话的日志一起走)',
@@ -210,6 +211,7 @@ export const zh = {
210
211
  'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写',
211
212
  'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉',
212
213
  'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)',
214
+ 'host.patchRefuseUnknownId': 'patch 层 {file} 的写入含顶层行 {ids},但生效 patch 链(bundle 层 / profile 层 / home 层)没有任何一层提供这些 id:宿主会按 not found 整行丢弃,已拒绝写入,文件未改动',
213
215
  'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动',
214
216
  'host.fsPathEscape': '路径越界: {path}',
215
217
  'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)',
@@ -305,8 +307,17 @@ export const zh = {
305
307
  'adapter.pluginInstallFailed': '插件 {name} 安装失败:{msg}。可手动安装:dsh plugin --profile {profile} add {name}(其余配置已导入;可修复依赖后在设置页重试或手动安装)',
306
308
  'adapter.pluginUpdateFailed': '插件 {name} 更新失败:{msg}。可手动安装:dsh plugin --profile {profile} add {name}(其余配置已导入;可修复依赖后在设置页重试或手动安装)',
307
309
  'adapter.patchLineCreate': '写入 patch 行 {lineId}',
310
+ 'adapter.patchLineOverride': '覆盖已存在条目(写入 patch 行 {lineId})',
311
+ 'adapter.patchLineOverrideDetail': '该 id 已由 {layers} 提供:只能写顶层覆盖行;写成 insert 会产生第二条同 id 条目(DSH 里保存该插件配置时会报 overridden)',
312
+ 'adapter.patchLineDowngraded': '{ids} 已由其它 patch 层提供,本次改写为覆盖行(不再新增第二条同 id 条目)',
313
+ 'adapter.patchChainPartial': '生效 patch 链有 {count} 层读不出来({files}):本次「这个 id 是否已存在」的判定只覆盖读到的那几层',
314
+ 'adapter.patchLineDuplicateInsert': 'patch 行 {lineId} 在本机已有多条「新增」(insert)来源:同 id 两条新增会让 DSH 保存该插件配置时一直报 overridden',
315
+ 'adapter.patchLineDuplicateInsertDetail': '另一条 insert 来自 {layers};需手工删除其中一条(本插件不会自动删行)',
316
+ 'adapter.patchNotesJoin': ';',
308
317
  'adapter.patchLineSame': 'patch 行 {lineId} 已一致',
309
318
  'adapter.patchLineDiff': 'patch 行 {lineId} 与目标不同',
319
+ 'adapter.patchKeyParseFail': 'patch 行 {ref} 在 {path} 处含会让 DSH 整份文件解析失败的键名:先给该键改成合法名字,再导入',
320
+ 'adapter.patchKeyAmbiguous': 'patch 行 {ref} 在 {path} 处的键名 {key} 会被 DSH 读成数字 / 布尔 / null:给键名加引号(\'{key}\':)后重新导入',
310
321
  'adapter.promptSame': '提示词 {name} 已一致',
311
322
  'adapter.promptDiff': '提示词 {name} 与目标不同',
312
323
  'adapter.promptDiffWithLine': '提示词 {name} 与目标不同(目标位于行 {line})',
@@ -344,6 +355,9 @@ export const zh = {
344
355
  'adapter.pwPatchesUnsupported': 'patchedDependencies 为单行 flow 写法,无法安全剔除缺失条目;若目标机没有对应 patch 文件,pnpm 可能拒绝安装:{line}',
345
356
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml 已写入,但移除了 {count} 条 patchedDependencies 声明(目标机没有对应 patch 文件):{names}',
346
357
  'adapter.patchWritten': 'patch 行 {ref} 已写入,重启后生效',
358
+ 'adapter.patchSecretsKept': '{ref} 已写入,但保留本机原有内容:{paths}(备份里这些字段被脱敏清空,未用空值覆盖本机;如需清空请对该行显式确认“使用备份配置”)',
359
+ 'adapter.patchSecretsCleared': '{ref} 已按备份写入,字段 {paths} 现为空(已显式确认该行使用备份配置)',
360
+ 'adapter.patchLocalReadFailed': 'patch 行 {ref} 未写入:读不出本机现值({reason});无法确认这次写入不会覆盖本机原有内容,已跳过这一行',
347
361
  'adapter.credentialValueMissing': '凭据值未提供(需补录)',
348
362
  'adapter.promptWarningNoWrite': '提示项,无需写入',
349
363
  'adapter.promptMissing': '导入数据缺少提示词 {id}',
@@ -400,6 +414,8 @@ export const zh = {
400
414
  'sync.credentialsNeedPassword': '快照 {id} 含加密凭据载荷,需要解密密码才能读取',
401
415
  'sync.encryptedNeedsPassword': '快照 {id} 已加密,需要解密密码才能读取(自动同步无法解密,请手动同步)',
402
416
  'sync.noPortableSections': '没有可同步的 portable 分区(全部导出失败)',
417
+ 'sync.pushSkipConflicted': '已跳过本轮推送:{sections} 仍待冲突裁决(未上传、未改动基线)',
418
+ 'sync.pushAllConflicted': '没有可推送的分区:{sections} 全部仍待冲突裁决(先裁决,或改用强制推送)',
403
419
  'sync.remoteEmpty': '远端无快照',
404
420
  'sync.sessionDeletionsRecorded': '已记录 {count} 个本机删除的历史对话(墓碑随快照传播,旧快照不会把它们带回来)',
405
421
  'sync.sessionsTombstoned': '已按远端墓碑跳过 {count} 个已删除的历史对话(不复活)',
@@ -481,6 +497,7 @@ export const zh = {
481
497
  'sync.pruneListFailed': '远端快照裁剪失败:无法列出远端快照,{reason}',
482
498
  'sync.pruneDeleteFailed': '远端快照裁剪失败:删除快照 {id} 失败,{reason}',
483
499
  'sync.gcSkipped': '本轮已放弃回收远端孤立文件({code}):本轮不做回收,快照本身不受影响',
500
+ 'sync.latestSkippedEncrypted': '加密快照不生成远端 latest/ 视图(密文无明文镜像):latest/ 保持上一次明文快照的内容,需要明文视图请推一次非加密快照',
484
501
 
485
502
  // ---------- 配置市场(m-market:只读公开仓库目录读取 + 校验) ----------
486
503
  'market.invalidItemId': '非法市场条目 id: {id}(仅允许字母数字开头,字符限 . _ -)',
@@ -553,6 +570,7 @@ export const en: Record<keyof typeof zh, string> = {
553
570
  'export.sectionFailed': 'Section {adapter} export failed: {reason}',
554
571
  'export.credentialsReadFailed': 'Failed to read the credentials file; secrets export skipped: {reason}',
555
572
  'export.vaultRefreshed': 'Credential plaintext did not enter the backup; mirrored to the local vault ({count} file(s), available for restore backfill)',
573
+ 'export.pluginDataSensitiveSkipped': 'Dropped {count} credential file(s) at packaging time (first: {sample}) — third-party plugin data never carries credential plaintext',
556
574
  'export.vaultRefreshSkipped': 'Vault mirror skipped {rel}: {reason}',
557
575
  'export.vaultRefreshFailed': 'Vault mirror refresh failed (export unaffected): {reason}',
558
576
  '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)',
@@ -738,6 +756,7 @@ export const en: Record<keyof typeof zh, string> = {
738
756
  'host.patchUnreadable': 'Cannot read patch layer {file} ({reason}): its patch rows are not exported or synced, and the file is left untouched',
739
757
  'host.patchRefuseClobber': 'Refusing to rewrite patch layer {file}: it cannot be parsed ({reason}), and rewriting would delete every row that could not be read',
740
758
  '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)',
759
+ 'host.patchRefuseUnknownId': 'Refusing to write patch layer {file}: it contains top-level rows {ids} that no layer of the effective patch chain (bundle / profile / home) provides; the host would drop them as not found, so the file is untouched',
741
760
  'host.patchSemanticDrift': 'Structure self-check failed after serializing patch layer {file} ({detail}): the write was refused and the file is untouched',
742
761
  'host.fsPathEscape': 'Path outside home directory: {path}',
743
762
  '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)',
@@ -833,8 +852,17 @@ export const en: Record<keyof typeof zh, string> = {
833
852
  'adapter.pluginInstallFailed': 'Plugin {name} install failed: {msg}. You can install it manually: dsh plugin --profile {profile} add {name} (the rest of the config was imported; fix dependencies and retry from the settings page, or install by hand)',
834
853
  'adapter.pluginUpdateFailed': 'Plugin {name} update failed: {msg}. You can install it manually: dsh plugin --profile {profile} add {name} (the rest of the config was imported; fix dependencies and retry from the settings page, or install by hand)',
835
854
  'adapter.patchLineCreate': 'Write patch row {lineId}',
855
+ 'adapter.patchLineOverride': 'Override the existing entry (write patch row {lineId})',
856
+ 'adapter.patchLineOverrideDetail': 'This id is already provided by {layers}: only a top-level override row is valid; an insert would add a second entry with the same id (saving that plugin config in DSH then reports it as overridden)',
857
+ 'adapter.patchLineDowngraded': '{ids} already provided by another patch layer; written as an override row instead of a second insert',
858
+ 'adapter.patchChainPartial': '{count} layer(s) of the effective patch chain could not be read ({files}); the "does this id already exist" check covers only the readable layers',
859
+ 'adapter.patchLineDuplicateInsert': 'Patch line {lineId} has more than one insert source on this machine: two inserts for the same id make DSH report that plugin config as overridden on every save',
860
+ 'adapter.patchLineDuplicateInsertDetail': 'Another insert comes from {layers}; delete one of them by hand (this plugin never deletes rows on its own)',
861
+ 'adapter.patchNotesJoin': '; ',
836
862
  'adapter.patchLineSame': 'Patch row {lineId} is already identical',
837
863
  'adapter.patchLineDiff': 'Patch row {lineId} differs from the target',
864
+ 'adapter.patchKeyParseFail': 'Patch row {ref} has a key at {path} that makes DSH fail to parse the whole file; rename that key before importing',
865
+ '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
866
  'adapter.promptSame': 'Prompt {name} is already identical',
839
867
  'adapter.promptDiff': 'Prompt {name} differs from the target',
840
868
  'adapter.promptDiffWithLine': 'Prompt {name} differs from the target (target lives at row {line})',
@@ -872,6 +900,9 @@ export const en: Record<keyof typeof zh, string> = {
872
900
  '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
901
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml written, but {count} patchedDependencies entries were removed (the target has no matching patch file): {names}',
874
902
  'adapter.patchWritten': 'Patch row {ref} written; takes effect after restart',
903
+ '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)',
904
+ 'adapter.patchSecretsCleared': '{ref} written from the backup; fields {paths} are now empty (you explicitly confirmed using the backup config for this row)',
905
+ '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
906
  'adapter.credentialValueMissing': 'Credential value not provided (re-entry required)',
876
907
  'adapter.promptWarningNoWrite': 'Informational item; nothing to write',
877
908
  'adapter.promptMissing': 'Import data is missing prompt {id}',
@@ -928,6 +959,8 @@ export const en: Record<keyof typeof zh, string> = {
928
959
  'sync.credentialsNeedPassword': 'Snapshot {id} carries an encrypted credentials payload; a decryption password is required',
929
960
  'sync.encryptedNeedsPassword': 'Snapshot {id} is encrypted; a decryption password is required (auto sync cannot decrypt — sync manually)',
930
961
  'sync.noPortableSections': 'No portable sections to sync (all exports failed)',
962
+ 'sync.pushSkipConflicted': 'Push skipped: {sections} still await conflict resolution (nothing uploaded, baseline untouched)',
963
+ 'sync.pushAllConflicted': 'Nothing to push: every target section ({sections}) still awaits conflict resolution (resolve them first, or force push)',
931
964
  'sync.remoteEmpty': 'No snapshots on the remote',
932
965
  'sync.sessionDeletionsRecorded': 'Recorded {count} locally deleted conversation(s) as tombstones (they travel with snapshots, so older snapshots will not bring them back)',
933
966
  'sync.sessionsTombstoned': 'Skipped {count} conversation(s) deleted on the remote side according to tombstones (no resurrection)',
@@ -1005,6 +1038,7 @@ export const en: Record<keyof typeof zh, string> = {
1005
1038
  'sync.pruneListFailed': 'Remote snapshot pruning failed: could not list remote snapshots, {reason}',
1006
1039
  'sync.pruneDeleteFailed': 'Remote snapshot pruning failed: deleting snapshot {id} failed, {reason}',
1007
1040
  'sync.gcSkipped': 'Skipped reclaiming remote orphan files this round ({code}); snapshots are unaffected',
1041
+ '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
1042
 
1009
1043
  // ---------- config marketplace (m-market: read-only public repo directory read + validation) ----------
1010
1044
  '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;