dsh-config-manager 0.8.2 → 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 (345) 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 +104 -49
  18. package/lib/client.js +12536 -12006
  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/session-ir.js +50 -9
  53. package/lib/foreign/session-read.d.ts +8 -0
  54. package/lib/foreign/session-read.js +26 -0
  55. package/lib/index.d.ts +1 -1
  56. package/lib/index.js +1 -1
  57. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  58. package/lib/profiles/dsh-profile-io.js +27 -0
  59. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  60. package/lib/profiles/dsh-profile-manager.js +45 -4
  61. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  62. package/lib/profiles/dsh-profile-runtime.js +16 -3
  63. package/lib/profiles/process-control.d.ts +18 -1
  64. package/lib/profiles/process-control.js +25 -1
  65. package/lib/routes/profiles.js +2 -1
  66. package/lib/routes/sync.js +13 -1
  67. package/lib/schema/types.d.ts +11 -0
  68. package/lib/security/redaction.js +22 -6
  69. package/lib/sync/autosync-repeat.d.ts +27 -0
  70. package/lib/sync/autosync-repeat.js +23 -0
  71. package/lib/sync/autosync-scheduler.d.ts +34 -1
  72. package/lib/sync/autosync-scheduler.js +151 -43
  73. package/lib/sync/baseline-heal.js +7 -0
  74. package/lib/sync/baseline-record.d.ts +67 -0
  75. package/lib/sync/baseline-record.js +74 -0
  76. package/lib/sync/blob-store.js +13 -0
  77. package/lib/sync/content-diff.d.ts +39 -0
  78. package/lib/sync/content-diff.js +46 -0
  79. package/lib/sync/git/git-transport.d.ts +32 -1
  80. package/lib/sync/git/git-transport.js +146 -26
  81. package/lib/sync/github-auth.d.ts +17 -1
  82. package/lib/sync/github-auth.js +37 -1
  83. package/lib/sync/merge-apply-plan.d.ts +38 -0
  84. package/lib/sync/merge-apply-plan.js +76 -0
  85. package/lib/sync/messages.d.ts +1 -0
  86. package/lib/sync/messages.js +2 -0
  87. package/lib/sync/pending-merge.d.ts +34 -0
  88. package/lib/sync/pending-merge.js +53 -0
  89. package/lib/sync/s3/s3-transport.d.ts +14 -2
  90. package/lib/sync/s3/s3-transport.js +72 -48
  91. package/lib/sync/sync-engine.d.ts +23 -40
  92. package/lib/sync/sync-engine.js +115 -132
  93. package/lib/sync/sync-history.d.ts +7 -0
  94. package/lib/sync/sync-state.d.ts +28 -0
  95. package/lib/sync/sync-state.js +20 -0
  96. package/lib/sync/transport.d.ts +12 -3
  97. package/lib/sync/transport.js +13 -4
  98. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  99. package/lib/sync/webdav/webdav-transport.js +81 -40
  100. package/lib/ui/commands.js +5 -11
  101. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  102. package/lib/ui/dsh-profiles-view.js +9 -5
  103. package/lib/ui/i18n.d.ts +2 -1
  104. package/lib/ui/i18n.js +4 -2
  105. package/lib/ui/menu-placement.js +1 -1
  106. package/lib/ui/migration-consult-view.d.ts +11 -0
  107. package/lib/ui/migration-consult-view.js +15 -0
  108. package/lib/ui/overview-view.d.ts +7 -0
  109. package/lib/ui/overview-view.js +3 -0
  110. package/lib/ui/report.d.ts +9 -0
  111. package/lib/ui/report.js +17 -4
  112. package/lib/ui/selection-model.d.ts +8 -0
  113. package/lib/ui/selection-model.js +16 -0
  114. package/lib/utils/patch-yaml.d.ts +39 -1
  115. package/lib/utils/patch-yaml.js +82 -2
  116. package/lib/utils/paths.d.ts +13 -0
  117. package/lib/utils/paths.js +35 -0
  118. package/lib/utils/workdir-lock.js +18 -3
  119. package/package.json +2 -1
  120. package/src/adapters/mcp.test.ts +29 -0
  121. package/src/adapters/mcp.ts +43 -12
  122. package/src/adapters/messages.ts +2 -0
  123. package/src/adapters/patch-key-guard.ts +29 -0
  124. package/src/adapters/plugin-data.test.ts +126 -0
  125. package/src/adapters/plugin-data.ts +97 -26
  126. package/src/adapters/plugins.test.ts +288 -0
  127. package/src/adapters/plugins.ts +141 -4
  128. package/src/cli/actions.test.ts +74 -1
  129. package/src/cli/actions.ts +27 -246
  130. package/src/cli/control-state.ts +143 -0
  131. package/src/cli/index.ts +18 -0
  132. package/src/cli/web/web.test.ts +27 -0
  133. package/src/cli/write-gates.ts +149 -0
  134. package/src/client/about/AboutPanel.tsx +7 -6
  135. package/src/client/about/release-notes-view.test.ts +17 -0
  136. package/src/client/about/release-notes-view.ts +49 -24
  137. package/src/client/chat/ChatEntryView.tsx +2 -2
  138. package/src/client/chat/rollback-entry-view.ts +6 -1
  139. package/src/client/common/CommandPalette.tsx +6 -3
  140. package/src/client/common/ConfirmDialog.tsx +29 -12
  141. package/src/client/common/ContentPicker.tsx +13 -12
  142. package/src/client/common/Modal.tsx +12 -5
  143. package/src/client/common/MoreMenu.tsx +4 -1
  144. package/src/client/common/RunsCenter.tsx +103 -32
  145. package/src/client/common/Select.tsx +2 -2
  146. package/src/client/common/floating-bounds.ts +1 -1
  147. package/src/client/common/floating-units.test.ts +1 -2
  148. package/src/client/common/plan-text-redaction.test.ts +188 -3
  149. package/src/client/common/runs-center-guard.test.ts +60 -0
  150. package/src/client/common/runs-center-view.test.ts +128 -0
  151. package/src/client/common/runs-center-view.ts +96 -0
  152. package/src/client/common/section-title-action.test.ts +66 -0
  153. package/src/client/common/ui.tsx +93 -30
  154. package/src/client/config-manager.module.css +1507 -272
  155. package/src/client/consult/ConsultCard.tsx +7 -6
  156. package/src/client/environment/EnvironmentPanel.tsx +20 -21
  157. package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
  158. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  159. package/src/client/export/ExportView.tsx +7 -16
  160. package/src/client/history/HistoryPanel.tsx +88 -28
  161. package/src/client/history/history-locales.ts +3 -3
  162. package/src/client/home/BackupScheduleCard.tsx +35 -30
  163. package/src/client/home/HomePanel.tsx +45 -10
  164. package/src/client/import/ConflictList.tsx +13 -13
  165. package/src/client/import/ForeignImportView.tsx +7 -6
  166. package/src/client/import/ImportWizardView.tsx +2 -3
  167. package/src/client/import/PathMappingForm.tsx +4 -4
  168. package/src/client/import/PathPickerDialog.tsx +2 -1
  169. package/src/client/import/import-wizard-steps.tsx +51 -39
  170. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  171. package/src/client/import/use-import-wizard-controller.ts +116 -22
  172. package/src/client/library/ArtifactRow.tsx +2 -2
  173. package/src/client/library/BackupInspectView.tsx +19 -15
  174. package/src/client/library/LibraryActions.tsx +56 -16
  175. package/src/client/library/LibraryPanel.tsx +7 -7
  176. package/src/client/library/RestorePlanView.tsx +13 -8
  177. package/src/client/locales/about.ts +0 -2
  178. package/src/client/locales/backup.ts +10 -12
  179. package/src/client/locales/common.ts +2 -0
  180. package/src/client/locales/export.ts +5 -12
  181. package/src/client/locales/foreign.ts +2 -2
  182. package/src/client/locales/import.ts +3 -2
  183. package/src/client/locales/overview.ts +4 -0
  184. package/src/client/locales/profiles.ts +32 -4
  185. package/src/client/locales/restore.ts +0 -2
  186. package/src/client/locales/sessions.ts +0 -2
  187. package/src/client/locales/shell.ts +2 -2
  188. package/src/client/market/MarketPanel.tsx +38 -20
  189. package/src/client/market/MyConfigsList.tsx +34 -32
  190. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  191. package/src/client/market/MyConfigsView.tsx +5 -5
  192. package/src/client/market/MyConfigsWizard.tsx +7 -12
  193. package/src/client/market/market-locales.ts +0 -6
  194. package/src/client/market/my-configs-split.test.ts +2 -1
  195. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  196. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  197. package/src/client/recovery/RecoveryPanel.tsx +31 -16
  198. package/src/client/recovery/RollbackCard.tsx +58 -16
  199. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  200. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  201. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  202. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  203. package/src/client/recovery/recovery-locales.ts +12 -8
  204. package/src/client/run-store.test.ts +30 -0
  205. package/src/client/run-store.ts +21 -1
  206. package/src/client/sync/AddChannelCard.tsx +65 -0
  207. package/src/client/sync/AutosyncCard.tsx +182 -108
  208. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  209. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  210. package/src/client/sync/MergePreviewView.tsx +3 -5
  211. package/src/client/sync/PushReportSections.tsx +35 -0
  212. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  213. package/src/client/sync/SyncConfirmView.tsx +3 -3
  214. package/src/client/sync/SyncLogList.tsx +16 -5
  215. package/src/client/sync/SyncPanel.tsx +153 -159
  216. package/src/client/sync/SyncProbeRow.tsx +5 -7
  217. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  218. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  219. package/src/client/sync/SyncSettingsDialog.tsx +304 -0
  220. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  221. package/src/client/sync/WorkDirCard.tsx +2 -4
  222. package/src/client/sync/config-clear-guard.test.ts +94 -0
  223. package/src/client/sync/config-clear-guard.ts +98 -0
  224. package/src/client/sync/config-dirty.test.ts +91 -0
  225. package/src/client/sync/config-dirty.ts +88 -0
  226. package/src/client/sync/history-model.test.ts +2 -0
  227. package/src/client/sync/history-model.ts +3 -0
  228. package/src/client/sync/merge-request.ts +20 -0
  229. package/src/client/sync/sync-api.ts +12 -0
  230. package/src/client/sync/sync-locales.ts +87 -47
  231. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  232. package/src/client/sync/sync-view.test.ts +20 -0
  233. package/src/client/sync/sync-view.ts +42 -4
  234. package/src/core/backup.test.ts +61 -1
  235. package/src/core/backup.ts +21 -4
  236. package/src/core/boot-rescue.test.ts +35 -0
  237. package/src/core/boot-rescue.ts +13 -2
  238. package/src/core/boot-safety.test.ts +25 -0
  239. package/src/core/boot-safety.ts +37 -2
  240. package/src/core/conflict-decisions.ts +2 -1
  241. package/src/core/exporter.ts +21 -1
  242. package/src/core/journal.test.ts +183 -0
  243. package/src/core/journal.ts +163 -25
  244. package/src/core/local-plugin-host.test.ts +68 -2
  245. package/src/core/local-plugin-host.ts +31 -4
  246. package/src/core/messages.ts +14 -0
  247. package/src/core/migration-history.test.ts +27 -0
  248. package/src/core/migration-history.ts +12 -4
  249. package/src/core/model-tools.test.ts +67 -0
  250. package/src/core/model-tools.ts +16 -4
  251. package/src/core/patch-secret-guard.test.ts +110 -0
  252. package/src/core/patch-secret-guard.ts +176 -0
  253. package/src/core/reconcile.ts +32 -4
  254. package/src/core/reinstall.ts +8 -2
  255. package/src/core/restore.ts +32 -7
  256. package/src/core/section-sanitize.ts +37 -0
  257. package/src/core/snapshot-diff.test.ts +73 -1
  258. package/src/core/snapshot-diff.ts +66 -21
  259. package/src/core/startup-barrier.test.ts +64 -0
  260. package/src/core/startup-barrier.ts +8 -2
  261. package/src/core/types.ts +27 -1
  262. package/src/core/update-check.test.ts +40 -0
  263. package/src/core/update-check.ts +53 -2
  264. package/src/foreign/claude-code.test.ts +5 -0
  265. package/src/foreign/claude-plugins.test.ts +57 -0
  266. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  267. package/src/foreign/dsh.test.ts +23 -0
  268. package/src/foreign/kernel.ts +9 -2
  269. package/src/foreign/read-claude-plugins.ts +32 -11
  270. package/src/foreign/read-dsh.ts +33 -2
  271. package/src/foreign/session-ir.test.ts +67 -0
  272. package/src/foreign/session-ir.ts +54 -14
  273. package/src/foreign/session-read.ts +23 -0
  274. package/src/index.ts +1 -1
  275. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  276. package/src/profiles/dsh-profile-io.ts +29 -0
  277. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  278. package/src/profiles/dsh-profile-manager.ts +53 -5
  279. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  280. package/src/profiles/dsh-profile-runtime.ts +17 -3
  281. package/src/profiles/process-control.test.ts +97 -0
  282. package/src/profiles/process-control.ts +28 -1
  283. package/src/routes/profiles.ts +2 -1
  284. package/src/routes/sync.ts +13 -1
  285. package/src/schema/types.ts +16 -1
  286. package/src/security/redaction.test.ts +31 -0
  287. package/src/security/redaction.ts +23 -6
  288. package/src/sync/autosync-repeat.test.ts +58 -0
  289. package/src/sync/autosync-repeat.ts +55 -0
  290. package/src/sync/autosync-scheduler.test.ts +417 -0
  291. package/src/sync/autosync-scheduler.ts +154 -41
  292. package/src/sync/baseline-heal.ts +6 -0
  293. package/src/sync/baseline-record.ts +135 -0
  294. package/src/sync/blob-store.test.ts +16 -0
  295. package/src/sync/blob-store.ts +13 -0
  296. package/src/sync/content-diff.test.ts +95 -0
  297. package/src/sync/content-diff.ts +79 -0
  298. package/src/sync/git/git-transport.test.ts +151 -4
  299. package/src/sync/git/git-transport.ts +143 -27
  300. package/src/sync/github-auth.test.ts +26 -1
  301. package/src/sync/github-auth.ts +37 -1
  302. package/src/sync/merge-apply-plan.ts +117 -0
  303. package/src/sync/messages.ts +2 -0
  304. package/src/sync/pending-merge.ts +77 -0
  305. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  306. package/src/sync/s3/s3-transport.ts +76 -42
  307. package/src/sync/sync-config.test.ts +39 -12
  308. package/src/sync/sync-device-identity.test.ts +3 -0
  309. package/src/sync/sync-engine.test.ts +465 -12
  310. package/src/sync/sync-engine.ts +130 -135
  311. package/src/sync/sync-history.ts +7 -0
  312. package/src/sync/sync-state.ts +48 -0
  313. package/src/sync/transport.test.ts +13 -1
  314. package/src/sync/transport.ts +12 -4
  315. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  316. package/src/sync/webdav/webdav-transport.ts +86 -34
  317. package/src/ui/commands.test.ts +11 -0
  318. package/src/ui/commands.ts +5 -14
  319. package/src/ui/dsh-profiles-view.test.ts +16 -0
  320. package/src/ui/dsh-profiles-view.ts +11 -5
  321. package/src/ui/i18n.ts +4 -2
  322. package/src/ui/menu-placement.ts +1 -1
  323. package/src/ui/migration-consult-view.test.ts +20 -1
  324. package/src/ui/migration-consult-view.ts +17 -0
  325. package/src/ui/overview-view.ts +10 -0
  326. package/src/ui/report.test.ts +25 -1
  327. package/src/ui/report.ts +15 -4
  328. package/src/ui/selection-model.test.ts +15 -1
  329. package/src/ui/selection-model.ts +18 -0
  330. package/src/utils/js-yaml4.d.ts +35 -0
  331. package/src/utils/patch-yaml.test.ts +207 -1
  332. package/src/utils/patch-yaml.ts +98 -2
  333. package/src/utils/paths.test.ts +14 -1
  334. package/src/utils/paths.ts +35 -0
  335. package/src/utils/workdir-lock.test.ts +69 -0
  336. package/src/utils/workdir-lock.ts +17 -3
  337. package/lib/ui/path-mapping.d.ts +0 -38
  338. package/lib/ui/path-mapping.js +0 -75
  339. package/src/client/common/InfoHint.tsx +0 -289
  340. package/src/client/common/info-hint-guard.test.ts +0 -1119
  341. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  342. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  343. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  344. package/src/ui/path-mapping.test.ts +0 -67
  345. 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 形态没有浏览器界面,只能在终端用它拉起)。 */
package/src/ui/i18n.ts CHANGED
@@ -147,7 +147,6 @@ export const uiZh = {
147
147
  'snapshots.failed': '失败',
148
148
  'snapshots.skipped': '跳过',
149
149
  'snapshots.noActions': '该快照无可恢复动作(或全部跳过)。',
150
- 'snapshots.selectHint': '选择一个快照预览其恢复计划(只读预览,不会改动任何设置):',
151
150
  'snapshots.reportTitle': '恢复报告',
152
151
  // 同步区块(sync-view)
153
152
  'sync.privateRepoHint': '安全要求:同步仓库必须为私有仓库(public 仓库会公开你的配置内容)。认证 token 仅用于仓库访问,绝不写入同步文件、提交内容或日志。',
@@ -177,6 +176,7 @@ export const uiZh = {
177
176
  'sync.neverSyncedShort': '从未同步',
178
177
  'sync.pushFailed': '推送失败',
179
178
  'sync.pushOk': '推送成功(快照 {id})',
179
+ 'sync.pushSkipped': '内容未变化,已跳过(沿用远端快照 {id})',
180
180
  'sync.conflictUnresolved': '冲突项 {id} 必须先选择解决方式(保留当前 / 使用导入)',
181
181
  'sync.pushPreviewHeadline': '将推送 {total} 个分区({changed} 个有变化)',
182
182
  'sync.pushPreviewEncrypted': '加密快照:载荷将整体加密,各分区相对基线的变化不可比对。',
@@ -266,6 +266,7 @@ export const uiZh = {
266
266
  'consult.loading': '正在生成咨询报告…',
267
267
  'diskUsage.title': '磁盘占用',
268
268
  'diskUsage.files': '{count} 个文件',
269
+ 'diskUsage.total': '合计 {size} · {files}',
269
270
  'diskUsage.refresh': '重新体检',
270
271
  'diskUsage.loading': '正在统计磁盘占用…',
271
272
  'diskUsage.unreadable': '未统计',
@@ -648,7 +649,6 @@ export const uiEn: Record<UiTextKey, string> = {
648
649
  'snapshots.failed': 'Failed',
649
650
  'snapshots.skipped': 'Skipped',
650
651
  'snapshots.noActions': 'No restorable actions for this snapshot (or all skipped).',
651
- 'snapshots.selectHint': 'Select a snapshot to preview its restore plan (read-only preview, changes nothing):',
652
652
  'snapshots.reportTitle': 'Restore Report',
653
653
  'sync.privateRepoHint': 'Security requirement: the sync repository MUST be private (a public repo would expose your configuration). The auth token is only used for repository access and is never written into sync files, commit content, or logs.',
654
654
  'sync.kind.create': 'Create',
@@ -677,6 +677,7 @@ export const uiEn: Record<UiTextKey, string> = {
677
677
  'sync.neverSyncedShort': 'Never synced',
678
678
  'sync.pushFailed': 'Push failed',
679
679
  'sync.pushOk': 'Push succeeded (snapshot {id})',
680
+ 'sync.pushSkipped': 'No content changes — skipped (reusing remote snapshot {id})',
680
681
  'sync.conflictUnresolved': 'Conflict item {id} must be resolved first (keep current / use imported)',
681
682
  'sync.pushPreviewHeadline': 'Will push {total} {total, plural, section|sections} ({changed} changed)',
682
683
  'sync.pushPreviewEncrypted': 'Encrypted snapshot: the payload is encrypted as a whole; per-section changes vs the baseline cannot be compared.',
@@ -758,6 +759,7 @@ export const uiEn: Record<UiTextKey, string> = {
758
759
  'consult.loading': 'Generating consultation report…',
759
760
  'diskUsage.title': 'Disk Usage',
760
761
  'diskUsage.files': '{count} {count, plural, file|files}',
762
+ 'diskUsage.total': 'Total {size} · {files}',
761
763
  'diskUsage.refresh': 'Re-scan',
762
764
  'diskUsage.loading': 'Measuring disk usage…',
763
765
  'diskUsage.unreadable': 'not measured',
@@ -72,7 +72,7 @@ export function placeMenu(anchor: Rect, bounds: Rect, menu: Size): MenuPlacement
72
72
  if (left + menu.width > bounds.right - MENU_EDGE) left = anchor.right - menu.width
73
73
  left = clampNumber(left, minLeft, maxLeft)
74
74
 
75
- // 垂直:下方优先;下方放不下且上方更宽裕 → 向上翻转(与 InfoHint 气泡同一判据)。
75
+ // 垂直:下方优先;下方放不下且上方更宽裕 → 向上翻转(与 Select 菜单同一判据)。
76
76
  const below = bounds.bottom - anchor.bottom - MENU_GAP - MENU_EDGE
77
77
  const above = anchor.top - bounds.top - MENU_GAP - MENU_EDGE
78
78
  const side: MenuPlacement['side'] = menu.height > below && above > below ? 'top' : 'bottom'
@@ -6,7 +6,7 @@ import assert from 'node:assert/strict';
6
6
  import { makeUiT } from './i18n.ts';
7
7
  import {
8
8
  consultView, consultVerdictBadgeKind, consultRecommendationBadgeKind,
9
- consultDimensionLabel, consultRecommendationLabel,
9
+ consultDimensionLabel, consultRecommendationLabel, consultScoreBadgeKind,
10
10
  dedupeConsultReasons, consultReasonGroups,
11
11
  } from './migration-consult-view.ts';
12
12
  import type { ConsultReport } from '../core/migration-consult.ts';
@@ -84,6 +84,25 @@ test('consult-view: verdict/recommendation badge kind 映射', () => {
84
84
  assert.equal(consultRecommendationLabel('block', t), '建议:阻止执行');
85
85
  });
86
86
 
87
+ test('consult-view: 维度分数配色按分数值派生(不跟 verdict 走)', () => {
88
+ // 稿 D-03:161-200:92/100/95 绿、82/74/60 橙 —— 分数 92 配 needs-attention 的 verdict 时
89
+ // 若沿用 badgeKind 会出现「92 分标橙」,所以按值分档。
90
+ assert.equal(consultScoreBadgeKind(100), 'ok');
91
+ assert.equal(consultScoreBadgeKind(90), 'ok');
92
+ assert.equal(consultScoreBadgeKind(89), 'warn');
93
+ assert.equal(consultScoreBadgeKind(70), 'warn');
94
+ assert.equal(consultScoreBadgeKind(69), 'error');
95
+ assert.equal(consultScoreBadgeKind(0), 'error');
96
+
97
+ const view = consultView(makeReport({
98
+ dimensions: [{ id: 'compatibility', score: 92, verdict: 'needs-attention', issues: [] }],
99
+ }), t);
100
+ const dim = view.dimensions[0];
101
+ assert.ok(dim !== undefined);
102
+ assert.equal(dim.badgeKind, 'warn');
103
+ assert.equal(dim.scoreKind, 'ok');
104
+ });
105
+
87
106
  /* ---------------- 建议依据:去重与分组 ---------------- */
88
107
 
89
108
  test('consult-reasons: dedupeConsultReasons 原文去重 + 保持首现顺序 + 丢弃空串/纯空白', () => {