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
@@ -21,6 +21,7 @@ import os from 'node:os';
21
21
  import path from 'node:path';
22
22
  import { createAdapters } from '../adapters/index.js';
23
23
  import { defaultSecretScanner } from '../core/exporter.js';
24
+ import { sanitizeSectionData } from '../core/section-sanitize.js';
24
25
  import { Importer } from '../core/importer.js';
25
26
  import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.js';
26
27
  import { isFileSection, SECTION_FILE_PREFIXES, SECTION_JSON_PATHS } from '../schema/config.js';
@@ -37,16 +38,22 @@ import { applyPluginRemovalStep, pluginRemovalPlanOf, pluginRemovalPreviewOf, re
37
38
  import { OPT_IN_SYNC_SECTIONS } from './sync-selection.js';
38
39
  import { listRemoteSnapshotIndex, planSessionBookkeeping, remoteTombstonesOf, stripTombstonedSessionsInPlace, } from './session-tombstones.js';
39
40
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './retention-policy.js';
40
- import { hashSection, loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.js';
41
+ import { hashSection, loadSyncState, resolveDeviceIdentity } from './sync-state.js';
42
+ import { pendingMergeFor as buildPendingMerge, recordPendingMerge as persistPendingMerge, writeMergeBaseline as persistMergeBaseline, } from './pending-merge.js';
43
+ // 写基线(祖先副本 + sync-state)的实现整体下沉,引擎只做环境透传(体量棘轮 + G-44 口径集中)
44
+ import { recordBaseline as recordBaselineAt } from './baseline-record.js';
45
+ // issue #140:内容判定(拉取/推送共用同一处实现,绝不各自比 id)
46
+ import { diffSnapshotContent, hashSections } from './content-diff.js';
41
47
  import { isEncryptedSections, PROBE_UNSUPPORTED_CODE, SyncTransportError } from './transport.js';
42
48
  import { msgOf, zhMsg } from '../core/messages.js';
43
49
  import { engineMsg } from './messages.js';
44
- import { DEFAULT_ANCESTOR_KEEP, pruneAncestors, tryLoadAncestor, writeAncestor, writeEncryptedAncestor } from './ancestor.js';
50
+ import { tryLoadAncestor } from './ancestor.js';
45
51
  import { merge as mergeSections } from './merge.js';
46
52
  import { prepareApplyBundle } from './apply-bundle.js';
47
53
  import { mergePreviewSectionView, previewCaliberDiffersFromExport } from './merge-preview-view.js';
48
54
  import { gcSkipWarning, readGcSkipCode, reportGcSkipOnce } from './gc-skip.js';
49
55
  import { classifyMergePlan } from './risk.js';
56
+ import { createMergeApplySnapshot, planMergeApply } from './merge-apply-plan.js';
50
57
  import { registerMessageCatalog } from '../core/engine-locale.js';
51
58
  import { createSnapshot, selectPruneCandidates } from '../core/backup.js';
52
59
  import { rollback } from '../core/rollback.js';
@@ -64,6 +71,7 @@ const zh = {
64
71
  'sync.sessionTombstonesInherited': '已从远端快照继承 {count} 条会话删除墓碑:删除继续跨设备传播(本机数据不动)',
65
72
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine 缺少 importer(需在 options 中注入)',
66
73
  'sync.mergePendingConflicts': '仍有 {count} 个分区未裁决({sections}):已裁决的部分已写入本机,但基线不推进,冲突下一轮会重新出现',
74
+ 'sync.mergeHeldConflicts': '有 {count} 个叶级冲突未裁决(分区:{sections}):这些项保持本机原值、未写入,其余内容已应用;确认后下一轮再合并',
67
75
  'sync.baselineRexportFailed': '写回成功但重新导出本机分区失败({sections}):无法证明基线与本机一致,本次**不记基线**(远端指针保持原值,下一轮重新合并收敛)',
68
76
  'sync.pushBaselineAdopted': '远端最新快照 {remote} 是本机上次推送的(本机基线停在 {base},上次推送在记录基线前被打断):已把它收养为基线并继续本次推送',
69
77
  'sync.pushBaselineAdoptedNoAncestor': '远端最新快照 {remote} 是本机上次推送的,但本机没有它的本地祖先副本:已收养基线(下次合并退化为两方合并,结果仍安全)',
@@ -74,6 +82,7 @@ const en = {
74
82
  'sync.sessionTombstonesInherited': 'Inherited {count} session deletion tombstone(s) from the remote snapshot: deletions keep propagating across devices (local data untouched)',
75
83
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine is missing the importer (must be injected via options)',
76
84
  'sync.mergePendingConflicts': '{count} section(s) still have no decision ({sections}): the decided parts were written locally, but the baseline is not advanced, so the conflicts will reappear next round',
85
+ 'sync.mergeHeldConflicts': '{count} leaf-level conflict(s) remain undecided (sections: {sections}): those items keep the local value and were not written, while the rest was applied; they merge again next round once decided',
77
86
  'sync.baselineRexportFailed': 'The write succeeded but re-exporting the local section(s) failed ({sections}): the baseline cannot be proven to match this machine, so no baseline was recorded (the remote pointer keeps its old value and the next merge converges again)',
78
87
  'sync.pushBaselineAdopted': 'The newest remote snapshot {remote} was pushed by this device (its baseline stopped at {base}: that push was interrupted before recording the baseline): the baseline has been adopted and this push continues',
79
88
  'sync.pushBaselineAdoptedNoAncestor': 'The newest remote snapshot {remote} was pushed by this device, but no local ancestor copy exists for it: the baseline has been adopted (the next merge degrades to a two-way merge, which is still safe)',
@@ -516,9 +525,11 @@ export class SyncEngine {
516
525
  }
517
526
  warnings.push(...section.warnings);
518
527
  // includeSecrets=true:凭据值保留(随后整体加密);否则过 SecretScanner 剥离(默认安全)
528
+ // issue #136 C:与 exporter 同走 `sanitizeSectionData`(脱敏 + 归属标注一次完成),
529
+ // 否则推送载荷里没有 `redactedPaths`,目标机无从判断哪一行被剥空。
519
530
  const data = isFileSection(adapter.id) || includeSecrets
520
531
  ? section.data
521
- : this.scanner.scanAndRedact(section.data).sanitized;
532
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
522
533
  plainSections[adapter.id] = data;
523
534
  }
524
535
  if (Object.keys(plainSections).length === 0) {
@@ -545,6 +556,38 @@ export class SyncEngine {
545
556
  if (bookkeeping.inherited > 0) {
546
557
  warnings.push(this.msg('sync.sessionTombstonesInherited', { count: String(bookkeeping.inherited) }));
547
558
  }
559
+ // issue #140:内容没变就**不新建快照**(不 upload、不建目录、不裁剪),只收养远端最新指针。
560
+ // 判据只有一处实现(content-diff.ts):远端最新快照实际携带的分区哈希 vs 本次导出。
561
+ // - force:true = 用户明确要求「就算一样也新建」(覆盖语义),跳过本判定;
562
+ // - 加密快照的 sections 恒空(transport.ts)⇒ 判定 unknown ⇒ 维持既有行为,不新增下载/解密;
563
+ // - 本轮新发现会话删除墓碑时不跳过:墓碑只随新快照的 manifest 传播,跳过等于丢掉删除。
564
+ if (!encrypted && opts.force !== true && bookkeeping.deletedNow.length === 0) {
565
+ const latest = remoteIndex.metas[remoteIndex.metas.length - 1];
566
+ const diff = diffSnapshotContent(latest, undefined, hashSections(plainSections));
567
+ if (diff.reason === 'same-content' && latest !== undefined) {
568
+ await this.recordBaseline(latest.id, plainSections, this.now().toISOString(), {
569
+ remoteSnapshotId: latest.id,
570
+ // P2:本轮内容已被远端收下(收养 = 远端最新就是本机内容)⇒ 冲突已有结论,清掉待裁决。
571
+ pendingMerge: null,
572
+ // G-44:远端观测必须是**远端快照自己**的 sections,绝不由 state.sections 反推
573
+ remoteSections: latest.sections,
574
+ ...(bookkeeping.tracked
575
+ ? { sessionUnits: bookkeeping.sessionUnits, deletedSessions: bookkeeping.tombstones }
576
+ : {}),
577
+ });
578
+ return {
579
+ ok: true,
580
+ snapshotId: latest.id,
581
+ sections: Object.keys(plainSections),
582
+ warnings,
583
+ skipped: 'unchanged',
584
+ adoptedSnapshotId: latest.id,
585
+ // 0.4.1 的基线收养是独立事实:本轮可能刚收养了「本机上次被打断的推送」,
586
+ // 紧接着又判定内容一致 —— 两件事都要如实回报(否则面板看不到基线自己动过)。
587
+ ...(adopted !== undefined ? { adoptedBase: adopted } : {}),
588
+ };
589
+ }
590
+ }
548
591
  // ⑥ 设备身份(cloud-sync 借鉴项 ⑥):首次生成后持久化在 sync-state.json(已有则纯读),
549
592
  // 随 manifest 上行 → 别的设备在历史列表里能看到「这份快照是哪台机器推的」。
550
593
  const device = await resolveDeviceIdentity(this.stateDir, os.hostname(), this.fsx, this.msg);
@@ -581,6 +624,9 @@ export class SyncEngine {
581
624
  }
582
625
  // ② 上传远端(传输通道负责散文件落盘 + 提交推送)
583
626
  await this.transport.upload(snapshot);
627
+ // issue #141:git 的 latest/ 视图只由明文快照生成(密文无明文镜像);显式告警,否则用户看到「push 成功但 latest/ 是旧内容」无从解释。
628
+ if (encrypted && this.transport.type === 'git')
629
+ warnings.push(this.msg('sync.latestSkippedEncrypted'));
584
630
  // ②·1 裁剪远端快照:保留最新 MAX_REMOTE_SNAPSHOTS 个(含刚 push 的)。
585
631
  // 删除失败只告警(进 warnings),不上抛 —— 不阻断 push 主流程。
586
632
  // 放在 upload 之后(保证新快照已推送成功)与 recordBaseline 之前(先管好远端再记基线)。
@@ -596,6 +642,11 @@ export class SyncEngine {
596
642
  ...(bookkeeping.tracked
597
643
  ? { sessionUnits: bookkeeping.sessionUnits, deletedSessions: bookkeeping.tombstones }
598
644
  : {}),
645
+ // issue #140:远端刚收下的就是这份明文 hash ⇒ 记录远端观测(下一次推送/拉取的内容判定起点)。
646
+ // 加密快照的 sections 恒空 ⇒ 不写(指针一变就清空该字段,判定因此回落 id 比较)。
647
+ ...(encrypted ? {} : { remoteSections: hashSections(plainSections) }),
648
+ // P2:本机配置已经推成远端最新 ⇒ 之前的待裁决已被这次推送消解,不再挂着误导用户。
649
+ pendingMerge: null,
599
650
  });
600
651
  return {
601
652
  ok: true,
@@ -664,7 +715,7 @@ export class SyncEngine {
664
715
  }
665
716
  const data = isFileSection(adapter.id) || includeSecrets
666
717
  ? section.data
667
- : this.scanner.scanAndRedact(section.data).sanitized;
718
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
668
719
  plainSections[adapter.id] = data;
669
720
  counts[adapter.id] = section.counts ? Object.values(section.counts).reduce((a, b) => a + b, 0) : 0;
670
721
  }
@@ -949,7 +1000,10 @@ export class SyncEngine {
949
1000
  * 远端是否出现比本地共同祖先更新的快照(§3.2「检测到远端新快照」)。
950
1001
  * - 远端为空 → false(无物可拉);
951
1002
  * - 远端指针未知(lastSnapshotId='':从未同步 / 远端 id 未知)且远端非空 → true(首次可拉);
952
- * - 否则比较远端最新快照 id 与 lastSnapshotId。
1003
+ * - 否则比较**内容**(issue #140):远端最新快照实际携带的分区哈希 vs 上次记录的远端观测。
1004
+ * 只比 id 时,任何一次新推送(哪怕分区逐字相同)都会判成「有新生」,白跑 download + 合并。
1005
+ * - 两边任一观测缺失(加密快照 sections 恒空 / 旧 state 没记过观测)⇒ 回落 id 比较,
1006
+ * 绝不把「读不到」猜成「没变」(判据与回落规则只在 content-diff.ts)。
953
1007
  * 只读远端列表(transport.list),不做下载/合并。
954
1008
  *
955
1009
  * 前提:lastSnapshotId 必须是**远端**快照 id(P0-7)。旧实现把本地生成的快照 id 也写进去,
@@ -963,11 +1017,15 @@ export class SyncEngine {
963
1017
  const metas = listed ?? await this.transport.list();
964
1018
  if (metas.length === 0)
965
1019
  return false;
966
- const latestId = metas[metas.length - 1].id; // list 按 createdAt 升序 → 最新在末
1020
+ const latest = metas[metas.length - 1]; // list 按 createdAt 升序 → 最新在末
967
1021
  const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
968
1022
  if (state.lastSnapshotId === '')
969
1023
  return true;
970
- return latestId !== state.lastSnapshotId;
1024
+ const diff = diffSnapshotContent(latest, state.lastRemoteSections);
1025
+ // unknown(加密快照 / 旧 state 没有远端观测)⇒ 只能比 id:这是「读不到」的唯一退路。
1026
+ if (diff.reason === 'unknown')
1027
+ return latest.id !== state.lastSnapshotId;
1028
+ return diff.changed;
971
1029
  }
972
1030
  /**
973
1031
  * 连通性探针(cloud-sync 借鉴项 ②):把当前通道的**只读**自检透出给宿主路由。
@@ -1002,7 +1060,7 @@ export class SyncEngine {
1002
1060
  catch {
1003
1061
  continue; // 单项导出失败不影响判定(与 push 单项跳过语义一致)
1004
1062
  }
1005
- const data = isFileSection(adapter.id) ? section.data : this.scanner.scanAndRedact(section.data).sanitized;
1063
+ const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
1006
1064
  const recorded = state.sections[adapter.id];
1007
1065
  if (recorded === undefined)
1008
1066
  return true; // 基线缺该分区 → 视为有变化
@@ -1122,7 +1180,7 @@ export class SyncEngine {
1122
1180
  catch {
1123
1181
  continue;
1124
1182
  }
1125
- const data = isFileSection(adapter.id) ? section.data : this.scanner.scanAndRedact(section.data).sanitized;
1183
+ const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
1126
1184
  localSections[adapter.id] = data;
1127
1185
  }
1128
1186
  const portableIds = this.pullSectionIds();
@@ -1315,33 +1373,18 @@ export class SyncEngine {
1315
1373
  pendingConflicts,
1316
1374
  };
1317
1375
  }
1318
- /** 组装 pendingMerge 记录:同一远端快照上的连续待裁决**保留首次时间**(界面据此讲「挂了多久」)。 */
1376
+ /** P2(2026-11-14 真机事故):自动同步撞冲突时把分区落成待裁决;实现与为什么见 pending-merge.ts。 */
1377
+ async recordPendingMerge(sections) {
1378
+ const deps = { stateDir: this.stateDir, fsx: this.fsx, msg: this.msg };
1379
+ return persistPendingMerge(deps, this.lastMergedRemoteSnapshotId, sections, this.now().toISOString());
1380
+ }
1381
+ /** 组装 pendingMerge 记录(同一远端快照上连续冲突保留首次时间);见 pending-merge.ts。 */
1319
1382
  pendingMergeFor(state, remoteSnapshotId, sections) {
1320
- const since = state.pendingMerge !== undefined && state.pendingMerge.remoteSnapshotId === remoteSnapshotId
1321
- ? state.pendingMerge.since
1322
- : this.now().toISOString();
1323
- return { remoteSnapshotId, sections, since };
1383
+ return buildPendingMerge(state, remoteSnapshotId, sections, this.now().toISOString());
1324
1384
  }
1325
- /**
1326
- * 基线纪律的**纯状态**写入(不写祖先副本、不碰远端):仅在本机没有任何配置写入时使用。
1327
- *
1328
- * - pending 提供 → 写 pendingMerge;undefined → 清除该字段(「全部裁决完」);
1329
- * - advanceRemoteId 提供 → 把远端指针推进到该快照 id(缺省 = 保持不变)。
1330
- *
1331
- * 为什么不走 recordBaseline:那条路径会重建祖先副本并只带本次应用的分区 —— 在「没有应用任何分区」
1332
- * 或「仍有未裁决冲突」时都会把共同基线改坏(下一轮所有分区都退化成「无祖先 → 冲突」)。
1333
- */
1385
+ /** 基线纪律的纯状态写入(不碰祖先副本、不推远端);为什么不用 recordBaseline 见 pending-merge.ts。 */
1334
1386
  async writeMergeBaseline(opts) {
1335
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1336
- if (opts.pending === undefined)
1337
- delete state.pendingMerge;
1338
- else
1339
- state.pendingMerge = opts.pending;
1340
- if (opts.advanceRemoteId !== undefined) {
1341
- state.lastSnapshotId = opts.advanceRemoteId;
1342
- state.lastSyncAt = this.now().toISOString();
1343
- }
1344
- await saveSyncState(this.stateDir, state, this.fsx);
1387
+ await persistMergeBaseline({ stateDir: this.stateDir, fsx: this.fsx, msg: this.msg }, opts, this.now().toISOString());
1345
1388
  }
1346
1389
  /**
1347
1390
  * 重新导出**已应用**的分区(F-2,2026-10):基线的唯一正确来源是「实际落地的本机内容」。
@@ -1363,7 +1406,7 @@ export class SyncEngine {
1363
1406
  const section = await adapter.export(this.ctx, { includeSecrets: false });
1364
1407
  out[adapter.id] = (isFileSection(adapter.id)
1365
1408
  ? section.data
1366
- : this.scanner.scanAndRedact(section.data).sanitized);
1409
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized);
1367
1410
  }
1368
1411
  catch {
1369
1412
  return null;
@@ -1375,78 +1418,26 @@ export class SyncEngine {
1375
1418
  * 记录祖先基线:写本地祖先副本 + 更新 sync-state(每分区 hash/updatedAt、lastSyncAt、transport、
1376
1419
  * 远端指针 lastSnapshotId、本地祖先目录名 ancestorId)+ 裁剪到 keep。
1377
1420
  *
1378
- * **两个 id 语义严格分开(P0-7),不要再混用同一个字段**:
1379
- * - `snapshotId`:本次基线的**本地**快照对象 id,同时是本地祖先副本的目录名(写入 `ancestorId`);
1380
- * - `opts.remoteSnapshotId`:该基线在**远端**对应的快照 id(写入 `lastSnapshotId`)。缺省 = snapshotId
1381
- * (push 路径两者天然相同);合并/应用路径**必须显式传**,否则 lastSnapshotId 会退化成「一个远端
1382
- * 并不存在的本地 id」→ hasNewRemoteSnapshot() 恒判「远端有新生」,每轮白跑 list + download + merge。
1383
- * 传入 `''` 表示「远端 id 未知」——宁可留空,也不要把本地 id 冒充成远端 id。
1384
- * - `opts.writeAncestor === false`:不落本地祖先副本,`ancestorId` 一并置 '' ——
1385
- * 绝不把一个本地并不存在的目录名写进状态(旧实现正是这样让下一轮 merge 直接抛错)。
1386
- * - `opts.ancestorPassword`(issue #107):祖先副本落**密文**(manifest.encrypted + 单密文载荷);
1387
- * 加密快照 push 必须传,否则下轮三方合并缺共同祖先、整分区冲突。
1388
- * - `opts.preserveAncestor === true`(合并仍有未裁决冲突):祖先副本与 ancestorId **保持不动** ——
1389
- * 共同基线必须仍是「本机与远端都认可的上一版」;拿只带本次应用分区的副本去覆盖它,会让
1390
- * 下一轮所有分区都退化成「无祖先 → 冲突」。
1391
- * - `opts.pendingMerge`(基线纪律):提供即写入;`null` = 清除该字段;缺省 = 不动(既有行为不变)。
1421
+ * 实现整体在 `baseline-record.ts`:P0-7 的两个 id 语义、G-44 的「远端观测 vs 本机观测」口径
1422
+ * 都写在那份文件头里,改这里之前先读它。引擎只把本机环境(快照目录、通道身份、时钟、文案)交出去。
1392
1423
  */
1393
- async recordBaseline(snapshotId,
1394
- // 基线**恒为明文**(加密快照的基线 hash 也用明文算,供 hasLocalChanges 比较);
1395
- // 需要落盘副本时由 opts.ancestorPassword 决定写明文还是密文目录。
1396
- sections, nowIso, opts = {}) {
1397
- const ts = nowIso ?? this.now().toISOString();
1398
- const preserveAncestor = opts.preserveAncestor === true;
1399
- const writesAncestorCopy = !preserveAncestor && this.localSnapshotsDir !== undefined && opts.writeAncestor !== false;
1400
- // 1) 写本地祖先副本(如有 localSnapshotsDir)。
1401
- // ancestorPassword 提供 → 落**密文**祖先副本(issue #107:加密通道也能做三方合并);
1402
- // 否则落明文散文件布局(既有行为逐字不变)。
1403
- if (writesAncestorCopy) {
1404
- const ancestorPassword = opts.ancestorPassword;
1405
- const encryptedAncestor = ancestorPassword !== undefined && ancestorPassword !== '';
1406
- const manifest = {
1407
- schemaVersion: CURRENT_SCHEMA_VERSION,
1424
+ async recordBaseline(snapshotId, sections, nowIso, opts = {}) {
1425
+ await recordBaselineAt({
1426
+ snapshotId,
1427
+ sections,
1428
+ ...(nowIso === undefined ? {} : { nowIso }),
1429
+ opts,
1430
+ env: {
1431
+ fsx: this.fsx,
1432
+ stateDir: this.stateDir,
1433
+ ...(this.localSnapshotsDir === undefined ? {} : { localSnapshotsDir: this.localSnapshotsDir }),
1408
1434
  dshVersion: this.ctx.dshVersion,
1409
1435
  platform: this.ctx.platform,
1410
- sectionIds: Object.keys(sections),
1411
- containsSecrets: false,
1412
- // 记录触发通道(git/webdav),供同步历史展示「由哪个通道触发」
1413
- transport: this.transport.type,
1414
- ...(encryptedAncestor ? { encrypted: true } : {}),
1415
- };
1416
- if (encryptedAncestor) {
1417
- const encryptedSections = await encryptSectionsPayload(sections, ancestorPassword);
1418
- await writeEncryptedAncestor(this.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections: encryptedSections }, this.fsx);
1419
- }
1420
- else {
1421
- await writeAncestor(this.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections }, this.fsx);
1422
- }
1423
- }
1424
- // 2) 更新 sync-state:远端指针 + 本地祖先目录名 + 每分区 hash/updatedAt + lastSyncAt + transport
1425
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1426
- state.lastSnapshotId = opts.remoteSnapshotId ?? snapshotId;
1427
- // preserveAncestor:祖先目录名一并保持不动(既不是 snapshotId,也不是 '')
1428
- if (!preserveAncestor)
1429
- state.ancestorId = writesAncestorCopy ? snapshotId : '';
1430
- state.lastSyncAt = ts;
1431
- state.transport = { type: this.transport.type, ref: this.transportRef };
1432
- // 基线纪律:null = 清除(全部裁决完);undefined = 不动该字段(既有调用方零感知)
1433
- if (opts.pendingMerge === null)
1434
- delete state.pendingMerge;
1435
- else if (opts.pendingMerge !== undefined)
1436
- state.pendingMerge = opts.pendingMerge;
1437
- // P1-5:只在调用方明确提供时覆盖(否则保留既有记录,绝不因某条路径不跟踪而清空)
1438
- if (opts.sessionUnits !== undefined)
1439
- state.sessionUnits = [...opts.sessionUnits];
1440
- if (opts.deletedSessions !== undefined)
1441
- state.deletedSessions = [...opts.deletedSessions];
1442
- for (const [sid, data] of Object.entries(sections)) {
1443
- state.sections[sid] = { hash: hashSection(data), updatedAt: ts };
1444
- }
1445
- await saveSyncState(this.stateDir, state, this.fsx);
1446
- // 3) 裁剪祖先副本(最近 N 个);preserveAncestor 时本轮没有新副本,不参与裁剪
1447
- if (!preserveAncestor && this.localSnapshotsDir !== undefined) {
1448
- await pruneAncestors(this.localSnapshotsDir, DEFAULT_ANCESTOR_KEEP, this.fsx);
1449
- }
1436
+ transport: { type: this.transport.type, ref: this.transportRef },
1437
+ now: () => this.now(),
1438
+ msg: this.msg,
1439
+ },
1440
+ });
1450
1441
  }
1451
1442
  /**
1452
1443
  * 应用自动应用计划:写本地(走 Importer.executeImportPlan 标准路径;应用前调 backup.createSnapshot 兜底);
@@ -1465,6 +1456,7 @@ export class SyncEngine {
1465
1456
  if (!this.importer) {
1466
1457
  throw new Error(this.msg('sync.applyMergePlanNoImporter'));
1467
1458
  }
1459
+ const importer = this.importer;
1468
1460
  const appliedIds = apply.autoApply.map((r) => r.id);
1469
1461
  // 0) 空 autoApply:无物可应用,直接短路(不构造 ZIP、不调 Importer)
1470
1462
  if (appliedIds.length === 0) {
@@ -1491,29 +1483,22 @@ export class SyncEngine {
1491
1483
  const tempSnapshot = bundle.tempSnapshot;
1492
1484
  const zipPath = await this.snapshotToZip(tempSnapshot, this.pullSectionIds());
1493
1485
  try {
1494
- const plan = await this.importer.createImportPlan(zipPath, {
1495
- strategy: 'replace', // auto 路径:冲突已在外部分流;这里 replace = 接受导入值
1496
- resolutions: {},
1497
- // issue #45:合并路径的映射来自 merge() 记下的远端 sourceHome + 用户映射
1486
+ // issue #136 B:两趟计划 + 待裁决面(判定与理由见 `planMergeApply` 的文档注释;不再兜底 replace)。
1487
+ const { plan, heldReview, heldWarnings } = await planMergeApply({
1488
+ zipPath,
1498
1489
  pathMappings: opts.pathMappings ?? this.lastMergedPathMappings,
1490
+ appliedIds,
1491
+ createImportPlan: (zip, decisions) => importer.createImportPlan(zip, decisions),
1492
+ heldConflictMessage: (count, sections) => this.msg('sync.mergeHeldConflicts', { count: String(count), sections: sections.join(', ') }),
1499
1493
  });
1500
1494
  if (!plan.items.length) {
1501
1495
  // 没有可执行项 → 视为 ok 但空 applied
1502
1496
  return { ok: true, applied: [], restoreId: '', rolledBack: false, review: [], warnings: [] };
1503
1497
  }
1504
1498
  // 2) 兜底:先建快照(拿到 restoreId 给 UI 一键回滚用)
1505
- const store = new FileSnapshotStore({ dir: this.rollbackSnapshotsDir });
1506
- let snapshot;
1507
- try {
1508
- snapshot = await createSnapshot({
1509
- ctx: this.ctx,
1510
- plan,
1511
- sourceZip: zipPath,
1512
- store,
1513
- adapters: this.adapters,
1514
- });
1515
- }
1516
- catch (backupErr) {
1499
+ const snap = await createMergeApplySnapshot({ ctx: this.ctx, plan, zipPath, storeDir: this.rollbackSnapshotsDir, adapters: this.adapters });
1500
+ if (!snap.ok) {
1501
+ const backupErr = snap.error;
1517
1502
  return {
1518
1503
  ok: false,
1519
1504
  applied: [],
@@ -1523,9 +1508,9 @@ export class SyncEngine {
1523
1508
  warnings: [this.msg('sync.preApplySnapshotFailed', { err: backupErr instanceof Error ? backupErr.message : String(backupErr) })],
1524
1509
  };
1525
1510
  }
1526
- // 3) 真正执行:Importer.executeImportPlan(rollbackOnError 取单一缺省 → 任一失败整体回滚)
1527
- // 自动同步路径没有密码(凭据载荷无法解密),因此恒不注入 decryptedCredentials;
1528
- // 加密快照本就不会进入自动同步(无密码无法 prepareSnapshot)。
1511
+ const { store, snapshot } = snap;
1512
+ // 3) 真正执行:rollbackOnError 取单一缺省 → 任一失败整体回滚;自动同步没有密码,
1513
+ // 恒不注入 decryptedCredentials(加密快照本就不进自动同步)。
1529
1514
  const result = await this.importer.executeImportPlan(zipPath, plan, {
1530
1515
  confirm: true,
1531
1516
  rollbackOnError: DEFAULT_ROLLBACK_ON_ERROR,
@@ -1549,13 +1534,11 @@ export class SyncEngine {
1549
1534
  rollbackFull: rb.full,
1550
1535
  };
1551
1536
  }
1552
- // 4') issue #132:跟随远端删除插件(手动与自动共享此路径)。必须在 exportAppliedSections
1553
- // 之前 —— 基线要记录「删完之后」的真实清单,否则祖先仍带着刚删的包、每轮重复提删除。
1537
+ // 4') issue #132:跟随远端删除插件(手动与自动共享此路径),必须先于基线重导出 ——
1538
+ // 基线要记录「删完之后」的真实清单,否则祖先仍带着刚删的包、每轮重复提删除。
1554
1539
  // 4'') undo 线索:删掉的插件写进本次回滚快照,恢复计划据此反向重装;记不上只告警。
1555
- const pluginStep = await applyPluginRemovalStep({
1556
- appliedIds, plan: await this.pluginRemovalPlan(), enabled: this.deletePlugins,
1557
- uninstall: (name) => this.ctx.plugins.uninstall(name), msg: this.msg,
1558
- });
1540
+ const pluginStep = await applyPluginRemovalStep({ appliedIds, plan: await this.pluginRemovalPlan(),
1541
+ enabled: this.deletePlugins, uninstall: (name) => this.ctx.plugins.uninstall(name), msg: this.msg });
1559
1542
  const undoWarnings = await recordPluginRemovalUndo({
1560
1543
  removals: pluginStep.removals, snapshotId: snapshot.id,
1561
1544
  record: store.recordPluginRemovals?.bind(store), msg: this.msg,
@@ -1573,8 +1556,8 @@ export class SyncEngine {
1573
1556
  applied: appliedIds,
1574
1557
  restoreId: snapshot.id,
1575
1558
  rolledBack: false,
1576
- review: [],
1577
- warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1559
+ review: heldReview,
1560
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, ...heldWarnings, this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1578
1561
  ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
1579
1562
  };
1580
1563
  }
@@ -1589,8 +1572,8 @@ export class SyncEngine {
1589
1572
  applied: appliedIds,
1590
1573
  restoreId: snapshot.id,
1591
1574
  rolledBack: false,
1592
- review: [],
1593
- warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings],
1575
+ review: heldReview,
1576
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, ...heldWarnings],
1594
1577
  // 删过插件必须重启(与安装同语义):报告不能只说「已应用」
1595
1578
  ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
1596
1579
  };
@@ -23,6 +23,13 @@ export interface AutosyncHistoryEntry {
23
23
  pulledSnapshotId?: string;
24
24
  /** failed 时的错误摘要(脱敏) */
25
25
  error?: string;
26
+ /**
27
+ * issue #136:本轮下行的用户可见告警(被保住的脱敏叶子 / 被扣下的叶级冲突)。
28
+ * 与 status 同看:有告警就不可能是一条「纯成功、什么都做了」的记录。
29
+ */
30
+ warnings?: string[];
31
+ /** issue #136:被保留待裁决的叶级冲突所在分区。 */
32
+ heldSections?: SectionId[];
26
33
  /** 连续失败 3 次通知时间(ISO-8601 UTC) */
27
34
  notifiedAt?: string;
28
35
  /** 本次触发时的连续失败计数 */
@@ -17,6 +17,17 @@ export interface SyncSectionState {
17
17
  hash: string;
18
18
  updatedAt: string;
19
19
  }
20
+ /**
21
+ * 分区 id → 内容哈希(= hashSection 的结果)。
22
+ *
23
+ * 同一个形状服务两种**完全不同**的观测,调用方必须分清(G-44:
24
+ * docs/known-issues/known-gaps.md 的「祖先副本与 state.sections 一参两用」):
25
+ * - `SyncState.sections`:**本机**文件最近一次基线的内容哈希(含本机尚未推送的改动);
26
+ * - `SyncState.lastRemoteSections`:上一次**远端快照实际携带**的分区哈希(远端观测);
27
+ * - 推送前刚导出的本地哈希(content-diff.hashSections)。
28
+ * 内容判定(src/sync/content-diff.ts)只接受后两者,绝不拿 state.sections 冒充远端观测。
29
+ */
30
+ export type SectionHashes = Partial<Record<SectionId, string>>;
20
31
  /**
21
32
  * 待裁决的合并状态(基线纪律,2026-10)。
22
33
  *
@@ -80,6 +91,23 @@ export interface SyncState {
80
91
  * 让冲突在下一轮重新出现(详见 PendingMerge)。
81
92
  */
82
93
  pendingMerge?: PendingMerge;
94
+ /**
95
+ * issue #140:上一次**远端快照实际携带**的分区哈希(远端观测,不是本机观测)。
96
+ *
97
+ * 用途:拉取侧判定「远端最新快照的内容是否真的变了」——只比 id 时,任何一次新推送
98
+ * (哪怕分区逐字相同)都会判成「有新生」,白跑 download + 三方合并。
99
+ *
100
+ * 纪律(G-44):
101
+ * - 只许由「真的看到了远端快照 sections」的路径写入(推送成功 / 推送跳过收养 / 收养孤儿头 /
102
+ * 合并应用到某个远端快照之后);
103
+ * - 指针变化但本轮没有远端观测 ⇒ 必须**删除**该字段(未知 ⇒ 调用方回落 id 比较),
104
+ * 绝不保留上一份观测冒充「远端现在也是这样」;
105
+ * - 加密快照的 sections 恒为空(transport.ts)⇒ 该字段保持缺席,判定恒为 unknown。
106
+ *
107
+ * 纯可选字段:**不提升 SYNC_STATE_SCHEMA_VERSION**(旧文件缺它 → 读回形状逐键不变;
108
+ * 旧版本代码读到新文件只是忽略它)。
109
+ */
110
+ lastRemoteSections?: SectionHashes;
83
111
  }
84
112
  /**
85
113
  * 分区内容 hash:
@@ -93,6 +93,22 @@ function readPendingMerge(raw) {
93
93
  return undefined;
94
94
  return { remoteSnapshotId: o['remoteSnapshotId'], sections: sections, since: o['since'] };
95
95
  }
96
+ /**
97
+ * 读取「远端观测」(分区 id → hash)。
98
+ *
99
+ * 形状不符(损坏/被篡改)或为空对象 → undefined:空集合无法证伪任何内容,
100
+ * 按「没有观测」处理(调用方回落到 id 比较),绝不把空对象当成「远端什么都没有」。
101
+ */
102
+ function readSectionHashes(raw) {
103
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
104
+ return undefined;
105
+ const out = {};
106
+ for (const [sid, value] of Object.entries(raw)) {
107
+ if (typeof value === 'string' && value !== '')
108
+ out[sid] = value;
109
+ }
110
+ return Object.keys(out).length > 0 ? out : undefined;
111
+ }
96
112
  /** 读取同步状态;文件不存在 → 返回缺省空状态(从未同步)。
97
113
  * 旧版本文件(v1/v2)→ 在内存中迁移到当前版本(见 SYNC_STATE_SUPPORTED_VERSIONS),
98
114
  * 不在磁盘上就地升级(首次 saveSyncState 时才写回新版本)。 */
@@ -148,6 +164,10 @@ export async function loadSyncState(dir, fsx = createSnapshotFs(), msg = zhMsg)
148
164
  ...(typeof obj['deviceName'] === 'string' && obj['deviceName'] !== '' ? { deviceName: obj['deviceName'] } : {}),
149
165
  // 基线纪律:同样「写过才回填」—— 缺席 = 无待裁决冲突(旧文件读回形状逐键不变)
150
166
  ...(readPendingMerge(obj['pendingMerge']) !== undefined ? { pendingMerge: readPendingMerge(obj['pendingMerge']) } : {}),
167
+ // issue #140:远端观测同样「写过才回填」—— 缺席/空 = 未知(判定层回落 id 比较)
168
+ ...(readSectionHashes(obj['lastRemoteSections']) !== undefined
169
+ ? { lastRemoteSections: readSectionHashes(obj['lastRemoteSections']) }
170
+ : {}),
151
171
  };
152
172
  const t = obj['transport'];
153
173
  if (t !== undefined) {
@@ -106,9 +106,18 @@ export interface SyncProbeResult {
106
106
  /** 本次探测顺带创建的目标目录层级(webdav 首连自建;无则为空数组) */
107
107
  createdCollections?: string[];
108
108
  }
109
- /** 写出/删除路径的**条件写**失败(HTTP 412 Precondition Failed,或 S3 兼容端点的 409):
110
- * 远端在我读取之后被别人改过 —— 必须中止本次写入让用户重试,绝不静默覆盖。 */
111
- export declare function isPreconditionFailedStatus(status: number): boolean;
109
+ /**
110
+ * 写出/删除路径的**条件写**失败判定(两条通道共用的唯一实现处):
111
+ * - 412 Precondition Failed 恒算(If-Match / If-None-Match 的语义);
112
+ * - 409 只在**本次确实带了条件写头**时才算 —— S3 兼容端点用 409 表达「对象已存在 / 冲突」,
113
+ * 而 WebDAV 的 409(如 MKCOL 缺父目录)与无条件的 409 另有含义,绝不能吞成并发冲突。
114
+ *
115
+ * 判定通过后仍须按通道报文细分:OSS 的 409 还可能表示 FileImmutable(桶被保护),
116
+ * 那必须如实报错而不是谎称「别的设备改过索引」(见 s3-transport 的 conditionalFailure)。
117
+ */
118
+ export declare function isPreconditionFailedStatus(status: number, opts?: {
119
+ guarded?: boolean;
120
+ }): boolean;
112
121
  export interface SyncTransport {
113
122
  readonly type: string;
114
123
  /** 列出远端已有快照(按 createdAt 升序) */
@@ -1,8 +1,17 @@
1
1
  import { hashSection } from './sync-state.js';
2
- /** 写出/删除路径的**条件写**失败(HTTP 412 Precondition Failed,或 S3 兼容端点的 409):
3
- * 远端在我读取之后被别人改过 —— 必须中止本次写入让用户重试,绝不静默覆盖。 */
4
- export function isPreconditionFailedStatus(status) {
5
- return status === 412;
2
+ /**
3
+ * 写出/删除路径的**条件写**失败判定(两条通道共用的唯一实现处):
4
+ * - 412 Precondition Failed 恒算(If-Match / If-None-Match 的语义);
5
+ * - 409 只在**本次确实带了条件写头**时才算 —— S3 兼容端点用 409 表达「对象已存在 / 冲突」,
6
+ * 而 WebDAV 的 409(如 MKCOL 缺父目录)与无条件的 409 另有含义,绝不能吞成并发冲突。
7
+ *
8
+ * 判定通过后仍须按通道报文细分:OSS 的 409 还可能表示 FileImmutable(桶被保护),
9
+ * 那必须如实报错而不是谎称「别的设备改过索引」(见 s3-transport 的 conditionalFailure)。
10
+ */
11
+ export function isPreconditionFailedStatus(status, opts = {}) {
12
+ if (status === 412)
13
+ return true;
14
+ return status === 409 && opts.guarded === true;
6
15
  }
7
16
  /** 默认可重试分类 = 瞬时网络故障;其余一律不重试(语义不明不冒险)。 */
8
17
  const RETRYABLE_KINDS = ['network', 'timeout', 'server'];
@@ -86,7 +86,10 @@ export declare class WebDavTransport implements SyncTransport {
86
86
  private blobsIndexUrl;
87
87
  /** 幂等创建 blobs 集合(405/301 等「已存在」语义一律视为成功,与 ensureCollection 同口径)。 */
88
88
  private ensureBlobsCollection;
89
- /** 把本次新写入的 blob 合并进远端索引(写失败 → 抛错,调用方看到的是上传失败而非静默漏记)。 */
89
+ /**
90
+ * 把本次新写入的 blob 合并进远端索引(写失败 → 抛错,调用方看到的是上传失败而非静默漏记)。
91
+ * audit-sync sync-P6-4(P3):这里的读失败必须上抛 —— 整体 PUT 会覆盖远端已登记条目。
92
+ */
90
93
  private appendBlobIndex;
91
94
  /**
92
95
  * 远端是否已存在历史内容(t66)。判据 = **blob 仓索引文件存在**:它是本通道在远端唯一的、
@@ -99,8 +102,22 @@ export declare class WebDavTransport implements SyncTransport {
99
102
  * 能力 ⇒ 无法自证),此时仍走读改写路径。C7 的伤害面(blob 被回收)恰由本判据覆盖。
100
103
  */
101
104
  private remoteHasPriorContent;
102
- /** 读取 blob 索引(哈希 → 写入时间 ms);缺失/损坏 → 空(GC 只会「少删」,不会误删)。 */
105
+ /** 读取 blob 索引(哈希 → 写入时间 ms);只读失败即抛,绝不回落成空索引,见 readBlobIndexDetailed。 */
103
106
  private readBlobIndex;
107
+ /**
108
+ * audit-sync sync-P6-4(P3):读 blob 索引的**带缺失标志**版本 —— 「读失败」与「确实没有索引」必须分开。
109
+ *
110
+ * 旧实现把 5xx / 坏 JSON / 非法结构一律当成空索引返回,紧接着 appendBlobIndex 读→合并→**整体 PUT**,
111
+ * 于是「一次读抖动」= 远端索引被覆盖成本次新增的那几条,已登记条目全丢(GC 从此看不见这些 blob,
112
+ * 等于远端漏账;再叠加 delete 的 GC 就可能删掉它们)。语义因此必须三态:
113
+ * - 404 / 405 / 501 → missing = true:**缺资源**。405/501 是部分 WebDAV 服务端表达「没有这个资源」
114
+ * 的方言(与 remoteHasPriorContent 同口径),此时确实没有索引可丢,按空处理是安全的;
115
+ * - 其它非 2xx(5xx / 403 / …)→ 抛错(可重试):读不出来就**不许**整体覆盖,让上传显式失败;
116
+ * - 200 但坏 JSON / 非对象 → 抛 protocol(不可重试):索引损坏是远端状态问题,覆盖写会抹掉残存记录。
117
+ *
118
+ * 最坏情况(可重试失败):本可跳过的 blob 被重传一遍,或本次 blob 漏登记(只占空间,不误删)。
119
+ */
120
+ private readBlobIndexDetailed;
104
121
  private writeBlobIndex;
105
122
  /**
106
123
  * blob 仓端口。`index` 是「仓里有哪些 blob」的权威视图(GC 与跳过判定同源):