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
@@ -0,0 +1,249 @@
1
+ /**
2
+ * audit-sync sync-P6-1 / sync-P6-4(P3)的回归钉子(WebDAV 通道):
3
+ *
4
+ * P6-1:delete 必须**先条件写索引、后删对象**。旧顺序(先 DELETE 对象)在索引 PUT 回 412 时留下
5
+ * 「索引指向已删对象」的条目 —— list 不校验存在性,别的设备 pull 到它就是 notfound 硬失败。
6
+ * 最坏情况改为「索引摘除成功但对象 DELETE 失败」= 一个 list 看不到、pull 不会命中的孤儿文件。
7
+ *
8
+ * P6-4:blob 索引的「读失败」与「确实没有索引」必须分开。旧实现把 5xx / 坏 JSON 当空索引,
9
+ * 随后 appendBlobIndex 整体 PUT 覆盖 ⇒ 已登记条目全丢。现在:404/405/501 才是空,其余非 2xx 抛
10
+ * 可重试错误、坏 JSON 抛 protocol,绝不整体覆盖。
11
+ */
12
+ import test from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+
15
+ import { WebDavTransport, WebDavTransportError } from './webdav-transport.ts'
16
+ import type { WebDavRequestFn, WebDavResponse, WebDavTransportOptions } from './webdav-transport.ts'
17
+ import type { SyncSnapshot } from '../transport.ts'
18
+ import { zhMsg } from '../../core/messages.ts'
19
+
20
+ const BASE = 'https://dav.example.com/dav/config'
21
+ const COL = BASE + '/dsh-config-manager'
22
+ const BLOBS_COL = COL + '/blobs'
23
+ const INDEX_URL = COL + '/index.json'
24
+ const BLOBS_INDEX_URL = COL + '/blobs-index.json'
25
+ const SNAPSHOT_URL = COL + '/snap-001.json'
26
+ const TEST_PASSWORD = 'super-secret-password-9876'
27
+ const OLD_HASH = 'a'.repeat(64)
28
+ const NEW_HASH = 'b'.repeat(64)
29
+
30
+ interface MockCall { method: string; url: string; headers?: Record<string, string>; body?: string }
31
+
32
+ function res(status: number, bodyText = '', headers?: Record<string, string>): WebDavResponse {
33
+ return {
34
+ status,
35
+ ok: status >= 200 && status < 300,
36
+ ...(headers !== undefined ? { headers } : {}),
37
+ async text() { return bodyText; },
38
+ };
39
+ }
40
+
41
+ function makeOptions(request: WebDavRequestFn): WebDavTransportOptions {
42
+ return {
43
+ baseUrl: BASE,
44
+ username: 'alice',
45
+ credentials: { getPassword: async () => TEST_PASSWORD },
46
+ request,
47
+ };
48
+ }
49
+
50
+ function recorder(calls: MockCall[], handler: (m: MockCall) => WebDavResponse): WebDavRequestFn {
51
+ return async (method, url, opts = {}) => {
52
+ const rec: MockCall = { method, url, headers: opts.headers, body: opts.body };
53
+ calls.push(rec);
54
+ return handler(rec);
55
+ };
56
+ }
57
+
58
+ /** 一条索引条目(schema 只要求 id/createdAt/manifest/sections) */
59
+ const META = {
60
+ id: 'snap-001',
61
+ createdAt: '2026-10-18T09:00:00.000Z',
62
+ sections: {},
63
+ manifest: { schemaVersion: 1, dshVersion: '1', platform: 'win32', sectionIds: [], containsSecrets: false },
64
+ }
65
+
66
+ /** 带 sessions 文件分区的快照(触发 externalize → blob 仓读写) */
67
+ function sessionsSnapshot(): SyncSnapshot {
68
+ return {
69
+ id: 'snap-001',
70
+ createdAt: '2026-10-18T10:00:00.000Z',
71
+ manifest: {
72
+ schemaVersion: 1,
73
+ dshVersion: '1.2.3',
74
+ platform: 'win32',
75
+ sectionIds: ['sessions'],
76
+ containsSecrets: false,
77
+ },
78
+ sections: {
79
+ sessions: {
80
+ version: 1,
81
+ files: [
82
+ { relativePath: 's1.jsonl', data: new TextEncoder().encode('one'), contentHash: OLD_HASH },
83
+ { relativePath: 's2.jsonl', data: new TextEncoder().encode('two'), contentHash: NEW_HASH },
84
+ ],
85
+ },
86
+ },
87
+ } as unknown as SyncSnapshot;
88
+ }
89
+
90
+ const callsOf = (calls: MockCall[], method: string, url: string): MockCall[] =>
91
+ calls.filter((c) => c.method === method && c.url === url);
92
+
93
+ /* ---------------- P6-1:删除顺序 ---------------- */
94
+
95
+ test('P6-1(删除路径):索引写回 412 → 快照文件零 DELETE(绝不留「索引指向已删对象」)', async () => {
96
+ const calls: MockCall[] = [];
97
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
98
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, JSON.stringify([META]), { etag: '"v1-del"' });
99
+ if (m.method === 'PUT' && m.url === INDEX_URL) return res(412, 'precondition failed');
100
+ if (m.method === 'DELETE' && m.url === SNAPSHOT_URL) return res(204, '');
101
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
102
+ })));
103
+
104
+ await assert.rejects(
105
+ () => t.delete('snap-001'),
106
+ (err: unknown) => {
107
+ assert.ok(err instanceof WebDavTransportError);
108
+ assert.equal(err.kind, 'conflict');
109
+ assert.equal(err.message, zhMsg('sync.webdav.concurrentWrite', { status: '412', url: INDEX_URL }));
110
+ return true;
111
+ },
112
+ );
113
+ assert.equal(callsOf(calls, 'DELETE', SNAPSHOT_URL).length, 0, '索引没写成功就绝不许删对象');
114
+ });
115
+
116
+ test('P6-1(删除路径):成功路径顺序 = 先条件写索引(If-Match),后 DELETE 快照对象', async () => {
117
+ const calls: MockCall[] = [];
118
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
119
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, JSON.stringify([META]), { etag: '"v1-del"' });
120
+ if (m.method === 'PUT' && m.url === INDEX_URL) return res(201, '');
121
+ if (m.method === 'DELETE' && m.url === SNAPSHOT_URL) return res(204, '');
122
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) return res(404, '');
123
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
124
+ })));
125
+
126
+ await t.delete('snap-001');
127
+
128
+ const puts = callsOf(calls, 'PUT', INDEX_URL);
129
+ assert.equal(puts.length, 1, '删除后写回一次索引');
130
+ assert.equal(puts[0]!.headers?.['If-Match'], '"v1-del"', '索引写回仍是条件写');
131
+ assert.equal(puts[0]!.body, '[]', '摘掉了目标条目');
132
+ const putAt = calls.findIndex((c) => c.method === 'PUT' && c.url === INDEX_URL);
133
+ const delAt = calls.findIndex((c) => c.method === 'DELETE' && c.url === SNAPSHOT_URL);
134
+ assert.ok(putAt >= 0 && delAt >= 0, '两条请求都必须发生');
135
+ assert.ok(putAt < delAt, '索引必须先落盘,再删对象(P6-1)');
136
+ });
137
+
138
+ test('P6-1(删除路径):索引无该 id 且对象存在 → 只删对象,不写回索引', async () => {
139
+ const calls: MockCall[] = [];
140
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
141
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, '[]', { etag: '"v1-del"' });
142
+ if (m.method === 'DELETE' && m.url === SNAPSHOT_URL) return res(204, '');
143
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) return res(404, '');
144
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
145
+ })));
146
+
147
+ await t.delete('snap-001');
148
+
149
+ assert.equal(callsOf(calls, 'PUT', INDEX_URL).length, 0, '索引无变化就不写回(N1③ 口径)');
150
+ assert.equal(callsOf(calls, 'DELETE', SNAPSHOT_URL).length, 1, '孤儿对象仍按用户意图删掉');
151
+ });
152
+
153
+ /* ---------------- P6-4:blob 索引三态读 ---------------- */
154
+
155
+ test('P6-4:blob 索引 GET 500 → 上传可重试失败,快照与 blobs-index 零写入', async () => {
156
+ const calls: MockCall[] = [];
157
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
158
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, '[]', { etag: '"v1"' });
159
+ if (m.method === 'MKCOL') return res(201, '');
160
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) return res(503, 'backend down');
161
+ if (m.method === 'PUT' && m.url === SNAPSHOT_URL) return res(201, '');
162
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
163
+ })));
164
+
165
+ await assert.rejects(
166
+ () => t.upload(sessionsSnapshot()),
167
+ (err: unknown) => {
168
+ assert.ok(err instanceof WebDavTransportError);
169
+ assert.equal(err.kind, 'server');
170
+ assert.equal(err.retryable, true, '读抖动属于可重试,不能报成不可恢复');
171
+ return true;
172
+ },
173
+ );
174
+ assert.equal(callsOf(calls, 'PUT', SNAPSHOT_URL).length, 0, '读不出来就零写入');
175
+ assert.equal(callsOf(calls, 'PUT', BLOBS_INDEX_URL).length, 0, '绝不整体覆盖');
176
+ });
177
+
178
+ test('P6-4:blob 索引 200 + 坏 JSON → protocol 错误,绝不覆盖成只有本次条目', async () => {
179
+ const calls: MockCall[] = [];
180
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
181
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, '[]', { etag: '"v1"' });
182
+ if (m.method === 'MKCOL') return res(201, '');
183
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) return res(200, '{not-json');
184
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
185
+ })));
186
+
187
+ await assert.rejects(
188
+ () => t.upload(sessionsSnapshot()),
189
+ (err: unknown) => {
190
+ assert.ok(err instanceof WebDavTransportError);
191
+ assert.equal(err.kind, 'protocol');
192
+ assert.equal(err.retryable, false);
193
+ return true;
194
+ },
195
+ );
196
+ assert.equal(callsOf(calls, 'PUT', BLOBS_INDEX_URL).length, 0);
197
+ });
198
+
199
+ test('P6-4:写回前再读 blobs-index 失败 → 绝不 PUT(已登记条目不得被覆盖掉)', async () => {
200
+ const calls: MockCall[] = [];
201
+ let blobIdxReads = 0;
202
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
203
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, '[]', { etag: '"v1"' });
204
+ if (m.method === 'MKCOL') return res(201, '');
205
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) {
206
+ blobIdxReads += 1;
207
+ // 第一次(externalize 跳过判定)成功:OLD_HASH 已登记 → 零传输;第二次(合并写回)抖动
208
+ return blobIdxReads === 1 ? res(200, JSON.stringify({ [OLD_HASH]: 1 })) : res(500, 'flaky');
209
+ }
210
+ if (m.method === 'PUT' && m.url === SNAPSHOT_URL) return res(201, '');
211
+ if (m.method === 'PUT' && m.url === INDEX_URL) return res(201, '');
212
+ if (m.method === 'PUT' && m.url === BLOBS_INDEX_URL) return res(201, '');
213
+ if (m.method === 'PUT' && m.url.startsWith(BLOBS_COL + '/')) return res(201, '');
214
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
215
+ })));
216
+
217
+ await assert.rejects(
218
+ () => t.upload(sessionsSnapshot()),
219
+ (err: unknown) => {
220
+ assert.ok(err instanceof WebDavTransportError);
221
+ assert.equal(err.kind, 'server');
222
+ return true;
223
+ },
224
+ );
225
+ assert.equal(blobIdxReads, 2, '跳过判定一次 + 合并写回一次');
226
+ assert.equal(callsOf(calls, 'PUT', BLOBS_INDEX_URL).length, 0, '读失败时绝不整体 PUT(P6-4 的核心)');
227
+ assert.equal(callsOf(calls, 'PUT', SNAPSHOT_URL).length, 1, '快照已落盘:本次 blob 漏登记只占空间,不误删');
228
+ });
229
+
230
+ test('P6-4:blob 索引 404(确实没有索引)→ 照常上传并新建索引', async () => {
231
+ const calls: MockCall[] = [];
232
+ const t = new WebDavTransport(makeOptions(recorder(calls, (m) => {
233
+ if (m.method === 'GET' && m.url === INDEX_URL) return res(200, '[]', { etag: '"v1"' });
234
+ if (m.method === 'MKCOL') return res(201, '');
235
+ if (m.method === 'GET' && m.url === BLOBS_INDEX_URL) return res(404, '');
236
+ if (m.method === 'PUT' && m.url === SNAPSHOT_URL) return res(201, '');
237
+ if (m.method === 'PUT' && m.url === INDEX_URL) return res(201, '');
238
+ if (m.method === 'PUT' && m.url === BLOBS_INDEX_URL) return res(201, '');
239
+ if (m.method === 'PUT' && m.url.startsWith(BLOBS_COL + '/')) return res(201, '');
240
+ return res(500, 'unexpected ' + m.method + ' ' + m.url);
241
+ })));
242
+
243
+ await t.upload(sessionsSnapshot());
244
+
245
+ const puts = callsOf(calls, 'PUT', BLOBS_INDEX_URL);
246
+ assert.equal(puts.length, 1, '缺资源 = 空是安全的,必须照常建索引');
247
+ const written = JSON.parse(puts[0]!.body ?? '{}') as Record<string, number>;
248
+ assert.deepEqual(Object.keys(written).sort(), [OLD_HASH, NEW_HASH].sort());
249
+ });
@@ -39,7 +39,7 @@ import { BLOB_SECTIONS, gcBlobs, isBlobRefsSection, isFilesSectionLike, referenc
39
39
  import type { BlobRefsSection, BlobSink } from '../blob-store.ts';
40
40
  import {
41
41
  classifyHttpStatus, classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS,
42
- isEncryptedSections, sectionsEqual, SyncTransportError, withSyncRetry,
42
+ isEncryptedSections, isPreconditionFailedStatus, sectionsEqual, SyncTransportError, withSyncRetry,
43
43
  } from '../transport.ts';
44
44
  import type { FilesSection, SectionData, SectionId } from '../../schema/types.ts';
45
45
  import type {
@@ -420,11 +420,15 @@ export class WebDavTransport implements SyncTransport {
420
420
  const merged = idxBefore.filter((m) => m.id !== snapshot.id);
421
421
  merged.push(meta);
422
422
  merged.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
423
+ const idxHeaders = conditionalHeaders(idxEtag, indexMissing);
423
424
  const putIdx = await this.send('PUT', idxUrl, pwd, {
424
425
  body: JSON.stringify(merged),
425
- headers: conditionalHeaders(idxEtag, indexMissing),
426
+ headers: idxHeaders,
426
427
  });
427
- if (putIdx.status === 412) throw this.concurrentWrite(idxUrl, putIdx.status);
428
+ // 条件写失败判定与 s3 通道共用 transport.ts 的唯一实现(412 恒算;409 仅在真的带了条件头时算)
429
+ if (isPreconditionFailedStatus(putIdx.status, { guarded: Object.keys(idxHeaders).length > 0 })) {
430
+ throw this.concurrentWrite(idxUrl, putIdx.status);
431
+ }
428
432
  if (!putIdx.ok) {
429
433
  throw new WebDavTransportError(await this.failText('PUT', idxUrl, putIdx, pwd), classifyHttpStatus(putIdx.status));
430
434
  }
@@ -471,29 +475,46 @@ export class WebDavTransport implements SyncTransport {
471
475
  // gcBlobStore 以空引用集回收,删掉仍被现存快照文件引用的会话 blob(不可恢复)。
472
476
  // 与 F1 同口径:宁可显式失败,也不制造不可恢复的远端状态。list() 仍保留「404 = 空集合」语义。
473
477
  const { entries: idx, missing: indexMissing, etag: idxEtag } = await this.readIndexDetailed(pwd);
474
- // delete 快照文件:404 = 不存在,视为成功
475
478
  const url = this.snapshotUrl(id);
476
- const res = await this.send('DELETE', url, pwd);
477
- if (!res.ok && res.status !== 404) {
478
- throw new WebDavTransportError(await this.failText('DELETE', url, res, pwd), classifyHttpStatus(res.status));
479
+ if (indexMissing) {
480
+ // audit-sync sync-N1(P0):索引真缺失(404)= **缺信息**而不是「集合为空」。此时「哪些 blob
481
+ // 无人引用」无从证明 —— 一律**不写回 index.json、不触发 blob GC**,其余快照与其引用的 blob
482
+ // 原样保留(宁可留垃圾,不可删在用的)。目标快照文件按用户意图删除(404 视为成功)。
483
+ const res = await this.send('DELETE', url, pwd);
484
+ if (!res.ok && res.status !== 404) {
485
+ throw new WebDavTransportError(await this.failText('DELETE', url, res, pwd), classifyHttpStatus(res.status));
486
+ }
487
+ return;
479
488
  }
480
- // audit-sync sync-N1(P0):索引真缺失(404)= **缺信息**而不是「集合为空」。此时「哪些 blob
481
- // 无人引用」无从证明 —— 一律**不写回 index.json、不触发 blob GC**,其余快照与其引用的 blob
482
- // 原样保留(宁可留垃圾,不可删在用的)。目标快照文件已按用户意图删除(404 视为成功)。
483
- if (indexMissing) return;
484
- // 若 index 中无该 id,则无需写回
485
489
  const remaining = idx.filter((m) => m.id !== id);
486
- if (remaining.length === idx.length && res.status === 404) {
487
- return; // 文件与 index 都不存在 → 静默成功,无写回
490
+ const entryPresent = remaining.length !== idx.length;
491
+ // audit-sync sync-P6-1(P3):**先写索引、后删对象**。
492
+ // 反序(旧实现先 DELETE 快照文件)的伤害:索引 PUT 回 412(别的设备刚改过索引)时本次删除已
493
+ // 抛错中止,但对象已经没了 ⇒ 索引里留下指向不存在对象的条目;list() 不校验存在性,别的设备
494
+ // pull 到该 id 就是 notfound 硬失败,只能靠用户再删一次自愈。
495
+ // 调整顺序后的**最坏情况**:索引写成功而对象 DELETE 失败 ⇒ 远端留一个索引里不存在、list()
496
+ // 看不到、pull 不会命中的孤儿文件(只占空间);重跑 delete 会把对象补删(404 视为成功)。
497
+ // 「多一个看不见的孤儿文件」远轻于「索引指向已删对象」,因此顺序必须是索引在前。
498
+ if (entryPresent) {
499
+ const idxHeaders = conditionalHeaders(idxEtag, false);
500
+ const putIdx = await this.send('PUT', idxUrl, pwd, {
501
+ body: JSON.stringify(remaining),
502
+ headers: idxHeaders,
503
+ });
504
+ // 判定与 s3 通道共用同一实现(412 恒算;409 仅在真的带了条件头时算)
505
+ if (isPreconditionFailedStatus(putIdx.status, { guarded: Object.keys(idxHeaders).length > 0 })) {
506
+ throw this.concurrentWrite(idxUrl, putIdx.status);
507
+ }
508
+ if (!putIdx.ok) {
509
+ throw new WebDavTransportError(await this.failText('PUT', idxUrl, putIdx, pwd), classifyHttpStatus(putIdx.status));
510
+ }
488
511
  }
489
- const putIdx = await this.send('PUT', idxUrl, pwd, {
490
- body: JSON.stringify(remaining),
491
- headers: conditionalHeaders(idxEtag, false),
492
- });
493
- if (putIdx.status === 412) throw this.concurrentWrite(idxUrl, putIdx.status);
494
- if (!putIdx.ok) {
495
- throw new WebDavTransportError(await this.failText('PUT', idxUrl, putIdx, pwd), classifyHttpStatus(putIdx.status));
512
+ // 索引已摘除(或本来就无该 id)后才动对象:404 = 不存在,视为成功
513
+ const res = await this.send('DELETE', url, pwd);
514
+ if (!res.ok && res.status !== 404) {
515
+ throw new WebDavTransportError(await this.failText('DELETE', url, res, pwd), classifyHttpStatus(res.status));
496
516
  }
517
+ if (!entryPresent && !res.ok) return; // 索引无该 id 且对象本就不存在 → 静默成功,无 GC 可做
497
518
  // P1-4:快照被裁掉后回收无人引用的 blob(best-effort,失败不影响删除结果)
498
519
  await this.gcBlobStore(pwd, remaining).catch(() => undefined);
499
520
  }
@@ -528,7 +549,10 @@ export class WebDavTransport implements SyncTransport {
528
549
  }
529
550
  }
530
551
 
531
- /** 把本次新写入的 blob 合并进远端索引(写失败 → 抛错,调用方看到的是上传失败而非静默漏记)。 */
552
+ /**
553
+ * 把本次新写入的 blob 合并进远端索引(写失败 → 抛错,调用方看到的是上传失败而非静默漏记)。
554
+ * audit-sync sync-P6-4(P3):这里的读失败必须上抛 —— 整体 PUT 会覆盖远端已登记条目。
555
+ */
532
556
  private async appendBlobIndex(fresh: Map<string, number>, pwd: string): Promise<void> {
533
557
  const index = await this.readBlobIndex(pwd);
534
558
  for (const [hash, at] of fresh) index[hash] = at;
@@ -567,23 +591,51 @@ export class WebDavTransport implements SyncTransport {
567
591
  }
568
592
  }
569
593
 
570
- /** 读取 blob 索引(哈希 → 写入时间 ms);缺失/损坏 → 空(GC 只会「少删」,不会误删)。 */
594
+ /** 读取 blob 索引(哈希 → 写入时间 ms);只读失败即抛,绝不回落成空索引,见 readBlobIndexDetailed。 */
571
595
  private async readBlobIndex(pwd: string): Promise<Record<string, number>> {
596
+ return (await this.readBlobIndexDetailed(pwd)).index;
597
+ }
598
+
599
+ /**
600
+ * audit-sync sync-P6-4(P3):读 blob 索引的**带缺失标志**版本 —— 「读失败」与「确实没有索引」必须分开。
601
+ *
602
+ * 旧实现把 5xx / 坏 JSON / 非法结构一律当成空索引返回,紧接着 appendBlobIndex 读→合并→**整体 PUT**,
603
+ * 于是「一次读抖动」= 远端索引被覆盖成本次新增的那几条,已登记条目全丢(GC 从此看不见这些 blob,
604
+ * 等于远端漏账;再叠加 delete 的 GC 就可能删掉它们)。语义因此必须三态:
605
+ * - 404 / 405 / 501 → missing = true:**缺资源**。405/501 是部分 WebDAV 服务端表达「没有这个资源」
606
+ * 的方言(与 remoteHasPriorContent 同口径),此时确实没有索引可丢,按空处理是安全的;
607
+ * - 其它非 2xx(5xx / 403 / …)→ 抛错(可重试):读不出来就**不许**整体覆盖,让上传显式失败;
608
+ * - 200 但坏 JSON / 非对象 → 抛 protocol(不可重试):索引损坏是远端状态问题,覆盖写会抹掉残存记录。
609
+ *
610
+ * 最坏情况(可重试失败):本可跳过的 blob 被重传一遍,或本次 blob 漏登记(只占空间,不误删)。
611
+ */
612
+ private async readBlobIndexDetailed(pwd: string): Promise<{ index: Record<string, number>; missing: boolean }> {
572
613
  const url = this.blobsIndexUrl();
573
614
  const res = await this.send('GET', url, pwd);
574
- if (res.status === 404) return {};
575
- if (!res.ok) return {};
615
+ if (res.status === 404 || res.status === 405 || res.status === 501) return { index: {}, missing: true };
616
+ if (!res.ok) {
617
+ throw new WebDavTransportError(await this.failText('GET', url, res, pwd), classifyHttpStatus(res.status));
618
+ }
619
+ let parsed: unknown;
576
620
  try {
577
- const parsed = parseJsonSafe(await res.text());
578
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
579
- const out: Record<string, number> = {};
580
- for (const [hash, at] of Object.entries(parsed as Record<string, unknown>)) {
581
- if (BLOB_HASH_RE.test(hash) && typeof at === 'number' && Number.isFinite(at)) out[hash] = at;
582
- }
583
- return out;
584
- } catch {
585
- return {};
621
+ parsed = parseJsonSafe(await res.text());
622
+ } catch (err) {
623
+ throw new WebDavTransportError(
624
+ this.o.msg('sync.webdav.indexInvalid', { url, err: this.mask(String((err as Error)?.message ?? ''), pwd) }),
625
+ { kind: 'protocol', retryable: false },
626
+ );
627
+ }
628
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
629
+ throw new WebDavTransportError(
630
+ this.o.msg('sync.webdav.indexInvalid', { url, err: 'not an object' }),
631
+ { kind: 'protocol', retryable: false },
632
+ );
633
+ }
634
+ const out: Record<string, number> = {};
635
+ for (const [hash, at] of Object.entries(parsed as Record<string, unknown>)) {
636
+ if (BLOB_HASH_RE.test(hash) && typeof at === 'number' && Number.isFinite(at)) out[hash] = at;
586
637
  }
638
+ return { index: out, missing: false };
587
639
  }
588
640
 
589
641
  private async writeBlobIndex(pwd: string, index: Record<string, number>): Promise<void> {
@@ -70,6 +70,17 @@ test('关键词命中(同义说法)', () => {
70
70
  assert.ok(ids(filterCommands(COMMANDS, 'webdav', titleOf, ctx())).includes('go.sync'))
71
71
  })
72
72
 
73
+ test('关键词命中:四个同步通道都能搜到「同步」(P10-1:手写镜像漏过 s3/gist)', () => {
74
+ // 镜像只抄了 git/webdav 两通道时,搜 s3 或 gist 一条「同步」命令都不出现 ——
75
+ // 现在关键词从 SYNC_CHANNELS 派生(唯一事实源在 utils/shared-constants.ts)。
76
+ for (const channel of ['git', 'webdav', 's3', 'gist']) {
77
+ assert.ok(
78
+ ids(filterCommands(COMMANDS, channel, titleOf, ctx())).includes('go.sync'),
79
+ '搜 ' + channel + ' 必须命中 go.sync',
80
+ )
81
+ }
82
+ })
83
+
73
84
  test('关键词命中:口语「磁盘」直达维护与诊断、「恢复」直达事故恢复', () => {
74
85
  assert.ok(ids(filterCommands(COMMANDS, '磁盘', titleOf, ctx())).includes('maintenance.open'))
75
86
  assert.ok(ids(filterCommands(COMMANDS, '恢复', titleOf, ctx())).includes('recovery.open'))
@@ -12,19 +12,10 @@
12
12
  * 中文用户敲「导出」命中标题,英文用户敲 "export" 命中 id。
13
13
  */
14
14
 
15
- // 只导入**类型**:type-only import 在编译期被擦除,不会把 src/sync 的运行时依赖带进 client bundle。
16
- import type { SyncTransportType } from '../sync/sync-config.ts'
17
-
18
- /**
19
- * 通道搜索词 = **受守卫的客户端镜像**。
20
- *
21
- * 为什么必须写成这个形状:t32 源码守卫(`src/sync/sync-config.test.ts`)把「两个通道名的
22
- * 字面量相邻出现」视为第二处通道枚举声明(历史上一模一样的两份数组漏改过一份,导致某通道
23
- * 永不排期),只有带 `satisfies` 穷尽标记的客户端镜像才放行。**连注释里都不许把这两个名字
24
- * 写成相邻的带引号字面量** —— 守卫扫的是文本,不区分代码与注释。
25
- * 写成搜索关键词也一样要守这条规矩 —— 守卫认的是形状,不是用途。
26
- */
27
- const SYNC_CHANNEL_TERMS = ['git', 'webdav'] satisfies readonly SyncTransportType[]
15
+ // 通道搜索词只认**唯一事实源** `SYNC_CHANNELS`(`src/utils/shared-constants.ts`,零依赖,
16
+ // client 侧已有多处运行时 import 先例)。这里绝不再抄一份清单:手写镜像漏过 s3/gist,
17
+ // 结果搜这两个通道名时「同步」一条命令都不出现(审计 P10-1)。通道增删时这里自动跟随。
18
+ import { SYNC_CHANNELS } from '../utils/shared-constants.ts'
28
19
 
29
20
  /** 命令分组(渲染顺序见 `COMMAND_GROUP_ORDER`)。 */
30
21
  export type CommandGroup = 'navigate' | 'library' | 'action' | 'view' | 'rescue'
@@ -92,7 +83,7 @@ export const COMMANDS: readonly CommandItem[] = [
92
83
  // —— 前往:四个一级页面(v3 §3.1;市场不再是页面)——
93
84
  { id: 'go.home', group: 'navigate', titleKey: 'nav.home', keywords: ['home', 'overview', '首页', '总览'] },
94
85
  { id: 'go.library', group: 'navigate', titleKey: 'library.title', keywords: ['library', 'artifact', '产物', '快照'] },
95
- { id: 'go.sync', group: 'navigate', titleKey: 'nav.sync', keywords: ['sync', ...SYNC_CHANNEL_TERMS, '同步'] },
86
+ { id: 'go.sync', group: 'navigate', titleKey: 'nav.sync', keywords: ['sync', ...SYNC_CHANNELS, '同步'] },
96
87
  {
97
88
  // 环境 = 档案 + 维护与诊断。文案用导航条上的名字(environment.title),
98
89
  // 不用旧的 nav.profiles('档案')—— 面板里找不到「档案」这个页面。
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { test } from 'node:test'
5
5
  import assert from 'node:assert/strict'
6
+ import { readFileSync } from 'node:fs'
6
7
 
7
8
  import {
8
9
  bundleLines, canLaunchProfile, copyWarningKey, dependencyLines, formatBytes, formatProfileTime,
@@ -212,6 +213,21 @@ test('profileInstallCommand / copyWarningKey:副本缺 node_modules 的自救
212
213
  assert.notEqual(profileInstallCommand('a'), restartCommand('a'), '安装命令与启动命令不是同一条')
213
214
  assert.equal(copyWarningKey('depsNotInstalled'), 'profiles.duplicate.warn.depsNotInstalled')
214
215
  })
216
+
217
+ test('copyWarningKey:未映射的告警码暴露为 undefined,不再套用 depsNotInstalled 文案(P10-4)', () => {
218
+ // 修复前 if + 兜底 return 同一字面量:任何入参都返回「缺 node_modules」文案,
219
+ // 于是新增告警码会被静默显示成错误原因。这里用类型逃逸模拟「未来新增的码」。
220
+ assert.equal(copyWarningKey('futureCode' as never), undefined, '未映射的码必须留白,而不是伪造原因')
221
+ // 穷尽性由 Record 的键类型保证(新增 DshProfileCopyWarning 而漏配 ⇒ typecheck 失败),
222
+ // 这里再锁一次机制本身:函数体只能是查表,不能退回手写兜底。
223
+ const src = readFileSync(new URL('./dsh-profiles-view.ts', import.meta.url), 'utf8')
224
+ assert.match(src, /const COPY_WARNING_KEY: Record<DshProfileCopyWarning, /, '映射表必须用 Record<告警码, …> 声明(穷尽性检查的来源)')
225
+ assert.match(
226
+ src,
227
+ /export function copyWarningKey[^}]*\{\s*return COPY_WARNING_KEY\[warning\]\s*\}/,
228
+ 'copyWarningKey 只能是查表:任何 return 字面量兜底都会重新引入「所有码都说缺 node_modules」',
229
+ )
230
+ })
215
231
  test('formatBytes:B / KB / MB 与非法输入', () => {
216
232
  assert.equal(formatBytes(0), '0 B')
217
233
  assert.equal(formatBytes(-5), '0 B')
@@ -176,12 +176,18 @@ export function suggestCopyName(name: string, existingNames: readonly string[],
176
176
  }
177
177
 
178
178
  /**
179
- * 复制告警码 → i18n key。目前只有 `depsNotInstalled` 一类(副本没带 node_modules 却声明了依赖),
180
- * 返回类型写成字面量联合:新增告警码时这里会编译报错,逼着补文案而不是静默吞掉。
179
+ * 复制告警码 → i18n key。目前只有 `depsNotInstalled` 一类(副本没带 node_modules 却声明了依赖)。
180
+ *
181
+ * 为什么是 `Record<告警码, 文案键>` 而不是 if + 兜底:原先 if 与兜底 return 同一字面量,
182
+ * 任何新告警码都会被静默显示成「缺 node_modules」的文案,注释里承诺的「新增码编译报错」
183
+ * 并不存在(审计 P10-4)。Record 的键即告警码全集 —— 码增删而映射不跟上就是编译错误。
181
184
  */
182
- export function copyWarningKey(warning: DshProfileCopyWarning): 'profiles.duplicate.warn.depsNotInstalled' {
183
- if (warning === 'depsNotInstalled') return 'profiles.duplicate.warn.depsNotInstalled'
184
- return 'profiles.duplicate.warn.depsNotInstalled'
185
+ const COPY_WARNING_KEY: Record<DshProfileCopyWarning, 'profiles.duplicate.warn.depsNotInstalled'> = {
186
+ depsNotInstalled: 'profiles.duplicate.warn.depsNotInstalled',
187
+ }
188
+
189
+ export function copyWarningKey(warning: DshProfileCopyWarning): (typeof COPY_WARNING_KEY)[DshProfileCopyWarning] {
190
+ return COPY_WARNING_KEY[warning]
185
191
  }
186
192
 
187
193
  /** 终端启动命令(非 web 形态没有浏览器界面,只能在终端用它拉起)。 */
@@ -14,6 +14,7 @@ import assert from 'node:assert/strict';
14
14
  import {
15
15
  FOREIGN_LOSSY_KINDS,
16
16
  FOREIGN_SKIP_KEY,
17
+ foreignImportFailure,
17
18
  foreignLossyRows,
18
19
  foreignPathsText,
19
20
  foreignSkipLine,
@@ -316,3 +317,38 @@ test('foreign-view:prompts 分区 / 六文件类分区同时命中 → 三条
316
317
  const rows = foreignLossyRows(['skills', 'prompts'], zh);
317
318
  for (const row of rows) assert.equal(row.applicable, true, row.kind + ' 在本包里应当适用');
318
319
  });
320
+
321
+ /**
322
+ * 导入失败文案(issue #134 第二半):后端 400 的稳定码必须被翻成字典文案,
323
+ * 而不是把 message / 裸机器码直接糊到用户脸上。
324
+ */
325
+ test('foreign-view:导入失败按稳定码翻字典(skip 码 / nothing-to-import / 未知码回落原文)', () => {
326
+ const withCode = (code: unknown, message = 'raw backend message') => foreignImportFailure(
327
+ Object.assign(new Error(message), { code }),
328
+ zh,
329
+ );
330
+
331
+ // skip 码:用 build 阶段真实会返回的码(含本轮新增的 4 个 trae-db-*)
332
+ for (const code of ['sessions-not-migrated', 'trae-db-key-invalid', 'trae-db-too-large', 'trae-db-decrypt-failed', 'trae-db-schema-mismatch'] as const) {
333
+ const failure = withCode(code);
334
+ assert.equal(failure.code, code);
335
+ assert.equal(failure.text, zh(('foreign.skip.' + code) as UiTextKey), code + ' 必须翻成既有字典文案');
336
+ assert.notEqual(failure.text, 'raw backend message', code + ' 不得回落原始 message');
337
+ }
338
+ // 路由自己的 400 码(不在 skip 词表里)也要有文案
339
+ const nothing = withCode('nothing-to-import');
340
+ assert.equal(nothing.code, 'nothing-to-import');
341
+ assert.equal(nothing.text, zh('foreign.importNothing'));
342
+ assert.ok(nothing.text.length > 0 && nothing.text !== 'foreign.importNothing', 'zh 文案必须是真文案(回退键名即视为缺失)');
343
+
344
+ // 未知码 / 无码:原样展示后端 message(不编造、不吞掉)
345
+ const unknown = withCode('some-future-code', '磁盘满了');
346
+ assert.equal(unknown.code, 'some-future-code');
347
+ assert.equal(unknown.text, '磁盘满了');
348
+ const bare = foreignImportFailure(new Error('网络断了'), zh);
349
+ assert.equal(bare.code, null);
350
+ assert.equal(bare.text, '网络断了');
351
+ const weird = foreignImportFailure('not an error', zh);
352
+ assert.equal(weird.code, null);
353
+ assert.equal(weird.text, 'not an error');
354
+ });
@@ -147,6 +147,11 @@ export const FOREIGN_SKIP_KEY: Record<ForeignSkipCode, UiTextKey> = {
147
147
  'session-id-mismatch': 'foreign.skip.session-id-mismatch',
148
148
  'mcp-server-id-conflict': 'foreign.skip.mcp-server-id-conflict',
149
149
  'project-scan-truncated': 'foreign.skip.project-scan-truncated',
150
+ // 2026-11-12(#134):Trae 2.3.x 加密会话库的四条可判定失败 —— 同样是全量 Record 保底
151
+ 'trae-db-key-invalid': 'foreign.skip.trae-db-key-invalid',
152
+ 'trae-db-too-large': 'foreign.skip.trae-db-too-large',
153
+ 'trae-db-decrypt-failed': 'foreign.skip.trae-db-decrypt-failed',
154
+ 'trae-db-schema-mismatch': 'foreign.skip.trae-db-schema-mismatch',
150
155
  }
151
156
 
152
157
  /**
@@ -397,3 +402,44 @@ export function foreignLossyRows(sections: readonly string[] | null, t: UiT): re
397
402
  applicable: applicable[kind],
398
403
  }))
399
404
  }
405
+
406
+ /* -------------------------------------------------- 导入失败(#134) */
407
+
408
+ /**
409
+ * 导入失败 → 可见载荷(码 + 后端原话 + 一句人话)。
410
+ *
411
+ * 为什么要有它:宿主把「为什么没东西可导」放在 **400 的 body**(`code` + `skipped`),
412
+ * 而客户端过去只显示 `err.message` —— 于是 `sessions-not-migrated`、
413
+ * `trae-db-key-invalid` 这些**字典里早就有中英文案**的码,用户根本看不到。
414
+ * 现在按同一本字典把码翻成文案(skip 码走冻结映射,`nothing-to-import` 走单独一条键),
415
+ * 翻不出才回落后端 message —— 绝不吞掉原因,也绝不编解释。
416
+ */
417
+ export interface ForeignImportFailure {
418
+ /** 稳定机器码(后端 400 带的 code;没有则为 null) */
419
+ code: string | null
420
+ /** 后端原始 message(渲染处再过 redact) */
421
+ message: string
422
+ /** 展示文案(字典优先;没有就用 message) */
423
+ text: string
424
+ }
425
+
426
+ /**
427
+ * 非 skip 词表、但同样会作为 400 码出现的导入失败(与 `src/routes/foreign.ts` 同源):
428
+ * `nothing-to-import` 是路由层的码,不在 `ForeignSkipCode` union 里,故单独映射。
429
+ */
430
+ const IMPORT_FAILURE_KEYS: Readonly<Record<string, UiTextKey>> = {
431
+ 'nothing-to-import': 'foreign.importNothing',
432
+ }
433
+
434
+ /** 失败载荷的构造(未知码 → 原样返回 message,绝不猜语义) */
435
+ export function foreignImportFailure(err: unknown, t: UiT): ForeignImportFailure {
436
+ const source = typeof err === 'object' && err !== null ? (err as { code?: unknown; message?: unknown }) : null
437
+ const rawCode = source?.code
438
+ const code = typeof rawCode === 'string' && rawCode !== '' ? rawCode : null
439
+ const rawMessage = source?.message
440
+ const message = typeof rawMessage === 'string' && rawMessage !== '' ? rawMessage : String(err)
441
+ if (code === null) return { code, message, text: message }
442
+ const mapped = IMPORT_FAILURE_KEYS[code] ?? (isKnownSkipCode(code) ? FOREIGN_SKIP_KEY[code] : undefined)
443
+ return { code, message, text: mapped === undefined ? message : t(mapped) }
444
+ }
445
+