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
@@ -22,6 +22,7 @@ import path from 'node:path';
22
22
 
23
23
  import { createAdapters } from '../adapters/index.ts';
24
24
  import { defaultSecretScanner } from '../core/exporter.ts';
25
+ import { sanitizeSectionData } from '../core/section-sanitize.ts';
25
26
  import { Importer } from '../core/importer.ts';
26
27
  import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.ts';
27
28
  // issue #91:只读预览与基线 hash 的口径判定(本地源插件在预览里不会被 npm pack)
@@ -60,14 +61,24 @@ import {
60
61
  import type { SessionBookkeepingResult } from './session-tombstones.ts';
61
62
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './retention-policy.ts';
62
63
  import type { RetentionPolicy } from './retention-policy.ts';
63
- import { hashSection, loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.ts';
64
+ import { hashSection, loadSyncState, resolveDeviceIdentity } from './sync-state.ts';
65
+ import {
66
+ pendingMergeFor as buildPendingMerge,
67
+ recordPendingMerge as persistPendingMerge,
68
+ writeMergeBaseline as persistMergeBaseline,
69
+ } from './pending-merge.ts';
64
70
  import type { PendingMerge, SyncState } from './sync-state.ts';
71
+ // 写基线(祖先副本 + sync-state)的实现整体下沉,引擎只做环境透传(体量棘轮 + G-44 口径集中)
72
+ import { recordBaseline as recordBaselineAt } from './baseline-record.ts';
73
+ import type { RecordBaselineOptions } from './baseline-record.ts';
74
+ // issue #140:内容判定(拉取/推送共用同一处实现,绝不各自比 id)
75
+ import { diffSnapshotContent, hashSections } from './content-diff.ts';
65
76
  import type { EncryptedCredentials, SyncProbeResult, SyncSnapshot, SyncSnapshotMeta, SyncTransport } from './transport.ts';
66
77
  import { isEncryptedSections, PROBE_UNSUPPORTED_CODE, SyncTransportError } from './transport.ts';
67
78
  import { msgOf, zhMsg } from '../core/messages.ts';
68
79
  import { engineMsg } from './messages.ts';
69
80
  import type { MsgFunc } from '../core/messages.ts';
70
- import { DEFAULT_ANCESTOR_KEEP, pruneAncestors, tryLoadAncestor, writeAncestor, writeEncryptedAncestor } from './ancestor.ts';
81
+ import { tryLoadAncestor } from './ancestor.ts';
71
82
  import type { MergePlan, MergeSectionResult } from './merge.ts';
72
83
  import { merge as mergeSections } from './merge.ts';
73
84
  import { prepareApplyBundle } from './apply-bundle.ts';
@@ -77,6 +88,7 @@ export type { MergePreview, MergePreviewConflictView, MergePreviewSectionView }
77
88
  import { gcSkipWarning, readGcSkipCode, reportGcSkipOnce } from './gc-skip.ts';
78
89
  import { classifyMergePlan } from './risk.ts';
79
90
  import type { SyncApplyPlan } from './risk.ts';
91
+ import { createMergeApplySnapshot, planMergeApply } from './merge-apply-plan.ts';
80
92
  import { registerMessageCatalog } from '../core/engine-locale.ts';
81
93
  import { createSnapshot, selectPruneCandidates } from '../core/backup.ts';
82
94
  import { rollback } from '../core/rollback.ts';
@@ -98,6 +110,7 @@ const zh = {
98
110
  'sync.sessionTombstonesInherited': '已从远端快照继承 {count} 条会话删除墓碑:删除继续跨设备传播(本机数据不动)',
99
111
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine 缺少 importer(需在 options 中注入)',
100
112
  'sync.mergePendingConflicts': '仍有 {count} 个分区未裁决({sections}):已裁决的部分已写入本机,但基线不推进,冲突下一轮会重新出现',
113
+ 'sync.mergeHeldConflicts': '有 {count} 个叶级冲突未裁决(分区:{sections}):这些项保持本机原值、未写入,其余内容已应用;确认后下一轮再合并',
101
114
  'sync.baselineRexportFailed': '写回成功但重新导出本机分区失败({sections}):无法证明基线与本机一致,本次**不记基线**(远端指针保持原值,下一轮重新合并收敛)',
102
115
  'sync.pushBaselineAdopted': '远端最新快照 {remote} 是本机上次推送的(本机基线停在 {base},上次推送在记录基线前被打断):已把它收养为基线并继续本次推送',
103
116
  'sync.pushBaselineAdoptedNoAncestor': '远端最新快照 {remote} 是本机上次推送的,但本机没有它的本地祖先副本:已收养基线(下次合并退化为两方合并,结果仍安全)',
@@ -109,6 +122,7 @@ const en: Record<keyof typeof zh, string> = {
109
122
  'sync.sessionTombstonesInherited': 'Inherited {count} session deletion tombstone(s) from the remote snapshot: deletions keep propagating across devices (local data untouched)',
110
123
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine is missing the importer (must be injected via options)',
111
124
  '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',
125
+ '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',
112
126
  '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)',
113
127
  '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',
114
128
  '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)',
@@ -266,6 +280,16 @@ export interface SyncPushReport {
266
280
  * deviceId」,别的设备推进过就仍然按冲突返回,绝不越过。
267
281
  */
268
282
  adoptedBase?: string;
283
+ /**
284
+ * issue #140:本次推送**没有产生新快照**(远端最新快照的分区内容与本次导出逐字相同)。
285
+ *
286
+ * 语义:`ok:true` + 本字段 = 「什么都没做,也不算失败」——未 upload、未建目录、未裁剪;
287
+ * 只是把基线指针**收养**到远端最新快照(`adoptedSnapshotId`),让下一轮判定有正确起点。
288
+ * GUI / 报告必须显式区分它(「内容未变化,已跳过」),不能显示成「已推送 xx」。
289
+ */
290
+ skipped?: 'unchanged';
291
+ /** issue #140:`skipped='unchanged'` 时被收养的远端快照 id(= 本次报告里的 snapshotId) */
292
+ adoptedSnapshotId?: string;
269
293
  }
270
294
 
271
295
  /** 差异报告中的单个变更项(PlanItem 摘要,不含敏感细节) */
@@ -881,9 +905,11 @@ export class SyncEngine {
881
905
  }
882
906
  warnings.push(...section.warnings);
883
907
  // includeSecrets=true:凭据值保留(随后整体加密);否则过 SecretScanner 剥离(默认安全)
908
+ // issue #136 C:与 exporter 同走 `sanitizeSectionData`(脱敏 + 归属标注一次完成),
909
+ // 否则推送载荷里没有 `redactedPaths`,目标机无从判断哪一行被剥空。
884
910
  const data = isFileSection(adapter.id) || includeSecrets
885
911
  ? section.data
886
- : this.scanner.scanAndRedact(section.data).sanitized;
912
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
887
913
  plainSections[adapter.id] = data as SectionData;
888
914
  }
889
915
 
@@ -914,6 +940,39 @@ export class SyncEngine {
914
940
  warnings.push(this.msg('sync.sessionTombstonesInherited', { count: String(bookkeeping.inherited) }));
915
941
  }
916
942
 
943
+ // issue #140:内容没变就**不新建快照**(不 upload、不建目录、不裁剪),只收养远端最新指针。
944
+ // 判据只有一处实现(content-diff.ts):远端最新快照实际携带的分区哈希 vs 本次导出。
945
+ // - force:true = 用户明确要求「就算一样也新建」(覆盖语义),跳过本判定;
946
+ // - 加密快照的 sections 恒空(transport.ts)⇒ 判定 unknown ⇒ 维持既有行为,不新增下载/解密;
947
+ // - 本轮新发现会话删除墓碑时不跳过:墓碑只随新快照的 manifest 传播,跳过等于丢掉删除。
948
+ if (!encrypted && opts.force !== true && bookkeeping.deletedNow.length === 0) {
949
+ const latest = remoteIndex.metas[remoteIndex.metas.length - 1];
950
+ const diff = diffSnapshotContent(latest, undefined, hashSections(plainSections));
951
+ if (diff.reason === 'same-content' && latest !== undefined) {
952
+ await this.recordBaseline(latest.id, plainSections, this.now().toISOString(), {
953
+ remoteSnapshotId: latest.id,
954
+ // P2:本轮内容已被远端收下(收养 = 远端最新就是本机内容)⇒ 冲突已有结论,清掉待裁决。
955
+ pendingMerge: null,
956
+ // G-44:远端观测必须是**远端快照自己**的 sections,绝不由 state.sections 反推
957
+ remoteSections: latest.sections,
958
+ ...(bookkeeping.tracked
959
+ ? { sessionUnits: bookkeeping.sessionUnits, deletedSessions: bookkeeping.tombstones }
960
+ : {}),
961
+ });
962
+ return {
963
+ ok: true,
964
+ snapshotId: latest.id,
965
+ sections: Object.keys(plainSections) as SectionId[],
966
+ warnings,
967
+ skipped: 'unchanged',
968
+ adoptedSnapshotId: latest.id,
969
+ // 0.4.1 的基线收养是独立事实:本轮可能刚收养了「本机上次被打断的推送」,
970
+ // 紧接着又判定内容一致 —— 两件事都要如实回报(否则面板看不到基线自己动过)。
971
+ ...(adopted !== undefined ? { adoptedBase: adopted } : {}),
972
+ };
973
+ }
974
+ }
975
+
917
976
  // ⑥ 设备身份(cloud-sync 借鉴项 ⑥):首次生成后持久化在 sync-state.json(已有则纯读),
918
977
  // 随 manifest 上行 → 别的设备在历史列表里能看到「这份快照是哪台机器推的」。
919
978
  const device = await resolveDeviceIdentity(this.stateDir, os.hostname(), this.fsx, this.msg);
@@ -952,6 +1011,8 @@ export class SyncEngine {
952
1011
  }
953
1012
  // ② 上传远端(传输通道负责散文件落盘 + 提交推送)
954
1013
  await this.transport.upload(snapshot);
1014
+ // issue #141:git 的 latest/ 视图只由明文快照生成(密文无明文镜像);显式告警,否则用户看到「push 成功但 latest/ 是旧内容」无从解释。
1015
+ if (encrypted && this.transport.type === 'git') warnings.push(this.msg('sync.latestSkippedEncrypted'));
955
1016
  // ②·1 裁剪远端快照:保留最新 MAX_REMOTE_SNAPSHOTS 个(含刚 push 的)。
956
1017
  // 删除失败只告警(进 warnings),不上抛 —— 不阻断 push 主流程。
957
1018
  // 放在 upload 之后(保证新快照已推送成功)与 recordBaseline 之前(先管好远端再记基线)。
@@ -967,6 +1028,11 @@ export class SyncEngine {
967
1028
  ...(bookkeeping.tracked
968
1029
  ? { sessionUnits: bookkeeping.sessionUnits, deletedSessions: bookkeeping.tombstones }
969
1030
  : {}),
1031
+ // issue #140:远端刚收下的就是这份明文 hash ⇒ 记录远端观测(下一次推送/拉取的内容判定起点)。
1032
+ // 加密快照的 sections 恒空 ⇒ 不写(指针一变就清空该字段,判定因此回落 id 比较)。
1033
+ ...(encrypted ? {} : { remoteSections: hashSections(plainSections) }),
1034
+ // P2:本机配置已经推成远端最新 ⇒ 之前的待裁决已被这次推送消解,不再挂着误导用户。
1035
+ pendingMerge: null,
970
1036
  });
971
1037
 
972
1038
  return {
@@ -1037,7 +1103,7 @@ export class SyncEngine {
1037
1103
  }
1038
1104
  const data = isFileSection(adapter.id) || includeSecrets
1039
1105
  ? section.data
1040
- : this.scanner.scanAndRedact(section.data).sanitized;
1106
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
1041
1107
  plainSections[adapter.id] = data as SectionData;
1042
1108
  counts[adapter.id] = section.counts ? Object.values(section.counts).reduce((a, b) => a + b, 0) : 0;
1043
1109
  }
@@ -1336,7 +1402,10 @@ export class SyncEngine {
1336
1402
  * 远端是否出现比本地共同祖先更新的快照(§3.2「检测到远端新快照」)。
1337
1403
  * - 远端为空 → false(无物可拉);
1338
1404
  * - 远端指针未知(lastSnapshotId='':从未同步 / 远端 id 未知)且远端非空 → true(首次可拉);
1339
- * - 否则比较远端最新快照 id 与 lastSnapshotId。
1405
+ * - 否则比较**内容**(issue #140):远端最新快照实际携带的分区哈希 vs 上次记录的远端观测。
1406
+ * 只比 id 时,任何一次新推送(哪怕分区逐字相同)都会判成「有新生」,白跑 download + 合并。
1407
+ * - 两边任一观测缺失(加密快照 sections 恒空 / 旧 state 没记过观测)⇒ 回落 id 比较,
1408
+ * 绝不把「读不到」猜成「没变」(判据与回落规则只在 content-diff.ts)。
1340
1409
  * 只读远端列表(transport.list),不做下载/合并。
1341
1410
  *
1342
1411
  * 前提:lastSnapshotId 必须是**远端**快照 id(P0-7)。旧实现把本地生成的快照 id 也写进去,
@@ -1349,10 +1418,13 @@ export class SyncEngine {
1349
1418
  async hasNewRemoteSnapshot(listed?: readonly SyncSnapshotMeta[]): Promise<boolean> {
1350
1419
  const metas = listed ?? await this.transport.list();
1351
1420
  if (metas.length === 0) return false;
1352
- const latestId = metas[metas.length - 1]!.id; // list 按 createdAt 升序 → 最新在末
1421
+ const latest = metas[metas.length - 1]!; // list 按 createdAt 升序 → 最新在末
1353
1422
  const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1354
1423
  if (state.lastSnapshotId === '') return true;
1355
- return latestId !== state.lastSnapshotId;
1424
+ const diff = diffSnapshotContent(latest, state.lastRemoteSections);
1425
+ // unknown(加密快照 / 旧 state 没有远端观测)⇒ 只能比 id:这是「读不到」的唯一退路。
1426
+ if (diff.reason === 'unknown') return latest.id !== state.lastSnapshotId;
1427
+ return diff.changed;
1356
1428
  }
1357
1429
 
1358
1430
  /**
@@ -1387,7 +1459,7 @@ export class SyncEngine {
1387
1459
  } catch {
1388
1460
  continue; // 单项导出失败不影响判定(与 push 单项跳过语义一致)
1389
1461
  }
1390
- const data = isFileSection(adapter.id) ? section.data : this.scanner.scanAndRedact(section.data).sanitized;
1462
+ const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
1391
1463
  const recorded = state.sections[adapter.id];
1392
1464
  if (recorded === undefined) return true; // 基线缺该分区 → 视为有变化
1393
1465
  if (recorded.hash !== hashSection(data as SectionData)) return true;
@@ -1504,7 +1576,7 @@ export class SyncEngine {
1504
1576
  } catch {
1505
1577
  continue;
1506
1578
  }
1507
- const data = isFileSection(adapter.id) ? section.data : this.scanner.scanAndRedact(section.data).sanitized;
1579
+ const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, this.scanner, section.data).sanitized;
1508
1580
  localSections[adapter.id] = data as SectionData;
1509
1581
  }
1510
1582
  const portableIds = this.pullSectionIds();
@@ -1694,32 +1766,20 @@ export class SyncEngine {
1694
1766
  };
1695
1767
  }
1696
1768
 
1697
- /** 组装 pendingMerge 记录:同一远端快照上的连续待裁决**保留首次时间**(界面据此讲「挂了多久」)。 */
1769
+ /** P2(2026-11-14 真机事故):自动同步撞冲突时把分区落成待裁决;实现与为什么见 pending-merge.ts。 */
1770
+ async recordPendingMerge(sections: readonly SectionId[]): Promise<PendingMerge | null> {
1771
+ const deps = { stateDir: this.stateDir, fsx: this.fsx, msg: this.msg };
1772
+ return persistPendingMerge(deps, this.lastMergedRemoteSnapshotId, sections, this.now().toISOString());
1773
+ }
1774
+
1775
+ /** 组装 pendingMerge 记录(同一远端快照上连续冲突保留首次时间);见 pending-merge.ts。 */
1698
1776
  private pendingMergeFor(state: SyncState, remoteSnapshotId: string, sections: SectionId[]): PendingMerge {
1699
- const since = state.pendingMerge !== undefined && state.pendingMerge.remoteSnapshotId === remoteSnapshotId
1700
- ? state.pendingMerge.since
1701
- : this.now().toISOString();
1702
- return { remoteSnapshotId, sections, since };
1777
+ return buildPendingMerge(state, remoteSnapshotId, sections, this.now().toISOString());
1703
1778
  }
1704
1779
 
1705
- /**
1706
- * 基线纪律的**纯状态**写入(不写祖先副本、不碰远端):仅在本机没有任何配置写入时使用。
1707
- *
1708
- * - pending 提供 → 写 pendingMerge;undefined → 清除该字段(「全部裁决完」);
1709
- * - advanceRemoteId 提供 → 把远端指针推进到该快照 id(缺省 = 保持不变)。
1710
- *
1711
- * 为什么不走 recordBaseline:那条路径会重建祖先副本并只带本次应用的分区 —— 在「没有应用任何分区」
1712
- * 或「仍有未裁决冲突」时都会把共同基线改坏(下一轮所有分区都退化成「无祖先 → 冲突」)。
1713
- */
1780
+ /** 基线纪律的纯状态写入(不碰祖先副本、不推远端);为什么不用 recordBaseline 见 pending-merge.ts。 */
1714
1781
  private async writeMergeBaseline(opts: { pending?: PendingMerge; advanceRemoteId?: string }): Promise<void> {
1715
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1716
- if (opts.pending === undefined) delete state.pendingMerge;
1717
- else state.pendingMerge = opts.pending;
1718
- if (opts.advanceRemoteId !== undefined) {
1719
- state.lastSnapshotId = opts.advanceRemoteId;
1720
- state.lastSyncAt = this.now().toISOString();
1721
- }
1722
- await saveSyncState(this.stateDir, state, this.fsx);
1782
+ await persistMergeBaseline({ stateDir: this.stateDir, fsx: this.fsx, msg: this.msg }, opts, this.now().toISOString());
1723
1783
  }
1724
1784
 
1725
1785
  /**
@@ -1741,7 +1801,7 @@ export class SyncEngine {
1741
1801
  const section = await adapter.export(this.ctx, { includeSecrets: false });
1742
1802
  out[adapter.id] = (isFileSection(adapter.id)
1743
1803
  ? section.data
1744
- : this.scanner.scanAndRedact(section.data).sanitized) as SectionData;
1804
+ : sanitizeSectionData(adapter, this.scanner, section.data).sanitized) as SectionData;
1745
1805
  } catch {
1746
1806
  return null;
1747
1807
  }
@@ -1753,89 +1813,31 @@ export class SyncEngine {
1753
1813
  * 记录祖先基线:写本地祖先副本 + 更新 sync-state(每分区 hash/updatedAt、lastSyncAt、transport、
1754
1814
  * 远端指针 lastSnapshotId、本地祖先目录名 ancestorId)+ 裁剪到 keep。
1755
1815
  *
1756
- * **两个 id 语义严格分开(P0-7),不要再混用同一个字段**:
1757
- * - `snapshotId`:本次基线的**本地**快照对象 id,同时是本地祖先副本的目录名(写入 `ancestorId`);
1758
- * - `opts.remoteSnapshotId`:该基线在**远端**对应的快照 id(写入 `lastSnapshotId`)。缺省 = snapshotId
1759
- * (push 路径两者天然相同);合并/应用路径**必须显式传**,否则 lastSnapshotId 会退化成「一个远端
1760
- * 并不存在的本地 id」→ hasNewRemoteSnapshot() 恒判「远端有新生」,每轮白跑 list + download + merge。
1761
- * 传入 `''` 表示「远端 id 未知」——宁可留空,也不要把本地 id 冒充成远端 id。
1762
- * - `opts.writeAncestor === false`:不落本地祖先副本,`ancestorId` 一并置 '' ——
1763
- * 绝不把一个本地并不存在的目录名写进状态(旧实现正是这样让下一轮 merge 直接抛错)。
1764
- * - `opts.ancestorPassword`(issue #107):祖先副本落**密文**(manifest.encrypted + 单密文载荷);
1765
- * 加密快照 push 必须传,否则下轮三方合并缺共同祖先、整分区冲突。
1766
- * - `opts.preserveAncestor === true`(合并仍有未裁决冲突):祖先副本与 ancestorId **保持不动** ——
1767
- * 共同基线必须仍是「本机与远端都认可的上一版」;拿只带本次应用分区的副本去覆盖它,会让
1768
- * 下一轮所有分区都退化成「无祖先 → 冲突」。
1769
- * - `opts.pendingMerge`(基线纪律):提供即写入;`null` = 清除该字段;缺省 = 不动(既有行为不变)。
1816
+ * 实现整体在 `baseline-record.ts`:P0-7 的两个 id 语义、G-44 的「远端观测 vs 本机观测」口径
1817
+ * 都写在那份文件头里,改这里之前先读它。引擎只把本机环境(快照目录、通道身份、时钟、文案)交出去。
1770
1818
  */
1771
1819
  async recordBaseline(
1772
1820
  snapshotId: string,
1773
- // 基线**恒为明文**(加密快照的基线 hash 也用明文算,供 hasLocalChanges 比较);
1774
- // 需要落盘副本时由 opts.ancestorPassword 决定写明文还是密文目录。
1775
1821
  sections: Partial<Record<SectionId, SectionData>>,
1776
1822
  nowIso?: string,
1777
- opts: {
1778
- writeAncestor?: boolean;
1779
- /** 提供即把祖先副本写成**密文**(密码仅本次内存使用;issue #107) */
1780
- ancestorPassword?: string;
1781
- remoteSnapshotId?: string;
1782
- /** 保留当前祖先副本与 ancestorId(缺省 false = 既有行为逐字不变) */
1783
- preserveAncestor?: boolean;
1784
- /** 待裁决冲突记录:null = 清除;缺省 = 不动该字段 */
1785
- pendingMerge?: PendingMerge | null;
1786
- /** P1-5:本轮**实际带走**的会话单元(提供即覆盖;缺省 = 保留原记录) */
1787
- sessionUnits?: string[];
1788
- /** P1-5:本轮累积的删除墓碑(提供即覆盖;缺省 = 保留原记录) */
1789
- deletedSessions?: string[];
1790
- } = {},
1823
+ opts: RecordBaselineOptions = {},
1791
1824
  ): Promise<void> {
1792
- const ts = nowIso ?? this.now().toISOString();
1793
- const preserveAncestor = opts.preserveAncestor === true;
1794
- const writesAncestorCopy = !preserveAncestor && this.localSnapshotsDir !== undefined && opts.writeAncestor !== false;
1795
- // 1) 写本地祖先副本(如有 localSnapshotsDir)。
1796
- // ancestorPassword 提供 → 落**密文**祖先副本(issue #107:加密通道也能做三方合并);
1797
- // 否则落明文散文件布局(既有行为逐字不变)。
1798
- if (writesAncestorCopy) {
1799
- const ancestorPassword = opts.ancestorPassword;
1800
- const encryptedAncestor = ancestorPassword !== undefined && ancestorPassword !== '';
1801
- const manifest: SyncSnapshot['manifest'] = {
1802
- schemaVersion: CURRENT_SCHEMA_VERSION,
1825
+ await recordBaselineAt({
1826
+ snapshotId,
1827
+ sections,
1828
+ ...(nowIso === undefined ? {} : { nowIso }),
1829
+ opts,
1830
+ env: {
1831
+ fsx: this.fsx,
1832
+ stateDir: this.stateDir,
1833
+ ...(this.localSnapshotsDir === undefined ? {} : { localSnapshotsDir: this.localSnapshotsDir }),
1803
1834
  dshVersion: this.ctx.dshVersion,
1804
1835
  platform: this.ctx.platform as Platform,
1805
- sectionIds: Object.keys(sections) as SectionId[],
1806
- containsSecrets: false,
1807
- // 记录触发通道(git/webdav),供同步历史展示「由哪个通道触发」
1808
- transport: this.transport.type,
1809
- ...(encryptedAncestor ? { encrypted: true } : {}),
1810
- };
1811
- if (encryptedAncestor) {
1812
- const encryptedSections = await encryptSectionsPayload(sections, ancestorPassword);
1813
- await writeEncryptedAncestor(this.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections: encryptedSections }, this.fsx);
1814
- } else {
1815
- await writeAncestor(this.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections }, this.fsx);
1816
- }
1817
- }
1818
- // 2) 更新 sync-state:远端指针 + 本地祖先目录名 + 每分区 hash/updatedAt + lastSyncAt + transport
1819
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1820
- state.lastSnapshotId = opts.remoteSnapshotId ?? snapshotId;
1821
- // preserveAncestor:祖先目录名一并保持不动(既不是 snapshotId,也不是 '')
1822
- if (!preserveAncestor) state.ancestorId = writesAncestorCopy ? snapshotId : '';
1823
- state.lastSyncAt = ts;
1824
- state.transport = { type: this.transport.type, ref: this.transportRef };
1825
- // 基线纪律:null = 清除(全部裁决完);undefined = 不动该字段(既有调用方零感知)
1826
- if (opts.pendingMerge === null) delete state.pendingMerge;
1827
- else if (opts.pendingMerge !== undefined) state.pendingMerge = opts.pendingMerge;
1828
- // P1-5:只在调用方明确提供时覆盖(否则保留既有记录,绝不因某条路径不跟踪而清空)
1829
- if (opts.sessionUnits !== undefined) state.sessionUnits = [...opts.sessionUnits];
1830
- if (opts.deletedSessions !== undefined) state.deletedSessions = [...opts.deletedSessions];
1831
- for (const [sid, data] of Object.entries(sections)) {
1832
- state.sections[sid as SectionId] = { hash: hashSection(data as SectionData), updatedAt: ts };
1833
- }
1834
- await saveSyncState(this.stateDir, state, this.fsx);
1835
- // 3) 裁剪祖先副本(最近 N 个);preserveAncestor 时本轮没有新副本,不参与裁剪
1836
- if (!preserveAncestor && this.localSnapshotsDir !== undefined) {
1837
- await pruneAncestors(this.localSnapshotsDir, DEFAULT_ANCESTOR_KEEP, this.fsx);
1838
- }
1836
+ transport: { type: this.transport.type, ref: this.transportRef },
1837
+ now: () => this.now(),
1838
+ msg: this.msg,
1839
+ },
1840
+ });
1839
1841
  }
1840
1842
 
1841
1843
  /**
@@ -1881,6 +1883,7 @@ export class SyncEngine {
1881
1883
  if (!this.importer) {
1882
1884
  throw new Error(this.msg('sync.applyMergePlanNoImporter'));
1883
1885
  }
1886
+ const importer = this.importer;
1884
1887
  const appliedIds: SectionId[] = apply.autoApply.map((r) => r.id);
1885
1888
  // 0) 空 autoApply:无物可应用,直接短路(不构造 ZIP、不调 Importer)
1886
1889
  if (appliedIds.length === 0) {
@@ -1906,28 +1909,22 @@ export class SyncEngine {
1906
1909
  const tempSnapshot = bundle.tempSnapshot;
1907
1910
  const zipPath = await this.snapshotToZip(tempSnapshot, this.pullSectionIds());
1908
1911
  try {
1909
- const plan = await this.importer.createImportPlan(zipPath, {
1910
- strategy: 'replace', // auto 路径:冲突已在外部分流;这里 replace = 接受导入值
1911
- resolutions: {},
1912
- // issue #45:合并路径的映射来自 merge() 记下的远端 sourceHome + 用户映射
1912
+ // issue #136 B:两趟计划 + 待裁决面(判定与理由见 `planMergeApply` 的文档注释;不再兜底 replace)。
1913
+ const { plan, heldReview, heldWarnings } = await planMergeApply({
1914
+ zipPath,
1913
1915
  pathMappings: opts.pathMappings ?? this.lastMergedPathMappings,
1916
+ appliedIds,
1917
+ createImportPlan: (zip, decisions) => importer.createImportPlan(zip, decisions),
1918
+ heldConflictMessage: (count, sections) => this.msg('sync.mergeHeldConflicts', { count: String(count), sections: sections.join(', ') }),
1914
1919
  });
1915
1920
  if (!plan.items.length) {
1916
1921
  // 没有可执行项 → 视为 ok 但空 applied
1917
1922
  return { ok: true, applied: [], restoreId: '', rolledBack: false, review: [], warnings: [] };
1918
1923
  }
1919
1924
  // 2) 兜底:先建快照(拿到 restoreId 给 UI 一键回滚用)
1920
- const store: SnapshotStore = new FileSnapshotStore({ dir: this.rollbackSnapshotsDir });
1921
- let snapshot: Snapshot | undefined;
1922
- try {
1923
- snapshot = await createSnapshot({
1924
- ctx: this.ctx,
1925
- plan,
1926
- sourceZip: zipPath,
1927
- store,
1928
- adapters: this.adapters,
1929
- });
1930
- } catch (backupErr) {
1925
+ const snap = await createMergeApplySnapshot({ ctx: this.ctx, plan, zipPath, storeDir: this.rollbackSnapshotsDir, adapters: this.adapters });
1926
+ if (!snap.ok) {
1927
+ const backupErr = snap.error;
1931
1928
  return {
1932
1929
  ok: false,
1933
1930
  applied: [],
@@ -1937,9 +1934,9 @@ export class SyncEngine {
1937
1934
  warnings: [this.msg('sync.preApplySnapshotFailed', { err: backupErr instanceof Error ? backupErr.message : String(backupErr) })],
1938
1935
  };
1939
1936
  }
1940
- // 3) 真正执行:Importer.executeImportPlan(rollbackOnError 取单一缺省 → 任一失败整体回滚)
1941
- // 自动同步路径没有密码(凭据载荷无法解密),因此恒不注入 decryptedCredentials;
1942
- // 加密快照本就不会进入自动同步(无密码无法 prepareSnapshot)。
1937
+ const { store, snapshot } = snap;
1938
+ // 3) 真正执行:rollbackOnError 取单一缺省 → 任一失败整体回滚;自动同步没有密码,
1939
+ // 恒不注入 decryptedCredentials(加密快照本就不进自动同步)。
1943
1940
  const result = await this.importer.executeImportPlan(zipPath, plan, {
1944
1941
  confirm: true,
1945
1942
  rollbackOnError: DEFAULT_ROLLBACK_ON_ERROR,
@@ -1963,13 +1960,11 @@ export class SyncEngine {
1963
1960
  rollbackFull: rb.full,
1964
1961
  };
1965
1962
  }
1966
- // 4') issue #132:跟随远端删除插件(手动与自动共享此路径)。必须在 exportAppliedSections
1967
- // 之前 —— 基线要记录「删完之后」的真实清单,否则祖先仍带着刚删的包、每轮重复提删除。
1963
+ // 4') issue #132:跟随远端删除插件(手动与自动共享此路径),必须先于基线重导出 ——
1964
+ // 基线要记录「删完之后」的真实清单,否则祖先仍带着刚删的包、每轮重复提删除。
1968
1965
  // 4'') undo 线索:删掉的插件写进本次回滚快照,恢复计划据此反向重装;记不上只告警。
1969
- const pluginStep = await applyPluginRemovalStep({
1970
- appliedIds, plan: await this.pluginRemovalPlan(), enabled: this.deletePlugins,
1971
- uninstall: (name) => this.ctx.plugins.uninstall(name), msg: this.msg,
1972
- });
1966
+ const pluginStep = await applyPluginRemovalStep({ appliedIds, plan: await this.pluginRemovalPlan(),
1967
+ enabled: this.deletePlugins, uninstall: (name) => this.ctx.plugins.uninstall(name), msg: this.msg });
1973
1968
  const undoWarnings = await recordPluginRemovalUndo({
1974
1969
  removals: pluginStep.removals, snapshotId: snapshot.id,
1975
1970
  record: store.recordPluginRemovals?.bind(store), msg: this.msg,
@@ -1987,8 +1982,8 @@ export class SyncEngine {
1987
1982
  applied: appliedIds,
1988
1983
  restoreId: snapshot.id,
1989
1984
  rolledBack: false,
1990
- review: [],
1991
- warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1985
+ review: heldReview,
1986
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, ...heldWarnings, this.msg('sync.baselineRexportFailed', { sections: appliedIds.join(', ') })],
1992
1987
  ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
1993
1988
  };
1994
1989
  }
@@ -2003,8 +1998,8 @@ export class SyncEngine {
2003
1998
  applied: appliedIds,
2004
1999
  restoreId: snapshot.id,
2005
2000
  rolledBack: false,
2006
- review: [],
2007
- warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings],
2001
+ review: heldReview,
2002
+ warnings: [...(result.warnings ?? []), ...pluginStep.warnings, ...undoWarnings, ...heldWarnings],
2008
2003
  // 删过插件必须重启(与安装同语义):报告不能只说「已应用」
2009
2004
  ...(pluginStep.removals.length === 0 ? {} : { pluginRemovals: pluginStep.removals, needsRestart: true }),
2010
2005
  };
@@ -41,6 +41,13 @@ export interface AutosyncHistoryEntry {
41
41
  pulledSnapshotId?: string;
42
42
  /** failed 时的错误摘要(脱敏) */
43
43
  error?: string;
44
+ /**
45
+ * issue #136:本轮下行的用户可见告警(被保住的脱敏叶子 / 被扣下的叶级冲突)。
46
+ * 与 status 同看:有告警就不可能是一条「纯成功、什么都做了」的记录。
47
+ */
48
+ warnings?: string[];
49
+ /** issue #136:被保留待裁决的叶级冲突所在分区。 */
50
+ heldSections?: SectionId[];
44
51
  /** 连续失败 3 次通知时间(ISO-8601 UTC) */
45
52
  notifiedAt?: string;
46
53
  /** 本次触发时的连续失败计数 */
@@ -31,6 +31,18 @@ export interface SyncSectionState {
31
31
  updatedAt: string; // ISO-8601 UTC
32
32
  }
33
33
 
34
+ /**
35
+ * 分区 id → 内容哈希(= hashSection 的结果)。
36
+ *
37
+ * 同一个形状服务两种**完全不同**的观测,调用方必须分清(G-44:
38
+ * docs/known-issues/known-gaps.md 的「祖先副本与 state.sections 一参两用」):
39
+ * - `SyncState.sections`:**本机**文件最近一次基线的内容哈希(含本机尚未推送的改动);
40
+ * - `SyncState.lastRemoteSections`:上一次**远端快照实际携带**的分区哈希(远端观测);
41
+ * - 推送前刚导出的本地哈希(content-diff.hashSections)。
42
+ * 内容判定(src/sync/content-diff.ts)只接受后两者,绝不拿 state.sections 冒充远端观测。
43
+ */
44
+ export type SectionHashes = Partial<Record<SectionId, string>>;
45
+
34
46
  /**
35
47
  * 待裁决的合并状态(基线纪律,2026-10)。
36
48
  *
@@ -92,6 +104,23 @@ export interface SyncState {
92
104
  * 让冲突在下一轮重新出现(详见 PendingMerge)。
93
105
  */
94
106
  pendingMerge?: PendingMerge;
107
+ /**
108
+ * issue #140:上一次**远端快照实际携带**的分区哈希(远端观测,不是本机观测)。
109
+ *
110
+ * 用途:拉取侧判定「远端最新快照的内容是否真的变了」——只比 id 时,任何一次新推送
111
+ * (哪怕分区逐字相同)都会判成「有新生」,白跑 download + 三方合并。
112
+ *
113
+ * 纪律(G-44):
114
+ * - 只许由「真的看到了远端快照 sections」的路径写入(推送成功 / 推送跳过收养 / 收养孤儿头 /
115
+ * 合并应用到某个远端快照之后);
116
+ * - 指针变化但本轮没有远端观测 ⇒ 必须**删除**该字段(未知 ⇒ 调用方回落 id 比较),
117
+ * 绝不保留上一份观测冒充「远端现在也是这样」;
118
+ * - 加密快照的 sections 恒为空(transport.ts)⇒ 该字段保持缺席,判定恒为 unknown。
119
+ *
120
+ * 纯可选字段:**不提升 SYNC_STATE_SCHEMA_VERSION**(旧文件缺它 → 读回形状逐键不变;
121
+ * 旧版本代码读到新文件只是忽略它)。
122
+ */
123
+ lastRemoteSections?: SectionHashes;
95
124
  }
96
125
 
97
126
  /** 文件类分区判定:{ version: 1, files: [...] }(duck-typing,与 JSON 分区区分) */
@@ -165,6 +194,21 @@ function readPendingMerge(raw: unknown): PendingMerge | undefined {
165
194
  return { remoteSnapshotId: o['remoteSnapshotId'], sections: sections as SectionId[], since: o['since'] };
166
195
  }
167
196
 
197
+ /**
198
+ * 读取「远端观测」(分区 id → hash)。
199
+ *
200
+ * 形状不符(损坏/被篡改)或为空对象 → undefined:空集合无法证伪任何内容,
201
+ * 按「没有观测」处理(调用方回落到 id 比较),绝不把空对象当成「远端什么都没有」。
202
+ */
203
+ function readSectionHashes(raw: unknown): SectionHashes | undefined {
204
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
205
+ const out: SectionHashes = {};
206
+ for (const [sid, value] of Object.entries(raw as Record<string, unknown>)) {
207
+ if (typeof value === 'string' && value !== '') out[sid as SectionId] = value;
208
+ }
209
+ return Object.keys(out).length > 0 ? out : undefined;
210
+ }
211
+
168
212
  /** 读取同步状态;文件不存在 → 返回缺省空状态(从未同步)。
169
213
  * 旧版本文件(v1/v2)→ 在内存中迁移到当前版本(见 SYNC_STATE_SUPPORTED_VERSIONS),
170
214
  * 不在磁盘上就地升级(首次 saveSyncState 时才写回新版本)。 */
@@ -220,6 +264,10 @@ export async function loadSyncState(dir: string, fsx: SnapshotFs = createSnapsho
220
264
  ...(typeof obj['deviceName'] === 'string' && obj['deviceName'] !== '' ? { deviceName: obj['deviceName'] } : {}),
221
265
  // 基线纪律:同样「写过才回填」—— 缺席 = 无待裁决冲突(旧文件读回形状逐键不变)
222
266
  ...(readPendingMerge(obj['pendingMerge']) !== undefined ? { pendingMerge: readPendingMerge(obj['pendingMerge'])! } : {}),
267
+ // issue #140:远端观测同样「写过才回填」—— 缺席/空 = 未知(判定层回落 id 比较)
268
+ ...(readSectionHashes(obj['lastRemoteSections']) !== undefined
269
+ ? { lastRemoteSections: readSectionHashes(obj['lastRemoteSections'])! }
270
+ : {}),
223
271
  };
224
272
  const t = obj['transport'];
225
273
  if (t !== undefined) {
@@ -7,7 +7,7 @@
7
7
  import test from 'node:test';
8
8
  import assert from 'node:assert/strict';
9
9
 
10
- import { classifyNetworkErrorText, computeSnapshotMeta, manifestSummaryFrom } from './transport.ts';
10
+ import { classifyNetworkErrorText, computeSnapshotMeta, isPreconditionFailedStatus, manifestSummaryFrom } from './transport.ts';
11
11
  import { hashSection } from './sync-state.ts';
12
12
  import type { ManifestSummary, SyncSnapshot, SyncTransport } from './transport.ts';
13
13
  import type { Manifest, SectionData, SectionId } from '../schema/types.ts';
@@ -130,3 +130,15 @@ test('ManifestSummary 类型形状(编译期保证 + 运行期检查)', () =
130
130
  assert.equal(s.schemaVersion, 1);
131
131
  assert.ok(Array.isArray(s.sectionIds));
132
132
  });
133
+
134
+ /* ------------------------------------------------- audit-sync sync-P6-5:条件写状态判定的单一实现 */
135
+
136
+ test('isPreconditionFailedStatus: 412 恒为并发写失败;409 仅在带条件头(guarded)时算', () => {
137
+ assert.equal(isPreconditionFailedStatus(412), true, 'WebDAV If-Match/If-None-Match 冲突 = 412');
138
+ assert.equal(isPreconditionFailedStatus(412, { guarded: false }), true);
139
+ assert.equal(isPreconditionFailedStatus(409, { guarded: true }), true, 'S3 兼容端点把条件写冲突报成 409');
140
+ assert.equal(isPreconditionFailedStatus(409), false, '无条件 409 另有含义(如 WebDAV MKCOL 缺父目录),不得当成并发写');
141
+ assert.equal(isPreconditionFailedStatus(409, { guarded: false }), false);
142
+ assert.equal(isPreconditionFailedStatus(200), false);
143
+ assert.equal(isPreconditionFailedStatus(500), false);
144
+ });
@@ -114,10 +114,18 @@ export interface SyncProbeResult {
114
114
  createdCollections?: string[];
115
115
  }
116
116
 
117
- /** 写出/删除路径的**条件写**失败(HTTP 412 Precondition Failed,或 S3 兼容端点的 409):
118
- * 远端在我读取之后被别人改过 —— 必须中止本次写入让用户重试,绝不静默覆盖。 */
119
- export function isPreconditionFailedStatus(status: number): boolean {
120
- return status === 412;
117
+ /**
118
+ * 写出/删除路径的**条件写**失败判定(两条通道共用的唯一实现处):
119
+ * - 412 Precondition Failed 恒算(If-Match / If-None-Match 的语义);
120
+ * - 409 只在**本次确实带了条件写头**时才算 —— S3 兼容端点用 409 表达「对象已存在 / 冲突」,
121
+ * 而 WebDAV 的 409(如 MKCOL 缺父目录)与无条件的 409 另有含义,绝不能吞成并发冲突。
122
+ *
123
+ * 判定通过后仍须按通道报文细分:OSS 的 409 还可能表示 FileImmutable(桶被保护),
124
+ * 那必须如实报错而不是谎称「别的设备改过索引」(见 s3-transport 的 conditionalFailure)。
125
+ */
126
+ export function isPreconditionFailedStatus(status: number, opts: { guarded?: boolean } = {}): boolean {
127
+ if (status === 412) return true;
128
+ return status === 409 && opts.guarded === true;
121
129
  }
122
130
 
123
131
  export interface SyncTransport {