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
@@ -22,8 +22,12 @@ import { engineMsg } from './messages.ts';
22
22
  import { stringifyJsonSafe } from '../utils/json.ts';
23
23
  import { isPathSafe, normalizePath } from '../utils/paths.ts';
24
24
  import { isENOENT } from '../utils/guards.ts';
25
+ import { findPatchKeyHazards } from '../utils/patch-yaml.ts';
26
+ import { patchKeyHazardMessage } from './patch-key-guard.ts';
25
27
  import { PLUGIN_PATCH_REF_PREFIX, PLUGIN_PROFILE_MANIFEST_REF } from '../core/backup.ts';
26
28
  import { readEffectivePatchLines, resolveWriteLayer, USER_PATCH_FILE } from '../core/patch-layers.ts';
29
+ import { providedByOtherLayers, readPatchChainIndex } from '../core/patch-chain.ts';
30
+ import { applyPatchSecretGuard } from '../core/patch-secret-guard.ts';
27
31
  import { stripMcpEntries } from './mcp.ts';
28
32
  import {
29
33
  parsePnpmPatchedDependencies, restorePnpmMachinePaths, sanitizePnpmWorkspacePatches, stripPnpmMachinePaths,
@@ -31,7 +35,7 @@ import {
31
35
  import type { LocalPluginTarball, PatchLine, PluginEntry, PluginsSection, PnpmPatchFile } from '../schema/types.ts';
32
36
  import type {
33
37
  ApplyResult, ConfigAdapter, ExportOptions, ExportSection, ExportUnit, HostContext,
34
- ImportContext, PlanItem, PluginAreaRef, SectionPreview, ValidationResult,
38
+ ImportContext, PlanItem, PluginAreaRef, SectionPreview, SensitiveHit, ValidationResult,
35
39
  } from '../core/types.ts';
36
40
  import { BUILTIN_PLUGIN_DATA_SOURCES, areasForSection } from '../core/plugin-data-registry.ts';
37
41
  import type { PluginDataSource } from '../core/plugin-data-registry.ts';
@@ -279,6 +283,33 @@ async function measureLocalSources(plugins: PluginEntry[], ctx: HostContext): Pr
279
283
  }
280
284
  return sizes;
281
285
  }
286
+ /**
287
+ * issue #136 A:读目标机**当前生效**的 patch 行原文(写回守卫的「本机现值」)。
288
+ *
289
+ * 口径与 analyzeImport 判定 Skip/Conflict 时逐字相同(readEffectivePatchLines + lineId 匹配),
290
+ * 这样「计划阶段看到的现值」与「写回阶段比对的现值」不会分叉。
291
+ *
292
+ * 读失败**不得**降级成「没有本机行」:那等于跳过守卫、静默覆盖本机明文(#136 的复现条件),
293
+ * 而且连一条告警都不会有。失败必须显式上抛给 applyItem,由它对这一行返回非致命失败。
294
+ */
295
+ async function readLocalPatchRaw(
296
+ ctx: ImportContext,
297
+ lineId: string,
298
+ ): Promise<{ ok: true; raw: unknown } | { ok: false; reason: string }> {
299
+ try {
300
+ const { lines, failures } = await readEffectivePatchLines(ctx.target.patchFile, ctx.target.profile);
301
+ // 有层读不出来 → 无法证明「本机这一行现在是什么 / 到底有没有」。
302
+ // readEffectivePatchLines 把层读失败收进 failures(不抛错),此前的实现只 catch 抛错、
303
+ // 于是「有层读不出来」被当成「本机没有这一行」放行 —— 守卫被绕过且零告警(#136 的复现条件)。
304
+ // 这里宁可跳过这一行并说明原因,也不按「无本机值」写入。
305
+ if (failures.length > 0) {
306
+ return { ok: false, reason: failures.map((f) => `${f.file}: ${f.reason}`).join('; ') };
307
+ }
308
+ return { ok: true, raw: lines.find((l) => l.lineId === lineId)?.raw };
309
+ } catch (err) {
310
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
311
+ }
312
+ }
282
313
 
283
314
  /**
284
315
  * 由分区载荷派生单元清单(纯函数、零 I/O)。
@@ -371,6 +402,46 @@ export class PluginsAdapter implements ConfigAdapter<PluginsSection> {
371
402
  async export(ctx: HostContext, options: ExportOptions): Promise<ExportSection<PluginsSection>> {
372
403
  return this.collect(ctx, options, true);
373
404
  }
405
+ /**
406
+ * issue #136 C:脱敏**归属标注** —— 把 SecretScanner 的命中路径归属回具体 patch 行。
407
+ *
408
+ * 为什么必须做:导出侧把命中字段名/值形状的字符串叶子替换成空串(占位符),语义是「需补录」。
409
+ * 目标机只看到空串,无法区分「被剥空」与「用户主动写空」——于是合并/导入落地时照抄空串,
410
+ * 静默抹掉本机同一行里用户手写的明文(行是整行写回的,行内没有粒度)。
411
+ *
412
+ * 归属规则:命中路径 `patch[i].<内部路径>` → 第 i 行的 `redactedPaths`(行内相对,原样保留
413
+ * 扫描器语法,如 `raw.mcp.args.token`);未命中的行不写该字段(缺省 = 未知,写回侧走保守分支)。
414
+ *
415
+ * 纯函数:不改入参;命中不落在 patch 行上(plugins / pnpmWorkspace / localTarballs 等)→ 原样返回。
416
+ */
417
+ annotateRedactions(sanitized: unknown, hits: SensitiveHit[]): unknown {
418
+ if (hits.length === 0) return sanitized;
419
+ if (sanitized === null || typeof sanitized !== 'object') return sanitized;
420
+ const section = sanitized as PluginsSection;
421
+ if (!Array.isArray(section.patch) || section.patch.length === 0) return sanitized;
422
+ const byLine = new Map<number, Set<string>>();
423
+ for (const hit of hits) {
424
+ const m = /^patch\[(\d+)\]\.(.+)$/.exec(hit.path);
425
+ if (m === null) continue;
426
+ const index = Number(m[1]);
427
+ if (!Number.isInteger(index) || index < 0 || index >= section.patch.length) continue;
428
+ let paths = byLine.get(index);
429
+ if (paths === undefined) {
430
+ paths = new Set<string>();
431
+ byLine.set(index, paths);
432
+ }
433
+ const rel = m[2];
434
+ if (rel === undefined || rel === '') continue;
435
+ paths.add(rel);
436
+ }
437
+ if (byLine.size === 0) return sanitized;
438
+ const patch = section.patch.map((line, i) => {
439
+ const paths = byLine.get(i);
440
+ if (paths === undefined) return line;
441
+ return { ...line, redactedPaths: [...paths].sort() };
442
+ });
443
+ return { ...section, patch };
444
+ }
374
445
 
375
446
  /**
376
447
  * 只读预览(`/export-preview` 用):与 `export()` **同口径**,但不做任何本地源打包。
@@ -869,7 +940,24 @@ export class PluginsAdapter implements ConfigAdapter<PluginsSection> {
869
940
  // 用户 patch 行:lineId 唯一键;存在且同 → Skip;存在不同 → Conflict;不存在 → Create。
870
941
  // mcp-client 行与 systemPrompt/planMode 行由 mcp/prompts adapter 管理,此处跳过(避免重复写入覆盖)。
871
942
  // issue #71:目标行同样跨两层(否则 profile 层已有的行会被误判成 Create → 导入后出现重复行)
872
- const targetLines = (await readEffectivePatchLines(ctx.target.patchFile, ctx.target.profile)).lines;
943
+ const targetLines = (await readEffectivePatchLines(ctx.target.patchFile, ctx.target.profile)).lines
944
+ // issue #144:**还有第三层**——bundle 层。它由插件包自己的 `dsh.bundle.patch` 提供,
945
+ // 不在两个 patch 文件里;只看这两层会把 bundle 已有的 id 判成「本机没有」而写出第二条
946
+ // insert,宿主 compose 后插件保存配置必然报 overridden by a home patch or command-line overlay。
947
+ const chainRead = await readPatchChainIndex(ctx.target.patchFile);
948
+ const chain = chainRead.index;
949
+ // 判据不完整(有层读不出来)必须可见:否则「退回两层」等于把「未知」渲染成「确知没有」,
950
+ // 用户看到一份 Create 计划、写出重复 insert,日志里零线索(issue #144 的根因就是这样被藏住的)。
951
+ if (chainRead.failures.length > 0) {
952
+ items.push({
953
+ id: 'patch-chain:partial', kind: 'Warning', adapter: 'plugins', severity: 'warning',
954
+ description: msg('adapter.patchChainPartial', {
955
+ count: String(chainRead.failures.length),
956
+ files: chainRead.failures.map((f) => f.file).join(', '),
957
+ }),
958
+ detail: chainRead.failures.map((f) => `${f.file}: ${f.reason}`).join('; '),
959
+ });
960
+ }
873
961
  for (const pl of data.patch) {
874
962
  if (isManagedElsewhere(pl.raw)) continue;
875
963
  const id = `patch:${pl.lineId}`;
@@ -877,14 +965,54 @@ export class PluginsAdapter implements ConfigAdapter<PluginsSection> {
877
965
  // 层身份随计划项走:applyItem 按 pl.file 写回,导入前快照按 target.file 记原行,
878
966
  // 两者必须是同一层,否则回滚会把另一层改坏(issue #71)。
879
967
  const layer = resolveWriteLayer(pl.file, ctx.target.profile);
880
- if (!tl) {
968
+ // issue #144 存量:本机这一层和别的层**都以 insert 提供**同一个 id(0.9.0 写坏的机器)。
969
+ // 内容相同也走不了「无变化」—— 两份新增本身就是要修的东西;这里只提示,不自动删行。
970
+ const entry = chain?.get(pl.lineId);
971
+ const peerInserts = entry === undefined ? [] : entry.insertLayers.filter((l) => l !== layer);
972
+ if (tl && entry !== undefined && entry.insertLayers.includes(layer) && peerInserts.length > 0) {
881
973
  items.push({
882
- id, kind: 'Create', adapter: 'plugins',
883
- description: msg('adapter.patchLineCreate', { lineId: pl.lineId }), severity: 'info',
974
+ id, kind: 'Warning', adapter: 'plugins', severity: 'warning',
975
+ description: msg('adapter.patchLineDuplicateInsert', { lineId: pl.lineId }),
976
+ detail: msg('adapter.patchLineDuplicateInsertDetail', { layers: peerInserts.join(', ') }),
884
977
  target: { adapter: 'plugins', ref: pl.lineId, file: layer },
885
978
  });
886
- } else if (isDeepStrictEqual(tl.raw, pl.raw)) {
979
+ continue;
980
+ }
981
+ // 与目标一致 ⇒ 一个字节都不会写,键名风险不归我们管(见下方守卫);先判 Skip 以免误报。
982
+ if (tl && isDeepStrictEqual(tl.raw, pl.raw)) {
887
983
  items.push({ id, kind: 'Skip', adapter: 'plugins', description: msg('adapter.patchLineSame', { lineId: pl.lineId }), severity: 'info' });
984
+ continue;
985
+ }
986
+ // issue #137:写侧的 forceQuotes 只保**值**,键名仍会被 4.x 改判(空键更会让整份文件解析失败)。
987
+ // 命中即降级成本项「预判阻断」—— 本项不写、不触发整笔回滚,其余行照常导入。
988
+ const hazard = findPatchKeyHazards(pl.raw)[0];
989
+ if (hazard) {
990
+ items.push({
991
+ id, kind: 'Error', adapter: 'plugins',
992
+ description: patchKeyHazardMessage(msg, pl.lineId, hazard), severity: 'error',
993
+ });
994
+ continue;
995
+ }
996
+ if (!tl) {
997
+ // issue #144:本机两个 patch 层没有这一行,但**别的层**(bundle 层最常见)已经提供该 id
998
+ // ⇒ 这不是「新建」,而是对既有条目的覆盖。写成 insert 就是第二条新增;顶层覆盖行才是
999
+ // 宿主认可的形状(ConfigEditor 自己也是这么写的)。
1000
+ const elsewhere = chain === null ? undefined : providedByOtherLayers(chain, layer).get(pl.lineId)
1001
+ if (elsewhere !== undefined) {
1002
+ items.push({
1003
+ id, kind: 'Update', adapter: 'plugins',
1004
+ description: msg('adapter.patchLineOverride', { lineId: pl.lineId }),
1005
+ detail: msg('adapter.patchLineOverrideDetail', { layers: elsewhere.layers.join(', ') }),
1006
+ severity: 'info',
1007
+ target: { adapter: 'plugins', ref: pl.lineId, file: layer },
1008
+ });
1009
+ } else {
1010
+ items.push({
1011
+ id, kind: 'Create', adapter: 'plugins',
1012
+ description: msg('adapter.patchLineCreate', { lineId: pl.lineId }), severity: 'info',
1013
+ target: { adapter: 'plugins', ref: pl.lineId, file: layer },
1014
+ });
1015
+ }
888
1016
  } else {
889
1017
  items.push({
890
1018
  id, kind: 'Conflict', adapter: 'plugins',
@@ -1079,11 +1207,56 @@ export class PluginsAdapter implements ConfigAdapter<PluginsSection> {
1079
1207
  const data = ctx.sections.get('plugins') as PluginsSection | undefined;
1080
1208
  const pl = data?.patch.find((p) => p.lineId === ref);
1081
1209
  if (!pl) return { ok: false, message: msg('adapter.patchMissing', { ref }) };
1210
+ // issue #136 A:写回层守卫 —— 「被脱敏剥空」的叶子不得覆盖本机非空明文。
1211
+ //
1212
+ // 为什么在写回层做(而不是只靠导出侧标注):协同场景里对方的载荷来自更早版本、第三方工具或
1213
+ // 手工改过,`redactedPaths` 可能缺失;写回是最后一道能同时看见「本机现值」与「将被写下的值」
1214
+ // 的地方,也唯一能区分「被剥空」与「用户主动写空」(显式逐行 useImported 才放行清空)。
1215
+ // 守卫只在 Update/Conflict 上生效;Create 没有本机行可保(新行原样写入)。
1216
+ // 本机现值读不出来 → 无法证明这次写入不会覆盖明文,这一行**拒绝写**。
1217
+ // 非致命(warning):一行读不出来不该拖垮其余分区,也不该把整笔导入回滚。
1218
+ const localRead = item.kind === 'Create'
1219
+ ? ({ ok: true as const, raw: undefined })
1220
+ : await readLocalPatchRaw(ctx, ref);
1221
+ if (!localRead.ok) {
1222
+ return {
1223
+ ok: false,
1224
+ warning: true,
1225
+ message: msg('adapter.patchLocalReadFailed', { ref: item.id, reason: localRead.reason }),
1226
+ };
1227
+ }
1228
+ const guard = applyPatchSecretGuard({
1229
+ importedRaw: pl.raw,
1230
+ localRaw: localRead.raw,
1231
+ redactedPaths: pl.redactedPaths,
1232
+ // 显式逐行确认 = 用户对本行选了 useImported(全局 replace 策略不算确认)
1233
+ // #136 A:只有**逐项**确认才算「我要这一行按导入值写」。判定必须是**白名单**:
1234
+ // 分区级裁决(decidedBy: 'section',由合并落地 planMergeApply 注入)只决定分区是否应用,
1235
+ // 不构成对本行的确认;来源缺省(未来新增的注入路径忘了标注)一律按「未确认」处理 ——
1236
+ // 默认放行等于给同类漏洞留后门;翻转成默认拒绝后,忘标注只会少清空、不会误清空。
1237
+ confirmed: item.conflict?.resolution === 'useImported' && item.conflict?.decidedBy === 'item',
1238
+ });
1082
1239
  // 层身份按**语义**映射到目标机:来源是别的 profile 层时不能照抄名字(目标机未必有那个
1083
1240
  // profile,宿主门面会拒绝),一律落到目标机当前 profile 层(与计划项 target.file 同口径)。
1084
- await ctx.target.patchFile.applyPatchChanges(resolveWriteLayer(pl.file, ctx.target.profile), [
1085
- { lineId: ref, raw: pl.raw, action: item.kind === 'Create' ? 'insert' : 'update' },
1241
+ const outcome = await ctx.target.patchFile.applyPatchChanges(resolveWriteLayer(pl.file, ctx.target.profile), [
1242
+ { lineId: ref, raw: guard.raw, action: item.kind === 'Create' ? 'insert' : 'update' },
1086
1243
  ]);
1244
+ // 一次写入可能同时命中多件事(被降级 + 保留/清空了密钥字段),**必须并列报**:
1245
+ // 早退会让 #136 A 的安全告警静默消失,用户以为导入已经覆盖了密钥值。
1246
+ const notes: string[] = [];
1247
+ if (outcome.downgraded.length > 0) {
1248
+ // issue #144 兜底:门面发现该 id 已被别的层提供、把 insert 降级成覆盖行 → 说明实际写了哪种形状
1249
+ notes.push(msg('adapter.patchLineDowngraded', { ids: outcome.downgraded.join(', ') }));
1250
+ }
1251
+ // 告警只报行 id 与字段路径,绝不带值(值本身就是密钥)
1252
+ // 报告面用**计划项 id**(`patch:<lineId>`)而不是裸 lineId:报告与计划项要能逐条对上
1253
+ if (guard.kept.length > 0) {
1254
+ notes.push(msg('adapter.patchSecretsKept', { ref: item.id, paths: guard.kept.join(', ') }));
1255
+ }
1256
+ if (guard.cleared.length > 0) {
1257
+ notes.push(msg('adapter.patchSecretsCleared', { ref: item.id, paths: guard.cleared.join(', ') }));
1258
+ }
1259
+ if (notes.length > 0) return { ok: true, warning: true, needsRestart: true, message: notes.join(msg('adapter.patchNotesJoin')) };
1087
1260
  return { ok: true, needsRestart: true, message: msg('adapter.patchWritten', { ref }) };
1088
1261
  }
1089
1262
 
@@ -1119,6 +1292,23 @@ export class PluginsAdapter implements ConfigAdapter<PluginsSection> {
1119
1292
  const pl = raw as unknown;
1120
1293
  if (pl === null || typeof pl !== 'object') {
1121
1294
  issues.push({ path: `patch[${i}]`, message: msg('adapter.validate.recordObject', { subject: 'patch line' }), severity: 'error' });
1295
+ continue;
1296
+ }
1297
+ // issue #136 C:脱敏归属路径(可选;存在时必须是字符串数组、元素非空,写回守卫按它精确比对)。
1298
+ // **空数组合法**:语义就是「本行没有剥空位置」,守卫按缺省(保守分支)处理。
1299
+ // 不把空数组当形状错误 —— 第三方 exporter 写出 `[]` 时拦下整包导入,代价远大于收益,
1300
+ // 而且凝死一个「字段在但内容空」与「字段缺省」不等价的契约,纯属自找兼容债。
1301
+ const redactedPaths = (pl as { redactedPaths?: unknown }).redactedPaths;
1302
+ if (redactedPaths !== undefined) {
1303
+ if (!Array.isArray(redactedPaths)) {
1304
+ issues.push({ path: `patch[${i}].redactedPaths`, message: msg('adapter.validate.array', { subject: 'patch[].redactedPaths' }), severity: 'error' });
1305
+ } else {
1306
+ for (const [j, p] of redactedPaths.entries()) {
1307
+ if (typeof p !== 'string' || p === '') {
1308
+ issues.push({ path: `patch[${i}].redactedPaths[${j}]`, message: msg('adapter.validate.string', { subject: 'patch[].redactedPaths[]' }), severity: 'error' });
1309
+ }
1310
+ }
1311
+ }
1122
1312
  }
1123
1313
  }
1124
1314
  }
@@ -235,10 +235,16 @@ export class PromptsAdapter implements ConfigAdapter<PromptsExportSection> {
235
235
  const raw = buildPromptLine(ref, prompt);
236
236
  // issue #71:备份里记了来源层就落「同语义层」(来源 profile 层 → 目标机当前 profile 层,
237
237
  // 跨机器照抄 profile 名会被宿主门面拒绝);旧备份包无该字段 → 落 home 层(与改造前一致)
238
- await ctx.target.patchFile.applyPatchChanges(resolveWriteLayer(prompt.sourceFile, ctx.target.profile), [
238
+ const created = await ctx.target.patchFile.applyPatchChanges(resolveWriteLayer(prompt.sourceFile, ctx.target.profile), [
239
239
  { lineId: ref, raw, action: 'insert' },
240
240
  ]);
241
- return { ok: true, needsRestart: true, message: msg('adapter.promptCreated', { name: prompt.name, ref }) };
241
+ // issue #144:降级成覆盖行时必须报出来(落盘形状变了,不能显示成「新增成功」)
242
+ const createdDowngraded = created.downgraded.length > 0;
243
+ return {
244
+ ok: true, warning: createdDowngraded, needsRestart: true,
245
+ message: msg('adapter.promptCreated', { name: prompt.name, ref })
246
+ + (createdDowngraded ? ' ' + msg('adapter.patchLineDowngraded', { ids: created.downgraded.join(', ') }) : ''),
247
+ };
242
248
  }
243
249
  // Update / Conflict(useImported):合并进目标行 config
244
250
  // issue #71:先定位原行所在层(两层都没有 → home 层),再读该层的原行合并 —— 绝不把
@@ -248,10 +254,15 @@ export class PromptsAdapter implements ConfigAdapter<PromptsExportSection> {
248
254
  const line = lines.find((l) => l.lineId === ref);
249
255
  if (!line) return { ok: false, message: msg('adapter.patchLineMissing', { ref }) };
250
256
  const newRaw = mergePromptIntoLine(line.raw, prompt);
251
- await ctx.target.patchFile.applyPatchChanges(file, [
257
+ const written = await ctx.target.patchFile.applyPatchChanges(file, [
252
258
  { lineId: ref, raw: newRaw, action: 'update' },
253
259
  ]);
254
- return { ok: true, needsRestart: true, message: msg('adapter.promptWritten', { name: prompt.name, ref }) };
260
+ const writtenDowngraded = written.downgraded.length > 0;
261
+ return {
262
+ ok: true, warning: writtenDowngraded, needsRestart: true,
263
+ message: msg('adapter.promptWritten', { name: prompt.name, ref })
264
+ + (writtenDowngraded ? ' ' + msg('adapter.patchLineDowngraded', { ids: written.downgraded.join(', ') }) : ''),
265
+ };
255
266
  }
256
267
 
257
268
  async validate(data: PromptsExportSection, msg: MsgFunc = zhMsg): Promise<ValidationResult> {
@@ -7,6 +7,7 @@ import { createLogger, type Logger } from '../utils/logger.ts';
7
7
  import { sha256Hex } from '../utils/hashing.ts';
8
8
  import { zhMsg } from '../core/messages.ts';
9
9
  import { USER_PATCH_FILE } from '../core/patch-layers.ts';
10
+ import type { PatchChainRead } from '../core/patch-chain.ts';
10
11
  import type {
11
12
  CredentialsFacade, FileSystemFacade, HostContext, ImportContext, NamespaceInfo,
12
13
  PatchFileFacade, PluginInfo, PluginsFacade, SettingsFacade, Snapshot,
@@ -221,15 +222,28 @@ export class MemPatch implements PatchFileFacade {
221
222
  return bucket === undefined ? [] : [...bucket.values()];
222
223
  }
223
224
 
225
+ /** issue #144:生效 patch 链(bundle 层 + profile 层 + home 层)。默认空链 = 判据不加强。 */
226
+ chain: PatchChainRead | null = null;
227
+ /** 记录每次写入的动作,供「已存在的 id 必须走 update」这类断言使用。 */
228
+ actions: { file: string; lineId: string; action: 'insert' | 'update' | 'remove' }[] = [];
229
+ /** 注入「门面把 insert 降级成覆盖行」的结果(issue #144 兜底路径),默认不降级。 */
230
+ downgrade: string[] = [];
231
+
232
+ async readPatchChain(): Promise<PatchChainRead> {
233
+ return this.chain ?? { sources: [], failures: [] };
234
+ }
235
+
224
236
  async applyPatchChanges(
225
237
  file: string,
226
238
  changes: { lineId: string; raw: unknown; action: 'insert' | 'update' | 'remove' }[],
227
- ): Promise<void> {
239
+ ): Promise<{ downgraded: string[] }> {
228
240
  const bucket = this.bucket(file);
229
241
  for (const c of changes) {
242
+ this.actions.push({ file, lineId: c.lineId, action: c.action });
230
243
  if (c.action === 'remove') bucket.delete(c.lineId);
231
244
  else bucket.set(c.lineId, { lineId: c.lineId, raw: c.raw });
232
245
  }
246
+ return { downgraded: this.downgrade };
233
247
  }
234
248
  }
235
249
 
@@ -15,11 +15,12 @@ import path from 'node:path'
15
15
 
16
16
  import {
17
17
  checkWriteGates, cleanupDisk, collectVerifyResults, diskUsageDirsOf, exportOfflineBackup, isProcessAlive,
18
- planSnapshotRestore, readBackups, readDiskUsage, readLockState, readProfiles, readRescueStatus,
18
+ locksDirFromControlRoots, planSnapshotRestore, readBackups, readDiskUsage, readLockState, readProfiles, readRescueStatus,
19
19
  readRunningInstances, readSnapshots, recoverStaleEnvironmentLock, repairSessionLogInline, repairSessions,
20
20
  sessionRepairRowMessage, sessionVerifyNoteOf, stopProfile, unlockEncryptedBackup, type SessionLogRepairRow,
21
21
  } from './actions.ts'
22
22
  import type { SessionVerifyResult } from '../utils/session-verify.ts'
23
+ import { EnvironmentLockManager } from '../utils/env-lock.ts'
23
24
  import { parseZip } from '../utils/zip.ts'
24
25
  import { MANIFEST_FILE } from '../schema/manifest.ts'
25
26
 
@@ -574,3 +575,75 @@ test('C1 文案:不可修复项的回执指向字节级离线出口(不再
574
575
  assert.equal(/sessions repair\s+--apply/.test(message), false, message)
575
576
  })
576
577
  })
578
+ /* ---------------- 审计 P11-4:环境锁目录必须由控制面根派生(就地修复此前漏传 locksDir) ---------------- */
579
+
580
+ test('P11-4 写门:locksDir 由控制面根派生(第一个真实带锁的候选根优先)', async () => {
581
+ await withTmp(async (tmp) => {
582
+ const first = path.join(tmp, 'a')
583
+ const second = path.join(tmp, 'b')
584
+ await fs.mkdir(path.join(second, 'locks'), { recursive: true })
585
+ await fs.writeFile(path.join(second, 'locks', 'environment.lock'), '{}')
586
+ assert.equal(locksDirFromControlRoots([first, second]), path.join(second, 'locks'), '跳过没锁的候选根,用真正持有锁的那个')
587
+ assert.equal(locksDirFromControlRoots([first]), path.join(first, 'locks'), '都没有锁就退回首个候选(读不到 = 无锁,判据仍归 readLockState)')
588
+ assert.equal(locksDirFromControlRoots([]), undefined, '空候选列表没有可派生的目录')
589
+ })
590
+ })
591
+
592
+ test('P11-10 写门:不传 locksDir 也不再跳过环境锁检查(派生在门内完成,5 个调用点不再各拼参数)', async () => {
593
+ await withTmp(async (tmp) => {
594
+ const dataDir = path.join(tmp, 'dsh-config-manager')
595
+ await fs.mkdir(dataDir, { recursive: true })
596
+ const locksDir = path.join(dataDir, 'locks')
597
+ const mgr = new EnvironmentLockManager({ locksDir, heartbeatIntervalMs: 60_000 })
598
+ const acquired = await mgr.acquire({ op: 'test-hold', target: 'p11-10' })
599
+ assert.equal(acquired.state, 'ACQUIRED')
600
+ try {
601
+ // 只有 controlRoots,没有 locksDir —— 改前这就是「静默不查锁」的形态
602
+ const derived = await checkWriteGates([dataDir], { needsDshStopped: false })
603
+ assert.equal(derived.ok, false, '锁被持有时必须拒绝,不能因少传参数放行')
604
+ assert.equal(derived.ok === false ? derived.code : null, 'stale-lock')
605
+ } finally {
606
+ if (acquired.token !== null) await mgr.release(acquired.token)
607
+ await mgr.stopHeartbeatAndDrain()
608
+ }
609
+ })
610
+ })
611
+
612
+ test('P11-4 写门:真实持有的环境锁 → 就地修复必须拒绝(改前不传 locksDir,锁在也照样改写字节)', async () => {
613
+ await withTmp(async (tmp) => {
614
+ const home = path.join(tmp, 'home')
615
+ const dataDir = path.join(tmp, 'dsh-config-manager')
616
+ await fs.mkdir(home, { recursive: true })
617
+ await fs.mkdir(dataDir, { recursive: true })
618
+ const locksDir = path.join(dataDir, 'locks')
619
+ // 真实持锁(不是手写 ownership 文件):持有者是本进程,状态应为 LOCKED
620
+ const mgr = new EnvironmentLockManager({ locksDir, heartbeatIntervalMs: 60_000 })
621
+ const acquired = await mgr.acquire({ op: 'test-hold', target: 'inline-repair' })
622
+ assert.equal(acquired.state, 'ACQUIRED')
623
+ try {
624
+ const held = await checkWriteGates([dataDir], { needsDshStopped: true, locksDir })
625
+ assert.equal(held.ok, false)
626
+ assert.equal(held.ok === false ? held.code : null, 'stale-lock')
627
+
628
+ // 不显式传 locksDir:必须靠 controlRoots 派生出来,否则锁在也放行(P11-4 的形态)
629
+ const refused = await repairSessionLogInline(
630
+ { home, dataDir, unitIds: ['proj/session-x'], apply: true },
631
+ [dataDir],
632
+ )
633
+ assert.equal(refused.ok, false, '环境锁被持有仍放行 = P11-4 复现')
634
+ assert.match(refused.error ?? '', /环境锁/)
635
+ assert.equal(refused.rows.length, 0, '被门拒绝时不得逐条执行')
636
+
637
+ // 显式传同一个目录:判据相同,只换入口
638
+ const explicit = await repairSessionLogInline(
639
+ { home, dataDir, unitIds: ['proj/session-x'], apply: true, locksDir },
640
+ [dataDir],
641
+ )
642
+ assert.equal(explicit.ok, false)
643
+ assert.match(explicit.error ?? '', /环境锁/)
644
+ } finally {
645
+ if (acquired.token !== null) await mgr.release(acquired.token)
646
+ await mgr.stopHeartbeatAndDrain()
647
+ }
648
+ })
649
+ })