dsh-config-manager 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/lib/adapters/mcp.js +42 -13
  2. package/lib/adapters/messages.d.ts +1 -0
  3. package/lib/adapters/messages.js +2 -0
  4. package/lib/adapters/patch-key-guard.d.ts +23 -0
  5. package/lib/adapters/patch-key-guard.js +13 -0
  6. package/lib/adapters/plugin-data.d.ts +19 -5
  7. package/lib/adapters/plugin-data.js +76 -22
  8. package/lib/adapters/plugins.d.ts +14 -1
  9. package/lib/adapters/plugins.js +147 -4
  10. package/lib/cli/actions.d.ts +7 -105
  11. package/lib/cli/actions.js +16 -172
  12. package/lib/cli/control-state.d.ts +54 -0
  13. package/lib/cli/control-state.js +107 -0
  14. package/lib/cli/index.js +14 -0
  15. package/lib/cli/write-gates.d.ts +61 -0
  16. package/lib/cli/write-gates.js +110 -0
  17. package/lib/client.d.ts +122 -50
  18. package/lib/client.js +12676 -12091
  19. package/lib/core/backup.d.ts +0 -4
  20. package/lib/core/backup.js +21 -4
  21. package/lib/core/boot-rescue.d.ts +1 -1
  22. package/lib/core/boot-rescue.js +12 -1
  23. package/lib/core/boot-safety.js +37 -2
  24. package/lib/core/conflict-decisions.js +2 -1
  25. package/lib/core/exporter.js +22 -1
  26. package/lib/core/journal.d.ts +54 -4
  27. package/lib/core/journal.js +158 -35
  28. package/lib/core/local-plugin-host.d.ts +29 -0
  29. package/lib/core/local-plugin-host.js +55 -48
  30. package/lib/core/messages.d.ts +7 -0
  31. package/lib/core/messages.js +14 -0
  32. package/lib/core/migration-history.js +16 -9
  33. package/lib/core/model-tools.d.ts +2 -2
  34. package/lib/core/model-tools.js +14 -2
  35. package/lib/core/patch-secret-guard.d.ts +49 -0
  36. package/lib/core/patch-secret-guard.js +164 -0
  37. package/lib/core/reconcile.d.ts +8 -0
  38. package/lib/core/reconcile.js +18 -3
  39. package/lib/core/reinstall.d.ts +2 -0
  40. package/lib/core/reinstall.js +6 -2
  41. package/lib/core/restore.js +31 -6
  42. package/lib/core/section-sanitize.d.ts +32 -0
  43. package/lib/core/section-sanitize.js +13 -0
  44. package/lib/core/snapshot-diff.d.ts +30 -0
  45. package/lib/core/snapshot-diff.js +56 -20
  46. package/lib/core/startup-barrier.js +8 -2
  47. package/lib/core/types.d.ts +22 -0
  48. package/lib/core/update-check.js +51 -2
  49. package/lib/foreign/kernel.js +9 -2
  50. package/lib/foreign/read-claude-plugins.js +29 -11
  51. package/lib/foreign/read-dsh.js +31 -2
  52. package/lib/foreign/read-trae.d.ts +11 -0
  53. package/lib/foreign/read-trae.js +124 -4
  54. package/lib/foreign/session-ir.js +50 -9
  55. package/lib/foreign/session-read.d.ts +8 -0
  56. package/lib/foreign/session-read.js +26 -0
  57. package/lib/foreign/session-source.d.ts +12 -4
  58. package/lib/foreign/session-source.js +5 -3
  59. package/lib/foreign/trae-sqlcipher.d.ts +127 -0
  60. package/lib/foreign/trae-sqlcipher.js +519 -0
  61. package/lib/foreign/trae.js +3 -1
  62. package/lib/foreign/truth-table.js +3 -2
  63. package/lib/foreign/types.d.ts +9 -1
  64. package/lib/index.d.ts +1 -1
  65. package/lib/index.js +1 -1
  66. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  67. package/lib/profiles/dsh-profile-io.js +27 -0
  68. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  69. package/lib/profiles/dsh-profile-manager.js +45 -4
  70. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  71. package/lib/profiles/dsh-profile-runtime.js +16 -3
  72. package/lib/profiles/process-control.d.ts +18 -1
  73. package/lib/profiles/process-control.js +25 -1
  74. package/lib/routes/profiles.js +2 -1
  75. package/lib/routes/sync.js +13 -1
  76. package/lib/schema/types.d.ts +11 -0
  77. package/lib/security/redaction.js +22 -6
  78. package/lib/sync/autosync-repeat.d.ts +27 -0
  79. package/lib/sync/autosync-repeat.js +23 -0
  80. package/lib/sync/autosync-scheduler.d.ts +34 -1
  81. package/lib/sync/autosync-scheduler.js +151 -43
  82. package/lib/sync/baseline-heal.js +7 -0
  83. package/lib/sync/baseline-record.d.ts +67 -0
  84. package/lib/sync/baseline-record.js +74 -0
  85. package/lib/sync/blob-store.js +13 -0
  86. package/lib/sync/content-diff.d.ts +39 -0
  87. package/lib/sync/content-diff.js +46 -0
  88. package/lib/sync/git/git-transport.d.ts +32 -1
  89. package/lib/sync/git/git-transport.js +146 -26
  90. package/lib/sync/github-auth.d.ts +17 -1
  91. package/lib/sync/github-auth.js +37 -1
  92. package/lib/sync/merge-apply-plan.d.ts +38 -0
  93. package/lib/sync/merge-apply-plan.js +76 -0
  94. package/lib/sync/messages.d.ts +1 -0
  95. package/lib/sync/messages.js +2 -0
  96. package/lib/sync/pending-merge.d.ts +34 -0
  97. package/lib/sync/pending-merge.js +53 -0
  98. package/lib/sync/s3/s3-transport.d.ts +14 -2
  99. package/lib/sync/s3/s3-transport.js +72 -48
  100. package/lib/sync/sync-engine.d.ts +23 -40
  101. package/lib/sync/sync-engine.js +115 -132
  102. package/lib/sync/sync-history.d.ts +7 -0
  103. package/lib/sync/sync-state.d.ts +28 -0
  104. package/lib/sync/sync-state.js +20 -0
  105. package/lib/sync/transport.d.ts +12 -3
  106. package/lib/sync/transport.js +13 -4
  107. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  108. package/lib/sync/webdav/webdav-transport.js +81 -40
  109. package/lib/ui/commands.js +5 -11
  110. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  111. package/lib/ui/dsh-profiles-view.js +9 -5
  112. package/lib/ui/foreign-view.d.ts +19 -0
  113. package/lib/ui/foreign-view.js +24 -0
  114. package/lib/ui/i18n.d.ts +7 -1
  115. package/lib/ui/i18n.js +17 -2
  116. package/lib/ui/menu-placement.js +1 -1
  117. package/lib/ui/migration-consult-view.d.ts +11 -0
  118. package/lib/ui/migration-consult-view.js +15 -0
  119. package/lib/ui/overview-view.d.ts +7 -0
  120. package/lib/ui/overview-view.js +3 -0
  121. package/lib/ui/report.d.ts +9 -0
  122. package/lib/ui/report.js +17 -4
  123. package/lib/ui/selection-model.d.ts +8 -0
  124. package/lib/ui/selection-model.js +16 -0
  125. package/lib/utils/patch-yaml.d.ts +39 -1
  126. package/lib/utils/patch-yaml.js +82 -2
  127. package/lib/utils/paths.d.ts +13 -0
  128. package/lib/utils/paths.js +35 -0
  129. package/lib/utils/workdir-lock.js +18 -3
  130. package/package.json +2 -1
  131. package/src/adapters/mcp.test.ts +29 -0
  132. package/src/adapters/mcp.ts +43 -12
  133. package/src/adapters/messages.ts +2 -0
  134. package/src/adapters/patch-key-guard.ts +29 -0
  135. package/src/adapters/plugin-data.test.ts +126 -0
  136. package/src/adapters/plugin-data.ts +97 -26
  137. package/src/adapters/plugins.test.ts +288 -0
  138. package/src/adapters/plugins.ts +141 -4
  139. package/src/cli/actions.test.ts +74 -1
  140. package/src/cli/actions.ts +27 -246
  141. package/src/cli/control-state.ts +143 -0
  142. package/src/cli/index.ts +18 -0
  143. package/src/cli/web/web.test.ts +27 -0
  144. package/src/cli/write-gates.ts +149 -0
  145. package/src/client/about/AboutPanel.tsx +7 -6
  146. package/src/client/about/release-notes-view.test.ts +17 -0
  147. package/src/client/about/release-notes-view.ts +49 -24
  148. package/src/client/chat/ChatEntryView.tsx +2 -2
  149. package/src/client/chat/rollback-entry-view.ts +6 -1
  150. package/src/client/common/CommandPalette.tsx +6 -3
  151. package/src/client/common/ConfirmDialog.tsx +29 -12
  152. package/src/client/common/ContentPicker.tsx +13 -12
  153. package/src/client/common/Modal.tsx +12 -5
  154. package/src/client/common/MoreMenu.tsx +4 -1
  155. package/src/client/common/RunsCenter.tsx +103 -32
  156. package/src/client/common/Select.tsx +2 -2
  157. package/src/client/common/floating-bounds.ts +1 -1
  158. package/src/client/common/floating-units.test.ts +1 -2
  159. package/src/client/common/plan-text-redaction.test.ts +188 -3
  160. package/src/client/common/runs-center-guard.test.ts +60 -0
  161. package/src/client/common/runs-center-view.test.ts +128 -0
  162. package/src/client/common/runs-center-view.ts +96 -0
  163. package/src/client/common/section-title-action.test.ts +66 -0
  164. package/src/client/common/ui.tsx +93 -30
  165. package/src/client/config-manager.module.css +1507 -272
  166. package/src/client/consult/ConsultCard.tsx +7 -6
  167. package/src/client/environment/EnvironmentPanel.tsx +20 -21
  168. package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
  169. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  170. package/src/client/export/ExportView.tsx +7 -16
  171. package/src/client/history/HistoryPanel.tsx +88 -28
  172. package/src/client/history/history-locales.ts +3 -3
  173. package/src/client/home/BackupScheduleCard.tsx +35 -30
  174. package/src/client/home/HomePanel.tsx +45 -10
  175. package/src/client/import/ConflictList.tsx +13 -13
  176. package/src/client/import/ForeignImportView.tsx +32 -13
  177. package/src/client/import/ImportWizardView.tsx +2 -3
  178. package/src/client/import/PathMappingForm.tsx +4 -4
  179. package/src/client/import/PathPickerDialog.tsx +2 -1
  180. package/src/client/import/foreign-import-view-guard.test.ts +1 -1
  181. package/src/client/import/import-wizard-steps.tsx +51 -39
  182. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  183. package/src/client/import/use-import-wizard-controller.ts +116 -22
  184. package/src/client/library/ArtifactRow.tsx +2 -2
  185. package/src/client/library/BackupInspectView.tsx +19 -15
  186. package/src/client/library/LibraryActions.tsx +56 -16
  187. package/src/client/library/LibraryPanel.tsx +7 -7
  188. package/src/client/library/RestorePlanView.tsx +13 -8
  189. package/src/client/locales/about.ts +0 -2
  190. package/src/client/locales/backup.ts +10 -12
  191. package/src/client/locales/common.ts +2 -0
  192. package/src/client/locales/export.ts +5 -12
  193. package/src/client/locales/foreign.ts +11 -2
  194. package/src/client/locales/import.ts +3 -2
  195. package/src/client/locales/overview.ts +4 -0
  196. package/src/client/locales/profiles.ts +32 -4
  197. package/src/client/locales/restore.ts +0 -2
  198. package/src/client/locales/sessions.ts +0 -2
  199. package/src/client/locales/shell.ts +2 -2
  200. package/src/client/market/MarketPanel.tsx +38 -20
  201. package/src/client/market/MyConfigsList.tsx +34 -32
  202. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  203. package/src/client/market/MyConfigsView.tsx +5 -5
  204. package/src/client/market/MyConfigsWizard.tsx +7 -12
  205. package/src/client/market/market-locales.ts +0 -6
  206. package/src/client/market/my-configs-split.test.ts +2 -1
  207. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  208. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  209. package/src/client/recovery/RecoveryPanel.tsx +31 -16
  210. package/src/client/recovery/RollbackCard.tsx +58 -16
  211. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  212. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  213. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  214. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  215. package/src/client/recovery/recovery-locales.ts +12 -8
  216. package/src/client/run-store.test.ts +30 -0
  217. package/src/client/run-store.ts +21 -1
  218. package/src/client/sync/AddChannelCard.tsx +65 -0
  219. package/src/client/sync/AutosyncCard.tsx +182 -108
  220. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  221. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  222. package/src/client/sync/MergePreviewView.tsx +3 -5
  223. package/src/client/sync/PushReportSections.tsx +35 -0
  224. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  225. package/src/client/sync/SyncConfirmView.tsx +3 -3
  226. package/src/client/sync/SyncLogList.tsx +16 -5
  227. package/src/client/sync/SyncPanel.tsx +153 -159
  228. package/src/client/sync/SyncProbeRow.tsx +5 -7
  229. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  230. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  231. package/src/client/sync/SyncSettingsDialog.tsx +304 -0
  232. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  233. package/src/client/sync/WorkDirCard.tsx +2 -4
  234. package/src/client/sync/config-clear-guard.test.ts +94 -0
  235. package/src/client/sync/config-clear-guard.ts +98 -0
  236. package/src/client/sync/config-dirty.test.ts +91 -0
  237. package/src/client/sync/config-dirty.ts +88 -0
  238. package/src/client/sync/history-model.test.ts +2 -0
  239. package/src/client/sync/history-model.ts +3 -0
  240. package/src/client/sync/merge-request.ts +20 -0
  241. package/src/client/sync/sync-api.ts +12 -0
  242. package/src/client/sync/sync-locales.ts +87 -47
  243. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  244. package/src/client/sync/sync-view.test.ts +20 -0
  245. package/src/client/sync/sync-view.ts +42 -4
  246. package/src/core/backup.test.ts +61 -1
  247. package/src/core/backup.ts +21 -4
  248. package/src/core/boot-rescue.test.ts +35 -0
  249. package/src/core/boot-rescue.ts +13 -2
  250. package/src/core/boot-safety.test.ts +25 -0
  251. package/src/core/boot-safety.ts +37 -2
  252. package/src/core/conflict-decisions.ts +2 -1
  253. package/src/core/exporter.ts +21 -1
  254. package/src/core/journal.test.ts +183 -0
  255. package/src/core/journal.ts +163 -25
  256. package/src/core/local-plugin-host.test.ts +68 -2
  257. package/src/core/local-plugin-host.ts +31 -4
  258. package/src/core/messages.ts +14 -0
  259. package/src/core/migration-history.test.ts +27 -0
  260. package/src/core/migration-history.ts +12 -4
  261. package/src/core/model-tools.test.ts +67 -0
  262. package/src/core/model-tools.ts +16 -4
  263. package/src/core/patch-secret-guard.test.ts +110 -0
  264. package/src/core/patch-secret-guard.ts +176 -0
  265. package/src/core/reconcile.ts +32 -4
  266. package/src/core/reinstall.ts +8 -2
  267. package/src/core/restore.ts +32 -7
  268. package/src/core/section-sanitize.ts +37 -0
  269. package/src/core/snapshot-diff.test.ts +73 -1
  270. package/src/core/snapshot-diff.ts +66 -21
  271. package/src/core/startup-barrier.test.ts +64 -0
  272. package/src/core/startup-barrier.ts +8 -2
  273. package/src/core/types.ts +27 -1
  274. package/src/core/update-check.test.ts +40 -0
  275. package/src/core/update-check.ts +53 -2
  276. package/src/foreign/claude-code.test.ts +5 -0
  277. package/src/foreign/claude-plugins.test.ts +57 -0
  278. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  279. package/src/foreign/dsh.test.ts +23 -0
  280. package/src/foreign/file-budget.test.ts +7 -1
  281. package/src/foreign/kernel.ts +9 -2
  282. package/src/foreign/read-claude-plugins.ts +32 -11
  283. package/src/foreign/read-dsh.ts +33 -2
  284. package/src/foreign/read-trae.ts +117 -5
  285. package/src/foreign/session-ir.test.ts +67 -0
  286. package/src/foreign/session-ir.ts +54 -14
  287. package/src/foreign/session-read.ts +23 -0
  288. package/src/foreign/session-source.ts +15 -5
  289. package/src/foreign/trae-sqlcipher.test.ts +360 -0
  290. package/src/foreign/trae-sqlcipher.ts +564 -0
  291. package/src/foreign/trae.test.ts +188 -0
  292. package/src/foreign/trae.ts +3 -1
  293. package/src/foreign/truth-table.ts +4 -2
  294. package/src/foreign/types.ts +10 -1
  295. package/src/index.ts +1 -1
  296. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  297. package/src/profiles/dsh-profile-io.ts +29 -0
  298. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  299. package/src/profiles/dsh-profile-manager.ts +53 -5
  300. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  301. package/src/profiles/dsh-profile-runtime.ts +17 -3
  302. package/src/profiles/process-control.test.ts +97 -0
  303. package/src/profiles/process-control.ts +28 -1
  304. package/src/routes/profiles.ts +2 -1
  305. package/src/routes/sync.ts +13 -1
  306. package/src/schema/types.ts +16 -1
  307. package/src/security/redaction.test.ts +31 -0
  308. package/src/security/redaction.ts +23 -6
  309. package/src/sync/autosync-repeat.test.ts +58 -0
  310. package/src/sync/autosync-repeat.ts +55 -0
  311. package/src/sync/autosync-scheduler.test.ts +417 -0
  312. package/src/sync/autosync-scheduler.ts +154 -41
  313. package/src/sync/baseline-heal.ts +6 -0
  314. package/src/sync/baseline-record.ts +135 -0
  315. package/src/sync/blob-store.test.ts +16 -0
  316. package/src/sync/blob-store.ts +13 -0
  317. package/src/sync/content-diff.test.ts +95 -0
  318. package/src/sync/content-diff.ts +79 -0
  319. package/src/sync/git/git-transport.test.ts +151 -4
  320. package/src/sync/git/git-transport.ts +143 -27
  321. package/src/sync/github-auth.test.ts +26 -1
  322. package/src/sync/github-auth.ts +37 -1
  323. package/src/sync/merge-apply-plan.ts +117 -0
  324. package/src/sync/messages.ts +2 -0
  325. package/src/sync/pending-merge.ts +77 -0
  326. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  327. package/src/sync/s3/s3-transport.ts +76 -42
  328. package/src/sync/sync-config.test.ts +39 -12
  329. package/src/sync/sync-device-identity.test.ts +3 -0
  330. package/src/sync/sync-engine.test.ts +465 -12
  331. package/src/sync/sync-engine.ts +130 -135
  332. package/src/sync/sync-history.ts +7 -0
  333. package/src/sync/sync-state.ts +48 -0
  334. package/src/sync/transport.test.ts +13 -1
  335. package/src/sync/transport.ts +12 -4
  336. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  337. package/src/sync/webdav/webdav-transport.ts +86 -34
  338. package/src/ui/commands.test.ts +11 -0
  339. package/src/ui/commands.ts +5 -14
  340. package/src/ui/dsh-profiles-view.test.ts +16 -0
  341. package/src/ui/dsh-profiles-view.ts +11 -5
  342. package/src/ui/foreign-view.test.ts +36 -0
  343. package/src/ui/foreign-view.ts +46 -0
  344. package/src/ui/i18n.ts +17 -2
  345. package/src/ui/menu-placement.ts +1 -1
  346. package/src/ui/migration-consult-view.test.ts +20 -1
  347. package/src/ui/migration-consult-view.ts +17 -0
  348. package/src/ui/overview-view.ts +10 -0
  349. package/src/ui/report.test.ts +25 -1
  350. package/src/ui/report.ts +15 -4
  351. package/src/ui/selection-model.test.ts +15 -1
  352. package/src/ui/selection-model.ts +18 -0
  353. package/src/utils/js-yaml4.d.ts +35 -0
  354. package/src/utils/patch-yaml.test.ts +207 -1
  355. package/src/utils/patch-yaml.ts +98 -2
  356. package/src/utils/paths.test.ts +14 -1
  357. package/src/utils/paths.ts +35 -0
  358. package/src/utils/workdir-lock.test.ts +69 -0
  359. package/src/utils/workdir-lock.ts +17 -3
  360. package/lib/ui/path-mapping.d.ts +0 -38
  361. package/lib/ui/path-mapping.js +0 -75
  362. package/src/client/common/InfoHint.tsx +0 -289
  363. package/src/client/common/info-hint-guard.test.ts +0 -1119
  364. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  365. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  366. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  367. package/src/ui/path-mapping.test.ts +0 -67
  368. package/src/ui/path-mapping.ts +0 -103
@@ -10,6 +10,8 @@ import fs from 'node:fs/promises';
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
12
12
 
13
+ import { createCipheriv, randomBytes } from 'node:crypto';
14
+
13
15
  import { FOREIGN_TRUTH_TABLES, TRUTH_PROBE_ENV, TRUTH_PROBES } from './truth-table.ts';
14
16
  import { normalizePlatform, roamingAppDataDir, vscodeUserDataDir, xdgDataHome } from './platform-paths.ts';
15
17
  import type { ForeignPlatform } from './platform-paths.ts';
@@ -75,6 +77,13 @@ import {
75
77
  traeVscdbPaths,
76
78
  } from './read-trae.ts';
77
79
  import { sqliteCapability } from './sqlite.ts';
80
+ import {
81
+ TRAE_DB_DEFAULT_KEY,
82
+ TRAE_DB_KEY_ENV,
83
+ TRAE_DB_PAGE_SIZE,
84
+ TRAE_DB_RESERVE_BYTES,
85
+ traeDbPathFor,
86
+ } from './trae-sqlcipher.ts';
78
87
 
79
88
  interface SqliteModule {
80
89
  DatabaseSync?: new (p: string) => {
@@ -314,3 +323,182 @@ test('trae t9 旧版回退键的库:整库可读(不再漏读)', async (t)
314
323
  await fs.rm(root, { recursive: true, force: true });
315
324
  }
316
325
  });
326
+ /* ------------------------------------------- 2.3.x 加密库夹具(SQLCipher 形态) */
327
+
328
+ const DB_PAGE = TRAE_DB_PAGE_SIZE;
329
+ const DB_RESERVE = TRAE_DB_RESERVE_BYTES;
330
+ /** 会话 cwd 必须是**运行平台可判定为绝对**的路径(否则转码层按 session-missing-cwd 丢弃) */
331
+ const DB_CWD = HOST === 'win32' ? 'C:\\work\\trae' : '/work/trae';
332
+
333
+ /** 把 node:sqlite 建的普通库重排成 reserve 80 的明文库(真实 SQLCipher 明文的形状) */
334
+ function reserve80(input: Buffer): Buffer {
335
+ const out = Buffer.from(input);
336
+ const pages = Math.floor(out.length / DB_PAGE);
337
+ const usable = DB_PAGE - DB_RESERVE;
338
+ for (let index = 0; index < pages; index += 1) {
339
+ const base = index * DB_PAGE;
340
+ const header = index === 0 ? 100 : 0;
341
+ const cellCount = out.readUInt16BE(base + header + 3);
342
+ const contentStart = out.readUInt16BE(base + header + 5);
343
+ if (contentStart === 0 || contentStart >= DB_PAGE) continue;
344
+ out.copy(out, base + contentStart - DB_RESERVE, base + contentStart, base + DB_PAGE);
345
+ out.fill(0, base + usable, base + DB_PAGE);
346
+ out.writeUInt16BE(contentStart - DB_RESERVE, base + header + 5);
347
+ for (let cell = 0; cell < cellCount; cell += 1) {
348
+ const pointer = base + header + 8 + cell * 2;
349
+ out.writeUInt16BE(out.readUInt16BE(pointer) - DB_RESERVE, pointer);
350
+ }
351
+ }
352
+ out[20] = DB_RESERVE;
353
+ return out;
354
+ }
355
+
356
+ /** 按 SQLCipher 4.x 页面布局正向加密(page0 = salt + AES,每页尾 IV16 + HMAC64 占位) */
357
+ function sqlcipherPages(plain: Buffer, keyHex: string): Buffer {
358
+ const key = Buffer.from(keyHex, 'hex');
359
+ const pages = Math.ceil(plain.length / DB_PAGE);
360
+ const out: Buffer[] = [];
361
+ for (let index = 0; index < pages; index += 1) {
362
+ const start = index * DB_PAGE;
363
+ const page = Buffer.alloc(DB_PAGE);
364
+ plain.copy(page, 0, start, Math.min(start + DB_PAGE, plain.length));
365
+ const usable = DB_PAGE - DB_RESERVE;
366
+ const payload = index === 0 ? page.subarray(16, usable) : page.subarray(0, usable);
367
+ const iv = randomBytes(16);
368
+ const cipher = createCipheriv('aes-256-cbc', key, iv);
369
+ cipher.setAutoPadding(false);
370
+ const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
371
+ out.push(index === 0 ? randomBytes(16) : Buffer.alloc(0), encrypted, iv, randomBytes(64));
372
+ }
373
+ return Buffer.concat(out);
374
+ }
375
+
376
+ /** 在 <User>/ModularData/ai-agent/database.db 造一个 SQLCipher 形态的库(表真造,不是假数据) */
377
+ async function makeEncryptedDb(file: string, ids: readonly string[], keyHex = TRAE_DB_DEFAULT_KEY): Promise<boolean> {
378
+ const spec = 'node:sqlite';
379
+ let mod: SqliteModule;
380
+ try {
381
+ mod = await import(spec) as SqliteModule;
382
+ } catch {
383
+ return false;
384
+ }
385
+ const Ctor = mod.DatabaseSync;
386
+ if (Ctor === undefined) return false;
387
+ await fs.mkdir(path.dirname(file), { recursive: true });
388
+ const plainFile = file + '.plain';
389
+ const db = new Ctor(plainFile);
390
+ try {
391
+ db.exec('CREATE TABLE chat_session (id TEXT PRIMARY KEY, session_id TEXT, title TEXT, cwd TEXT, created_at INTEGER)');
392
+ db.exec('CREATE TABLE history_v2 (session_id TEXT, messages TEXT)');
393
+ const insertSession = db.prepare('INSERT INTO chat_session (id, session_id, title, cwd, created_at) VALUES (?, ?, ?, ?, ?)');
394
+ const insertHistory = db.prepare('INSERT INTO history_v2 (session_id, messages) VALUES (?, ?)');
395
+ for (const id of ids) {
396
+ insertSession.run(id, id, 'enc-' + id, DB_CWD, 1750000000000);
397
+ insertHistory.run(id, JSON.stringify({
398
+ raw_messages: [
399
+ { role: 'user', content: 'hi ' + id },
400
+ { role: 'assistant', content: 'yo ' + id },
401
+ ],
402
+ }));
403
+ }
404
+ } finally {
405
+ db.close();
406
+ }
407
+ const plain = reserve80(await fs.readFile(plainFile));
408
+ await fs.writeFile(file, sqlcipherPages(plain, keyHex));
409
+ await fs.rm(plainFile, { force: true });
410
+ return true;
411
+ }
412
+
413
+ test('trae t10 双通道并存:加密库优先且同 id 只计一份,旧 state.vscdb 的其余会话仍保留', async (t) => {
414
+ const capability = await sqliteCapability();
415
+ if (!capability.available) {
416
+ t.skip('本宿主无 node:sqlite');
417
+ return;
418
+ }
419
+ const root = await tmpRoot('trae-dual');
420
+ try {
421
+ const userDir = vscodeUserDataDir(HOST, root, {}, 'Trae CN');
422
+ assert.equal(await makeEncryptedDb(traeDbPathFor(userDir, HOST), ['d-1', 'd-2']), true, '加密库夹具必须造成功');
423
+ // 旧通道:d-1 与加密库同 id(迁移残留),old-9 只在旧库
424
+ assert.equal(await makeVscdb(path.join(userDir, 'globalStorage', 'state.vscdb'), [
425
+ { key: 'memento/icube-ai-agent-storage', value: JSON.stringify({
426
+ sessions: [
427
+ { id: 'd-1', workspace: DB_CWD, messages: [{ role: 'user', content: '旧残留' }] },
428
+ { id: 'old-9', workspace: DB_CWD, messages: [{ role: 'user', content: '只有旧库' }] },
429
+ ],
430
+ }) },
431
+ ]), true);
432
+
433
+ const read = await readTrae({ homeDir: root, env: {}, platform: HOST });
434
+ assert.deepEqual(read.files.map((f) => f.id), ['d-1', 'd-2', 'old-9'], '同 id 只出现一次,加密库先占位');
435
+ const dup = read.files.find((f) => f.id === 'd-1');
436
+ assert.equal(dup?.records[0]?.blocks[0]?.type, 'text', '同 id 用的是加密库那份正文');
437
+ assert.equal(read.extraCounts?.['trae.encryptedDb'], 1);
438
+ assert.equal(read.extraCounts?.['trae.encryptedSessions'], 2, '加密库贡献 2 条,旧库补 1 条');
439
+ assert.equal(read.extraSkips?.some((s) => s.code === 'sessions-not-migrated'), false, '加密库在场时不得再说「没迁移」');
440
+
441
+ const result = await traeSource.build(ctxOf(root, HOST));
442
+ assert.equal(result.counts['sessions.files'], 3);
443
+ } finally {
444
+ await fs.rm(root, { recursive: true, force: true });
445
+ }
446
+ });
447
+
448
+ test('trae t11 detect 期就带出 sessions-not-migrated(不再等 build 的 400 才闪一下)', async (t) => {
449
+ const capability = await sqliteCapability();
450
+ if (!capability.available) {
451
+ t.skip('本宿主无 node:sqlite');
452
+ return;
453
+ }
454
+ const root = await tmpRoot('trae-detect');
455
+ try {
456
+ const userDir = vscodeUserDataDir(HOST, root, {}, 'Trae');
457
+ assert.equal(await makeVscdb(path.join(userDir, 'globalStorage', 'state.vscdb'), [
458
+ { key: 'memento/workbench.panel.output', value: '{}' },
459
+ ]), true);
460
+ const detect = await traeSource.detect(ctxOf(root, HOST));
461
+ assert.equal(detect.found, true);
462
+ assert.equal(
463
+ detect.skipped?.some((s) => s.code === 'sessions-not-migrated' && s.detail === 'chat-storage-key-not-found'),
464
+ true,
465
+ 'detect 必须预告 build 会产生的同一 skip',
466
+ );
467
+ // 完全没有库时不预告(空目录 ≠ 没迁移)
468
+ const empty = await tmpRoot('trae-detect-empty');
469
+ try {
470
+ const skipped = await traeSource.detect(ctxOf(empty, HOST));
471
+ assert.deepEqual(skipped.skipped ?? [], []);
472
+ } finally {
473
+ await fs.rm(empty, { recursive: true, force: true });
474
+ }
475
+ } finally {
476
+ await fs.rm(root, { recursive: true, force: true });
477
+ }
478
+ });
479
+
480
+ test('trae t12 密钥不对:detect 与 build 都给 trae-db-key-invalid(绝不静默 0 会话)', async (t) => {
481
+ const capability = await sqliteCapability();
482
+ if (!capability.available) {
483
+ t.skip('本宿主无 node:sqlite');
484
+ return;
485
+ }
486
+ const root = await tmpRoot('trae-badkey');
487
+ try {
488
+ const userDir = vscodeUserDataDir(HOST, root, {}, 'TRAE SOLO CN');
489
+ assert.equal(await makeEncryptedDb(traeDbPathFor(userDir, HOST), ['k-1']), true);
490
+ const env = { [TRAE_DB_KEY_ENV]: '00'.repeat(32) };
491
+ const detect = await traeSource.detect(ctxOf(root, HOST, env));
492
+ assert.equal(detect.skipped?.some((s) => s.code === 'trae-db-key-invalid'), true, 'detect 必须先报密钥问题');
493
+
494
+ const read = await readTrae({ homeDir: root, env, platform: HOST });
495
+ assert.deepEqual(read.files, []);
496
+ assert.equal(read.extraSkips?.some((s) => s.code === 'trae-db-key-invalid'), true);
497
+ // 换回内置缺省密钥,同一台机器又能读到(密钥不是写死不可换)
498
+ const ok = await readTrae({ homeDir: root, env: {}, platform: HOST });
499
+ assert.deepEqual(ok.files.map((f) => f.id), ['k-1']);
500
+ } finally {
501
+ await fs.rm(root, { recursive: true, force: true });
502
+ }
503
+ });
504
+
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { draftFromTranscript, sessionSourceOf } from './session-source.ts';
8
8
  import type { SessionSourceWiring } from './session-source.ts';
9
- import { readTrae, traeProbePaths } from './read-trae.ts';
9
+ import { readTrae, traeDetectSkips, traeProbePaths } from './read-trae.ts';
10
10
  import type { TraeSessionFile } from './read-trae.ts';
11
11
  import type { ForeignSource } from './registry.ts';
12
12
 
@@ -14,6 +14,8 @@ export const traeWiring: SessionSourceWiring<TraeSessionFile> = {
14
14
  id: 'trae',
15
15
  evidence: 'fixture',
16
16
  probePaths: (opts) => traeProbePaths(opts),
17
+ // detect 期就预告「为什么没有会话」(密钥错 / 超限 / 旧库无候选键),别等 build 的 400
18
+ probeSkips: (opts) => traeDetectSkips(opts),
17
19
  read: (opts) => readTrae(opts),
18
20
  draftOf: (file) => draftFromTranscript(file.id, file, 'trae'),
19
21
  };
@@ -432,8 +432,10 @@ export const FOREIGN_TRUTH_TABLES: readonly ForeignTruthTableEntry[] = [
432
432
  envKeys: [{ key: 'XDG_CONFIG_HOME', mode: 'replace', absoluteOnly: true, platforms: ['linux'] }],
433
433
  autoRoots: true,
434
434
  evidence: 'fixture',
435
- refs: 'read-vault §10.1 trae 行 + chat-import discovery.mjs:80-93,140,2386(**4 个发行版** × 三分支;$APPDATA 缺失即跳过)',
436
- dynamic: '<User>/{workspaceStorage,globalStorage}/**/state.vscdb(SQLite ItemTable;键 memento/icube-ai-agent-storage + 4 回退键)',
435
+ refs: 'read-vault §10.1 trae 行 + chat-import discovery.mjs:80-93,140,2386(**4 个发行版** × 三分支;$APPDATA 缺失即跳过)+ issue #134(2.3.x 加密库布局与 raw key 见 xitula/trae-session-export;**本机无真机样本,evidence 仍为 fixture**)',
436
+ dynamic:
437
+ '<User>/ModularData/ai-agent/database.db(2.3.x SQLCipher 4.x 整库加密,page 4096 / reserve 80 = IV16+HMAC512;表 chat_session / history_v2 / chat_message / chat_turn / project,消息在 history_v2.messages 的 raw_messages[])'
438
+ + ' 与 <User>/{workspaceStorage,globalStorage}/**/state.vscdb(旧通道,SQLite ItemTable;键 memento/icube-ai-agent-storage + 4 回退键);两条并存时按会话 id 只计一份',
437
439
  },
438
440
  {
439
441
  id: 'vibe',
@@ -182,7 +182,16 @@ export type ForeignSkipCode =
182
182
  /** 同名 MCP server 在多处出现(全局 / 项目级 / 插件):先到先得,其余只报告 */
183
183
  | 'mcp-server-id-conflict'
184
184
  /** 项目级扫描触顶(maxProjects):**不静默**,如实报码 */
185
- | 'project-scan-truncated';
185
+ | 'project-scan-truncated'
186
+ /* ---- 2026-11-12(#134):Trae 2.3.x 的 SQLCipher 加密会话库四条可判定失败 ---- */
187
+ /** 加密库密钥不符(换版 / 用户覆盖了错误密钥):页头判据不成立,**绝不静默 0 会话** */
188
+ | 'trae-db-key-invalid'
189
+ /** 加密库超出**本来源**的体积上限(copy-too-large 语义;全局 1 GiB 兜底未改) */
190
+ | 'trae-db-too-large'
191
+ /** 加密库解密失败:截断 / 非 SQLCipher 形态 / 页尺寸不符 / IO 错误 */
192
+ | 'trae-db-decrypt-failed'
193
+ /** 解密成功但表结构不符(缺 chat_session / history_v2 或必需列):可判定失败,不猜字段 */
194
+ | 'trae-db-schema-mismatch';
186
195
 
187
196
  /**
188
197
  * 冲突语义(**契约冻结**,§8.4):同 id 会话恒「不覆盖、跳过并报码」。
package/src/index.ts CHANGED
@@ -184,7 +184,7 @@ export const name = 'config-manager'
184
184
  export const inject = ['settings', 'credentials']
185
185
 
186
186
  /** Plugin version, kept in sync with package.json ("version"). */
187
- export const PLUGIN_VERSION = '0.8.1'
187
+ export const PLUGIN_VERSION = '0.9.0'
188
188
 
189
189
  /** Plugin own package name — excluded from its own exported plugins list. */
190
190
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -14,12 +14,14 @@
14
14
  */
15
15
  import test from 'node:test'
16
16
  import assert from 'node:assert/strict'
17
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
17
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
18
18
  import { join } from 'node:path'
19
19
  import { tmpdir } from 'node:os'
20
20
 
21
- import { DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
21
+ import { DshProfileError, DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
22
+ import type { DshProfileManagerOptions } from './dsh-profile-manager.ts'
22
23
  import type { DshProfileCopyMarker } from './dsh-profile-shared.ts'
24
+ import type { AtomicIoSync } from '../utils/atomic-write.ts'
23
25
 
24
26
  /** 磁盘契约字面量:改名即等于把旧版本留下的残留重新变成「查不到」(与 dsh-profile-incomplete-copy.test.ts 同口径)。 */
25
27
  const MARKER = '.dcm-copy-in-progress.json'
@@ -33,14 +35,40 @@ const MARKER_OBJ: DshProfileCopyMarker = {
33
35
  pid: 4242,
34
36
  }
35
37
 
36
- function makeManager(): { mgr: DshProfileManager; home: string; cleanup: () => void } {
38
+ function makeManager(extra: Partial<DshProfileManagerOptions> = {}): { mgr: DshProfileManager; home: string; cleanup: () => void } {
37
39
  const root = mkdtempSync(join(tmpdir(), 'dsh-copy-rollback-'))
38
40
  const home = join(root, 'home')
39
41
  mkdirSync(join(home, 'profiles'), { recursive: true })
40
- const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web' })
42
+ const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web', ...extra })
41
43
  return { mgr, home, cleanup: () => { rmSync(root, { recursive: true, force: true }) } }
42
44
  }
43
45
 
46
+ /**
47
+ * 只让「标记那一次写入」失败:除 open(atomicWriteFileSync 唯一会真的动盘前的最后一步)之外
48
+ * 全部转发真实 fs。用它复现「目录已建好、标记却写不出来」这条窄缝。
49
+ */
50
+ function failingMarkerIo(): AtomicIoSync {
51
+ return {
52
+ mkdir: (dir, opts) => { mkdirSync(dir, { recursive: opts.recursive }) },
53
+ lstat: (target) => {
54
+ try {
55
+ const stat = lstatSync(target)
56
+ return { isSymbolicLink: () => stat.isSymbolicLink(), mode: stat.mode }
57
+ } catch {
58
+ return null
59
+ }
60
+ },
61
+ realpath: (target) => realpathSync(target),
62
+ open: () => { throw new Error('EIO: simulated copy-marker write failure') },
63
+ writeFd: () => {},
64
+ fsyncFd: () => {},
65
+ closeFd: () => {},
66
+ rename: (from, to) => { renameSync(from, to) },
67
+ unlink: (target) => { rmSync(target, { force: true }) },
68
+ fsyncDir: () => {},
69
+ }
70
+ }
71
+
44
72
  /** 造一个「复制中途失败」的目标目录:部分内容 + 标记,**没有 package.json**。 */
45
73
  function writeHalfCopy(home: string, name = 'work-copy'): string {
46
74
  const dir = join(home, 'profiles', name)
@@ -154,3 +182,29 @@ test('#5-D:copy() 失败路径确实走回滚(整体接线)—— 目标
154
182
  cleanup()
155
183
  }
156
184
  })
185
+
186
+ test('#5-E:标记写不出来 ⇒ 连目标目录一起回滚,绝不留「list() 看不到、remove() 报 notFound」的空壳', async () => {
187
+ const { mgr, home, cleanup } = makeManager({ markerIo: failingMarkerIo() })
188
+ try {
189
+ const src = join(home, 'profiles', 'work')
190
+ mkdirSync(src, { recursive: true })
191
+ writeFileSync(join(src, 'package.json'), JSON.stringify({ name: 'dsh-profile-work', dependencies: {} }), 'utf8')
192
+
193
+ const dest = join(home, 'profiles', 'work-copy')
194
+ await assert.rejects(
195
+ mgr.copy('work', 'work-copy'),
196
+ (err: unknown) => err instanceof DshProfileError && err.code === 'copyFailed',
197
+ '标记写失败也是复制失败:必须走统一错误码,不得把底层 fs 错误原样抛给调用方',
198
+ )
199
+
200
+ // 三个视角同时成立,才算没有孤儿:
201
+ // ① 盘上没有那个目录(旧实现会留下一个空目录)
202
+ assert.equal(existsSync(dest), false, '标记写失败必须连目录一起清掉')
203
+ // ② 档案列表里没有它
204
+ assert.deepEqual(mgr.list().map((meta) => meta.name), ['work'], '列表里只有源档案')
205
+ // ③ 残留列举里也没有它(残留应该是「有标记的半截副本」,而不是空壳)
206
+ assert.deepEqual(mgr.listIncompleteCopies(), [])
207
+ } finally {
208
+ cleanup()
209
+ }
210
+ })
@@ -11,6 +11,7 @@
11
11
  * `sanitizeFilePart`(同一正则)。
12
12
  */
13
13
  import { readFileSync } from 'node:fs'
14
+ import { createHash } from 'node:crypto'
14
15
 
15
16
  /**
16
17
  * 读文本文件;不可读返回 **null** —— 语义差异由调用方显式表达(**不得把 null 统一成 ''**):
@@ -29,3 +30,31 @@ export function readTextSafe(path: string): string | null {
29
30
  export function sanitizeFilePart(name: string): string {
30
31
  return name.replace(/[^A-Za-z0-9._-]/g, '_')
31
32
  }
33
+
34
+ /**
35
+ * 运行心跳文件名(**唯一实现**)—— 可读前缀 + 名字哈希。
36
+ *
37
+ * 为什么必须带哈希(审计 P11-2 P1,2026-11-13 实测):心跳文件此前叫
38
+ * `<sanitizeFilePart(name)>.json`,而清洗是**多对一**的 —— `web` 与 `web!` 都落到
39
+ * `web.json`,于是两个实例共享同一个心跳文件:后写的覆盖先写的,`listActive()` 只看得到
40
+ * 一个,`stopExternal` 可能停错人,`withdraw()` 也会删掉别人的心跳(对方从此「不可见」,
41
+ * 界面上又能被重复启动 —— 正是这套机制要防的事)。
42
+ *
43
+ * 判据:清洗只用于可读性(截断到 48 字符、去掉结尾的点/空格,Windows 会吃掉结尾点),
44
+ * **唯一性由 sha256(原名) 的前 12 hex 保证**;\0 之类不可达字符也天然被哈希区隔。
45
+ */
46
+ export function runtimeFileName(name: string): string {
47
+ const readable = sanitizeFilePart(name).replace(/[. ]+$/, '').slice(0, 48)
48
+ const digest = createHash('sha256').update(name, 'utf8').digest('hex').slice(0, 12)
49
+ return readable === '' ? `${digest}.json` : `${readable}-${digest}.json`
50
+ }
51
+
52
+ /**
53
+ * 旧版心跳文件名(升级清理专用):`<sanitizeFilePart(name)>.json`。
54
+ *
55
+ * 只用于「自报/自撤时顺手删掉自己那份旧文件」—— 否则升级后同一个 profile 会留下两份心跳,
56
+ * `listActive` 对同名记录会看到两条。绝不用于读别人的记录。
57
+ */
58
+ export function legacyRuntimeFileName(name: string): string {
59
+ return `${sanitizeFilePart(name)}.json`
60
+ }
@@ -349,6 +349,36 @@ test('remove:物理删除目录;当前 profile 需显式确认', () => {
349
349
  }
350
350
  })
351
351
 
352
+ test('removeAsync(审计 P11-9):同一套护栏 + 删除期间事件循环不被独占', async () => {
353
+ const { mgr, home, cleanup } = makeManager()
354
+ try {
355
+ mgr.create('work', 'base')
356
+ const dir = join(home, 'profiles', 'work')
357
+ mkdirSync(join(dir, 'node_modules', 'pkg'), { recursive: true })
358
+ for (let i = 0; i < 400; i += 1) writeFileSync(join(dir, 'node_modules', 'pkg', `f-${i}.js`), 'x')
359
+
360
+ // 删除期间每 5 ms 一次的心跳(真机对应宿主里的定时探测):同步实现期间一次都不会触发
361
+ let ticks = 0
362
+ const timer = setInterval(() => { ticks += 1 }, 5)
363
+ try {
364
+ await mgr.removeAsync('work')
365
+ } finally {
366
+ clearInterval(timer)
367
+ }
368
+ assert.equal(existsSync(dir), false, '目录必须真的删净')
369
+ assert.ok(ticks > 0, `异步删除期间事件循环必须能跑定时器,实际 ticks=${ticks}`)
370
+
371
+ // 护栏与同步版一致
372
+ mgr.create('live', 'web')
373
+ const current = new DshProfileManager({ homeDir: home, currentProfile: () => 'live' })
374
+ await assert.rejects(() => current.removeAsync('live'), (e: unknown) => e instanceof DshProfileError && e.code === 'currentProfile')
375
+ await assert.rejects(() => mgr.removeAsync('desktop'), (e: unknown) => e instanceof DshProfileError && e.code === 'managedProfile')
376
+ await assert.rejects(() => mgr.removeAsync('gone'), (e: unknown) => e instanceof DshProfileError && e.code === 'notFound')
377
+ } finally {
378
+ cleanup()
379
+ }
380
+ })
381
+
352
382
  test('remove:含悬空 junction 的档案也能删净(fs.rm 静默失效的回归)', () => {
353
383
  const { mgr, home, cleanup } = makeManager()
354
384
  try {
@@ -27,7 +27,7 @@ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, type
27
27
  // 复制走 async fs(整档案上万个文件,cpSync 会把宿主事件循环卡住二十多秒)
28
28
  import { copyFile, cp, mkdir, readdir, readlink, stat, symlink, unlink } from 'node:fs/promises'
29
29
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
30
- import { atomicWriteFileSync } from '../utils/atomic-write.ts'
30
+ import { atomicWriteFileSync, type AtomicIoSync } from '../utils/atomic-write.ts'
31
31
  import { removeTree, removeTreeSync } from '../utils/remove-tree.ts'
32
32
  import { isRecord } from '../utils/guards.ts'
33
33
  import { resolveProfileDir, validateProfileName } from '../core/plugin-cli.ts'
@@ -81,6 +81,13 @@ export interface DshProfileManagerOptions {
81
81
  /** 插件 dataDir(保留给调用方复用;本引擎不再落任何状态) */
82
82
  /** 当前运行中的 profile 名(惰性读取,宿主注入) */
83
83
  currentProfile?: () => string
84
+ /**
85
+ * 「复制进行中标记」那一次写盘用的可注入同步 io(缺省 undefined = 真实 fs)。
86
+ *
87
+ * 只给单测用:Windows 上造不出「目录建好、标记写不出来」的真实故障(写完立刻腾空间就失败了),
88
+ * 而这条窄缝恰恰会留下既不在 list() 里、remove() 又报 notFound 的空目录。
89
+ */
90
+ markerIo?: AtomicIoSync
84
91
  }
85
92
 
86
93
  /**
@@ -182,10 +189,13 @@ export async function rollbackCopiedProfileDir(
182
189
  export class DshProfileManager {
183
190
  private readonly homeDir: string
184
191
  private readonly currentProfile: () => string
192
+ /** 见 DshProfileManagerOptions.markerIo:只作用于「复制进行中标记」的写入 */
193
+ private readonly markerIo: AtomicIoSync | undefined
185
194
 
186
195
  constructor(options: DshProfileManagerOptions) {
187
196
  this.homeDir = options.homeDir
188
197
  this.currentProfile = options.currentProfile ?? ((): string => 'web')
198
+ this.markerIo = options.markerIo
189
199
  }
190
200
 
191
201
  /** profiles 根目录(`$DSH_HOME/profiles`) */
@@ -297,9 +307,6 @@ export class DshProfileManager {
297
307
  if (existsSync(destDir)) throw new DshProfileError('exists')
298
308
  const includeNodeModules = opts.includeNodeModules !== false
299
309
  const startedAt = Date.now()
300
- await mkdir(destDir, { recursive: true })
301
- // cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
302
- // 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
303
310
  const marker: DshProfileCopyMarker = {
304
311
  sourceName: name,
305
312
  newName,
@@ -307,8 +314,13 @@ export class DshProfileManager {
307
314
  includeNodeModules,
308
315
  pid: process.pid,
309
316
  }
310
- atomicWriteFileSync(this.copyMarkerPath(destDir), `${JSON.stringify(marker, null, 2)}\n`, { mode: 0o644 })
317
+ // 建目录与落标记同属一个回滚范围:标记写不出来时这个目录还没有任何可辨认身份,
318
+ // 留在盘上就是「list() 看不到、remove() 报 notFound」的空壳 —— 必须在 catch 里一并清掉。
311
319
  try {
320
+ await mkdir(destDir, { recursive: true })
321
+ // cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
322
+ // 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
323
+ this.writeCopyMarker(destDir, marker)
312
324
  const entries = await readdir(srcDir, { withFileTypes: true })
313
325
  for (const entry of entries) {
314
326
  // node_modules 与 DSH 投影出来的 .dsh-module-fallback 同进同出(后者的链接都指向前者)
@@ -449,6 +461,30 @@ export class DshProfileManager {
449
461
  }
450
462
  }
451
463
 
464
+ /**
465
+ * remove() 的异步版本:语义、护栏、错误码完全一致,只是不阻塞事件循环(审计 P11-9)。
466
+ *
467
+ * 为什么需要两份:档案目录是整仓里最大的一棵树(含 node_modules,真机 2 万文件)。实测
468
+ * removeTreeSync 删 2 万文件耗 15.5 s,期间宿主 20 ms 定时器 0/776 次触发 —— 心跳、实例
469
+ * 存活探测、同步定时器全停摆,面板表现成「后端卡死」。HTTP 删除走这里;只有确实同步
470
+ * 上下文(脚本、收尾清理)才用 remove(),且必须是自己知道很小的树。
471
+ */
472
+ async removeAsync(name: string, opts: { allowCurrent?: boolean } = {}): Promise<void> {
473
+ if (isManagedProfileName(name)) throw new DshProfileError('managedProfile')
474
+ const dir = this.requireManagedDir(name)
475
+ if (name === this.currentProfile() && opts.allowCurrent !== true) {
476
+ throw new DshProfileError('currentProfile')
477
+ }
478
+ try {
479
+ await removeTree(dir)
480
+ } catch (error) {
481
+ throw new DshProfileError('deleteFailed', error instanceof Error ? error.message : String(error))
482
+ }
483
+ if (existsSync(dir)) {
484
+ throw new DshProfileError('deleteFailed', `profile directory still exists after removal: ${dir}`)
485
+ }
486
+ }
487
+
452
488
  /**
453
489
  * cross-F3:目标目录 = **正常 profile(有 package.json)** 或 **中断的复制残留(有进行中标记)**;
454
490
  * 两者都没有 → notFound。残余标记的目录必须能被定位与删除,否则就是孤儿。
@@ -465,6 +501,18 @@ export class DshProfileManager {
465
501
  throw new DshProfileError('notFound')
466
502
  }
467
503
 
504
+ /**
505
+ * 落「复制进行中标记」(cross-F3 的唯一凭据)。
506
+ *
507
+ * 单独抽出来只为把注入点收窄到这一处写入:调用方(copy)据此保证「标记写失败 ⇒ 目录一起回滚」。
508
+ */
509
+ private writeCopyMarker(dir: string, marker: DshProfileCopyMarker): void {
510
+ atomicWriteFileSync(this.copyMarkerPath(dir), `${JSON.stringify(marker, null, 2)}\n`, {
511
+ mode: 0o644,
512
+ ...(this.markerIo === undefined ? {} : { syncIo: this.markerIo }),
513
+ })
514
+ }
515
+
468
516
  /** 复制进行中标记的路径。 */
469
517
  private copyMarkerPath(dir: string): string {
470
518
  return join(dir, PROFILE_COPY_MARKER_FILENAME)
@@ -16,6 +16,7 @@ import {
16
16
  parseRuntimeRecord, runtimeRecordLive,
17
17
  } from './dsh-profile-runtime.ts'
18
18
  import { DshProfileError } from './dsh-profile-manager.ts'
19
+ import { runtimeFileName } from './dsh-profile-io.ts'
19
20
 
20
21
  interface HarnessOptions {
21
22
  name?: string
@@ -75,13 +76,13 @@ test('announce / listActive / withdraw:自报 → 可见 → 自撤', () => {
75
76
  assert.equal(written.name, 'web')
76
77
  assert.equal(written.pid, 111)
77
78
  assert.equal(written.port, 3080)
78
- assert.equal(existsSync(join(h.dir, 'web.json')), true)
79
+ assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), true)
79
80
  const active = h.registry.listActive()
80
81
  assert.deepEqual(active.map((r) => r.name), ['web'])
81
82
  assert.equal(active[0]?.port, 3080)
82
83
  h.registry.withdraw()
83
84
  assert.deepEqual(h.registry.listActive(), [])
84
- assert.equal(existsSync(join(h.dir, 'web.json')), false)
85
+ assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), false)
85
86
  } finally { h.cleanup() }
86
87
  })
87
88
 
@@ -118,10 +119,31 @@ test('listActive:死心跳 / 过期心跳 / 坏文件都会被清掉(进程
118
119
  writeFileSync(join(h.dir, 'stale.json'), JSON.stringify(stale))
119
120
  const active = h.registry.listActive()
120
121
  assert.deepEqual(active.map((r) => r.name), ['web'], '只留活着的自己')
121
- assert.deepEqual(readdirSync(h.dir).sort(), ['web.json'], '死/坏心跳文件已清理')
122
+ assert.deepEqual(readdirSync(h.dir).sort(), [runtimeFileName('web')], '死/坏心跳文件已清理')
122
123
  } finally { h.cleanup() }
123
124
  })
124
125
 
126
+ test('心跳文件名必须唯一:清洗后同形的两个 profile 不得共用/互删心跳(审计 P11-2 回归)', () => {
127
+ // 旧实现 <sanitizeFilePart(name)>.json:'web' 与 'web!' 都落成 web.json ⇒ 后写的覆盖先写的,
128
+ // listActive 只看得到一个,withdraw 还会删掉别人的心跳(对方从此「不可见」,又能被重复启动)。
129
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-runtime-'))
130
+ try {
131
+ const mk = (name: string, pid: number) => new DshProfileRuntimeRegistry({
132
+ dataDir: dir, name, pid,
133
+ deps: { isAlivePid: (p) => p === pid, killPid: () => {}, now: () => 1_000_000, sleep: () => Promise.resolve() },
134
+ })
135
+ const a = mk('web', 111)
136
+ const b = mk('web!', 222)
137
+ a.announce()
138
+ b.announce()
139
+ assert.notEqual(a.fileFor('web'), b.fileFor('web!'), '清洗同形的两个名字必须落到不同文件')
140
+ assert.equal(readdirSync(join(dir, 'running')).length, 2, '两个实例各留一份心跳')
141
+ b.withdraw()
142
+ assert.equal(existsSync(a.fileFor('web')), true, 'B 自撤不得删掉 A 的心跳')
143
+ assert.deepEqual(a.listActive().map((r) => r.name), ['web'], 'A 仍可见')
144
+ } finally { rmSync(dir, { recursive: true, force: true }) }
145
+ })
146
+
125
147
  test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删除它的心跳', async () => {
126
148
  const a = makeHarness({ name: 'web', pid: 111, alive: 'die-on-kill' })
127
149
  const b = makeHarness({ name: 'cmtest', pid: 222, alive: 'die-on-kill' })
@@ -142,7 +164,7 @@ test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删
142
164
  assert.equal(stopped.name, 'cmtest')
143
165
  assert.deepEqual(a.killed, ['222:graceful'])
144
166
  assert.deepEqual(a.registry.listActive().map((r) => r.name), ['web'], 'B 的心跳已被删')
145
- assert.equal(existsSync(join(a.dir, 'cmtest.json')), false)
167
+ assert.equal(existsSync(join(a.dir, runtimeFileName('cmtest'))), false)
146
168
  } finally { a.cleanup(); b.cleanup() }
147
169
  })
148
170
 
@@ -165,7 +187,7 @@ test('stopExternal:没有心跳 → notRunning;停自己 → currentProfile
165
187
  () => h.registry.stopExternal('cmtest'),
166
188
  (e: unknown) => e instanceof DshProfileError && e.code === 'stopFailed' && e.message.includes('222'),
167
189
  )
168
- assert.equal(existsSync(join(h.dir, 'cmtest.json')), true, '杀不掉就不删心跳(否则会以为它已经没了)')
190
+ assert.equal(existsSync(join(h.dir, runtimeFileName('cmtest'))), true, '杀不掉就不删心跳(否则会以为它已经没了)')
169
191
  forced.cleanup()
170
192
  } finally { h.cleanup() }
171
193
  })
@@ -184,10 +206,10 @@ test('startHeartbeat:按 refreshMs 定期 announce,stop() 之后不再刷',
184
206
  const stop = h.registry.startHeartbeat()
185
207
  assert.equal(intervalMs, RUNTIME_REFRESH_MS)
186
208
  assert.notEqual(box.fn, null)
187
- const before = JSON.parse(readFileSync(join(h.dir, 'web.json'), 'utf8')) as { updatedAt: number }
209
+ const before = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
188
210
  h.tick(5_000)
189
211
  box.fn?.()
190
- const after = JSON.parse(readFileSync(join(h.dir, 'web.json'), 'utf8')) as { updatedAt: number }
212
+ const after = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
191
213
  assert.equal(after.updatedAt, before.updatedAt + 5_000, '心跳被刷新(判活靠它)')
192
214
  stop()
193
215
  stop()