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
@@ -65,6 +65,7 @@ import type { AutosyncConfig, AutosyncInterval } from './autosync-config.ts';
65
65
  import { readSyncConfigFor, isGitConfig, isWebDavConfig, isS3Config, isGistConfig, SYNC_CHANNELS } from './sync-config.ts';
66
66
  import type { SyncConfig, SyncConfigIssue, SyncTransportType } from './sync-config.ts';
67
67
  import { readSyncHistory, appendAutosyncEntry, markAutosyncNotified } from './sync-history.ts';
68
+ import { repeatHistorySignature } from './autosync-repeat.ts';
68
69
  import { classifyMergePlan } from './risk.ts';
69
70
  import type { AutosyncHistoryEntry } from './sync-history.ts';
70
71
  import type { AutosyncConflictPolicy } from './autosync-config.ts';
@@ -125,6 +126,13 @@ export interface AutosyncRunResult {
125
126
  * 「从来没配」在界面上长得一模一样,用户会反复重填同一个被拒地址。
126
127
  */
127
128
  configIssue?: string;
129
+ /**
130
+ * issue #136:本轮下行**实际产生的告警**(例:patch 行里被脱敏剥空的叶子已保留本机值、
131
+ * 叶级未裁决冲突被扣下)。非空 = 有内容没落地,终态不得再报成「成功且零告警」。
132
+ */
133
+ warnings?: string[];
134
+ /** issue #136:本轮被保留待裁决的叶级冲突所在分区(与 warnings 同源,供界面定位)。 */
135
+ heldSections?: SectionId[];
128
136
  }
129
137
 
130
138
  /**
@@ -291,6 +299,14 @@ export class AutoSyncScheduler {
291
299
  private readonly reportedConfigIssues = new Set<string>();
292
300
  private stopped = false;
293
301
  private running = false;
302
+ /**
303
+ * P1(2026-11-14 真机事故):上一轮真正落盘的历史签名,见 autosync-repeat.ts。
304
+ * 与本轮签名相同 → 这一轮不追加历史(同一结论连续播报把 200 条历史刷满、首页变成
305
+ * 每 1 分钟一条的噪音);但 lastRunAt / lastRunStatus / 跳过计数仍逐轮刷新。
306
+ */
307
+ private repeatSignature: string | null = null;
308
+ /** 本轮历史是否被压掉 —— writeFinalConfig 据此保留上一条真记录的 lastRunHistoryId。 */
309
+ private historyDeduped = false;
294
310
 
295
311
  constructor(opts: AutoSyncSchedulerOptions) {
296
312
  this.syncDir = opts.syncDir;
@@ -327,6 +343,16 @@ export class AutoSyncScheduler {
327
343
  channel: SyncTransportType,
328
344
  entry: AutosyncHistoryEntry & { forced?: boolean; configIssue?: string },
329
345
  ): Promise<void> {
346
+ const signature = repeatHistorySignature(channel, entry);
347
+ if (signature !== null && signature === this.repeatSignature) {
348
+ // 同一状态的第 N 轮(典型:远端快照一直比基线新,60s 轮询每轮都撞同一份冲突)。
349
+ // 不写 sync-history、也不写首页统一历史;但这一轮仍要刷新「上次运行」,
350
+ // 否则界面会停在几十分钟前的 lastRunAt,用户以为自动同步停了。
351
+ this.historyDeduped = true;
352
+ return;
353
+ }
354
+ this.repeatSignature = signature;
355
+ this.historyDeduped = false;
330
356
  await this.appendHistoryFn({ ...entry, transport: channel });
331
357
  }
332
358
 
@@ -404,32 +430,42 @@ export class AutoSyncScheduler {
404
430
  });
405
431
  }
406
432
 
407
- /** 兜底间隔定时器:每个 enabled 通道按各自 interval 排一次性定时器,触发后只重排自己。 */
433
+ /**
434
+ * 兜底间隔定时器:每个 enabled 通道按各自 interval 排一次性定时器,触发后**只重排自己**。
435
+ *
436
+ * 早期实现是「清掉全部通道再统一重排」:webdav 5m 每跑一轮就把 git 30m 的定时器清掉重排,
437
+ * 30m 永远等不到 → 纯定时器模式下慢通道永久饥饿(审计 P5-1,虚拟时钟 180min 实测 git 只跑 1 次)。
438
+ */
408
439
  private scheduleIntervalTimers(): void {
409
440
  for (const timer of this.timers.values()) this.clearTimer(timer);
410
441
  this.timers.clear();
411
442
  // 通道清单唯一来源 = SYNC_CHANNELS(此前同一数组在本文件写了两遍:漏改一处即某通道永不排期)
412
- const channels = SYNC_CHANNELS;
413
- for (const channel of channels) {
414
- void this.readConfig(channel).then((cfg) => {
415
- if (this.stopped || !cfg.enabled) return;
416
- const ms = intervalToMs(cfg.interval);
417
- const timer = this.setTimer(() => {
418
- // 一次性定时器:触发后立即从表移除,避免 reload() 清理到已失效的句柄
419
- this.timers.delete(channel);
420
- if (this.stopped) return;
421
- void this.runOnce(channel, { reason: 'interval' })
422
- .catch((err) => {
423
- this.host.log.error(`自动同步定时触发失败(${channel})`, { error: err instanceof Error ? err.message : String(err) });
424
- })
425
- .then(() => {
426
- // 只重排 interval 定时器(远端轮询有自己的节奏,绝不互相重置)
427
- if (!this.stopped) this.scheduleIntervalTimers();
428
- });
429
- }, ms);
430
- this.timers.set(channel, timer);
431
- }).catch(() => { /* 读配置失败静默 */ });
432
- }
443
+ for (const channel of SYNC_CHANNELS) this.scheduleChannelTimer(channel);
444
+ }
445
+
446
+ /** 单个通道的一次性 interval 排期(触发后只重排这一个通道)。 */
447
+ private scheduleChannelTimer(channel: SyncTransportType): void {
448
+ const existing = this.timers.get(channel);
449
+ if (existing !== undefined) this.clearTimer(existing);
450
+ this.timers.delete(channel);
451
+ void this.readConfig(channel).then((cfg) => {
452
+ if (this.stopped || !cfg.enabled) return;
453
+ const ms = intervalToMs(cfg.interval);
454
+ const timer = this.setTimer(() => {
455
+ // 一次性定时器:触发后立即从表移除,避免 reload() 清理到已失效的句柄
456
+ this.timers.delete(channel);
457
+ if (this.stopped) return;
458
+ void this.runOnce(channel, { reason: 'interval' })
459
+ .catch((err) => {
460
+ this.host.log.error(`自动同步定时触发失败(${channel})`, { error: err instanceof Error ? err.message : String(err) });
461
+ })
462
+ .then(() => {
463
+ // 只重排自己的 interval 定时器(远端轮询有自己的节奏,别的通道也不得被本通道重置)
464
+ if (!this.stopped) this.scheduleChannelTimer(channel);
465
+ });
466
+ }, ms);
467
+ this.timers.set(channel, timer);
468
+ }).catch(() => { /* 读配置失败静默 */ });
433
469
  }
434
470
 
435
471
  /**
@@ -653,7 +689,12 @@ export class AutoSyncScheduler {
653
689
  try {
654
690
  // 锁内重跑一次检测:预检到写入之间可能被别的进程推进(远端新快照 / 本机配置改动),
655
691
  // 拿过期结论去写等于覆盖别人的成果。无锁环境(测试)直接用预检结果 —— 同一份数据,没有竞态。
656
- const phase = releaseLock === null ? preflight : await this.detectPhase(channel, cfg, nowIso, historyId);
692
+ // P0(2026-11-14 真机事故):锁内重跑必须与预检同口径传 localCheck。
693
+ // 此前这里漏传 → 60s 远端轮询在锁内又跑了一遍全量本地导出(plugins 的 npm pack,
694
+ // 实测单插件 44.7s/轮),预检省下的开销全被这一步还回去。
695
+ const phase = releaseLock === null
696
+ ? preflight
697
+ : await this.detectPhase(channel, cfg, nowIso, historyId, { localCheck: opts.reason !== 'remote-poll' });
657
698
  if (phase.kind === 'skip') return phase.result;
658
699
  const { engine, remoteNew, localDirty, firstRun } = phase;
659
700
 
@@ -667,6 +708,12 @@ export class AutoSyncScheduler {
667
708
  * 真机现场「推本机配置当备份」这条链路被远端冲突连续阻塞,用户却只看到 skipped/conflict。
668
709
  */
669
710
  let conflictedSections: SectionId[] = [];
711
+ //
712
+ // issue #136:Phase B 的「成功但没全写进去」必须能被看见 —— 旧实现只看 applyReport.ok,
713
+ // ok 时把 warnings / 待裁决项整包丢掉,于是「patch 行被剥空→守卫保留本机」与
714
+ // 「叶级冲突被扣下」都表现为一轮干净的成功。
715
+ let downlinkWarnings: string[] = [];
716
+ let heldLeafSections: SectionId[] = [];
670
717
 
671
718
  // Phase A: pull 合并(下载)—— 仅当远端有新快照才拉取(§3.2)。
672
719
  if (remoteNew) {
@@ -727,6 +774,8 @@ export class AutoSyncScheduler {
727
774
  })).result as import('./sync-engine.ts').ApplyReport
728
775
  : await rawApply();
729
776
  appliedSections = applyReport.applied as SectionId[];
777
+ downlinkWarnings = applyReport.warnings;
778
+ heldLeafSections = [...new Set(applyReport.review.map((r) => r.sectionId as SectionId))];
730
779
  if (!applyReport.ok) {
731
780
  const error = applyReport.warnings.join('; ') || engineMsg('sync.autosyncApplyMergeFailed');
732
781
  const result: AutosyncRunResult = {
@@ -779,12 +828,18 @@ export class AutoSyncScheduler {
779
828
  // 绝不记 failed(那会累加连续失败计数并对用户发通知,把「需要用『检查远程合并』处理」
780
829
  // 谎报成「同步坏了」);错误摘要保留引擎给出的说明(用户能看见到底为什么没推上去)。
781
830
  const message = pushReport.message ?? engineMsg('sync.autosyncPushFailed');
831
+ // issue #136:下行自身的告警/待裁决与「推送被冲突挡下」合并进同一条记录,
832
+ // 不因上行受阻就把下行的事实抹掉。
833
+ const blockedConflicted = [...new Set([...conflictedSections, ...heldLeafSections])];
834
+ const blockedDegraded = downlinkWarnings.length > 0 || heldLeafSections.length > 0;
782
835
  const conflictResult: AutosyncRunResult = {
783
- status: conflictedSections.length > 0 ? 'partial' : 'skipped',
836
+ status: blockedConflicted.length > 0 || blockedDegraded ? 'partial' : 'skipped',
784
837
  direction: appliedSections.length ? 'both' : 'push',
785
838
  skipReason: 'conflict', error: message, historyId,
786
839
  appliedSections,
787
- ...(conflictedSections.length > 0 ? { conflictedSections } : {}),
840
+ ...(blockedConflicted.length > 0 ? { conflictedSections: blockedConflicted } : {}),
841
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
842
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
788
843
  consecutiveFailures: 0,
789
844
  ...forcedMark,
790
845
  };
@@ -792,10 +847,14 @@ export class AutoSyncScheduler {
792
847
  direction: appliedSections.length ? 'both' : 'push', status: conflictResult.status,
793
848
  skipReason: 'conflict', error: message,
794
849
  appliedSections,
795
- ...(conflictedSections.length > 0 ? { conflictedSections } : {}),
850
+ ...(blockedConflicted.length > 0 ? { conflictedSections: blockedConflicted } : {}),
851
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
852
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
796
853
  createdAt: nowIso, failureCountAtRun: 0,
797
854
  ...forcedMark,
798
855
  });
856
+ // 冲突分区落成待裁决(P2):首页与同步页据此给出裁决入口。
857
+ await this.recordPendingMerge(engine, conflictedSections);
799
858
  await this.writeFinalConfig(cfg, conflictResult, nowIso, historyId, channel);
800
859
  return conflictResult;
801
860
  }
@@ -835,21 +894,38 @@ export class AutoSyncScheduler {
835
894
  // 如实记一条 skipReason,让历史与首页能说清「这次推上去之前先修好了基线」,
836
895
  // 而不是让用户以为又发生了一次莫名冲突。冲突原因优先(真有冲突时更该被看见)。
837
896
  const adoptedReason = pushReport.adoptedBase !== undefined ? ('baseline-adopted' as const) : undefined;
897
+ // issue #136:下行有告警 / 有待裁决叶级项 → 终态只能是 partial。
898
+ // 「推送成功」不能替下行的未完成背书:用户会从 success 得出「两端一样了」,而实际上
899
+ // 有些叶子被有意扣下(保留本机 / 等待裁决)。
900
+ // 两类降级必须分开说:只有「叶级冲突被扣下」才是冲突待裁决;
901
+ // 纯告警(插件没装上、undo 有残留等)与冲突无关,套上 'conflict' 会让
902
+ // 界面上出现「跳过原因:冲突」「另有 N 个分区待确认」,而 conflictedSections 是空的。
903
+ const heldDegraded = heldLeafSections.length > 0;
904
+ const degraded = downlinkWarnings.length > 0 || heldDegraded;
905
+ const finalPartial = partial || degraded;
906
+ const finalSkipReason = skipReason
907
+ ?? (heldDegraded ? ('conflict' as const) : degraded ? ('warning' as const) : undefined);
908
+ // 扣下的叶级冲突所在分区也要出现在「待处理分区」里(与分区级冲突合并去重)
909
+ const finalConflicted = [...new Set([...reportedConflicted, ...heldLeafSections])];
838
910
  const result: AutosyncRunResult = {
839
- status: partial ? 'partial' : 'success',
911
+ status: finalPartial ? 'partial' : 'success',
840
912
  direction: appliedSections.length ? 'both' : 'push',
841
913
  appliedSections, pushedSnapshotId: pushReport.snapshotId, historyId,
842
- ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
843
- ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
914
+ ...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
915
+ ...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
916
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
917
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
844
918
  consecutiveFailures: 0,
845
919
  ...forcedMark,
846
920
  };
847
921
  await this.appendHistory(channel, {
848
922
  direction: appliedSections.length ? 'both' : 'push',
849
- status: partial ? 'partial' : 'success',
923
+ status: finalPartial ? 'partial' : 'success',
850
924
  appliedSections, pushedSnapshotId: pushReport.snapshotId,
851
- ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
852
- ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
925
+ ...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
926
+ ...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
927
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
928
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
853
929
  createdAt: nowIso, failureCountAtRun: 0,
854
930
  ...forcedMark,
855
931
  });
@@ -875,29 +951,46 @@ export class AutoSyncScheduler {
875
951
 
876
952
  // 本轮下行被冲突挡下、且没有可上行内容(startup 变体 / 本地无改动)→ 如实 skipped/conflict。
877
953
  if (conflictedSections.length > 0) {
954
+ // issue #136:被扣下的叶级冲突也算「待处理分区」(与分区级冲突同列)。
955
+ const skipConflicted = [...new Set([...conflictedSections, ...heldLeafSections])];
878
956
  const conflictResult: AutosyncRunResult = {
879
957
  status: 'skipped', direction: 'pull', skipReason: 'conflict',
880
- conflictedSections, historyId, consecutiveFailures: 0,
958
+ conflictedSections: skipConflicted, historyId, consecutiveFailures: 0,
959
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
960
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
881
961
  };
882
962
  await this.appendHistory(channel, {
883
963
  direction: 'pull', status: 'skipped', skipReason: 'conflict',
884
- conflictedSections, createdAt: nowIso, failureCountAtRun: 0,
964
+ conflictedSections: skipConflicted, createdAt: nowIso, failureCountAtRun: 0,
965
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
966
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
885
967
  });
968
+ await this.recordPendingMerge(engine, conflictedSections);
886
969
  await this.writeFinalConfig(cfg, conflictResult, nowIso, historyId, channel);
887
970
  return conflictResult;
888
971
  }
889
972
 
890
973
  // startup 变体 / 仅远端合并:只做 pull 合并(不上传),或远端无新生且本地无改动(已在上方 upToDate 短路上)。
974
+ // issue #136:纯下行的告警/待裁决同样算「没全做完」—— 终态不得写成 success。
975
+ const degraded = downlinkWarnings.length > 0 || heldLeafSections.length > 0;
976
+ const pulledConflicted = [...new Set([...deferredSections, ...heldLeafSections])];
977
+ const pullSkipReason = !degraded && appliedSections.length === 0
978
+ ? ('unchanged' as const)
979
+ : degraded ? ('conflict' as const) : undefined;
891
980
  const result: AutosyncRunResult = {
892
- status: 'success', direction: 'pull', appliedSections,
893
- ...(appliedSections.length === 0 ? { skipReason: 'unchanged' as const } : {}),
894
- ...(deferredSections.length > 0 ? { conflictedSections: deferredSections } : {}),
981
+ status: degraded ? 'partial' : 'success', direction: 'pull', appliedSections,
982
+ ...(pullSkipReason !== undefined ? { skipReason: pullSkipReason } : {}),
983
+ ...(pulledConflicted.length > 0 ? { conflictedSections: pulledConflicted } : {}),
984
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
985
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
895
986
  historyId, consecutiveFailures: 0,
896
987
  };
897
988
  await this.appendHistory(channel, {
898
- direction: 'pull', status: 'success', appliedSections,
899
- ...(appliedSections.length === 0 ? { skipReason: 'unchanged' as const } : {}),
900
- ...(deferredSections.length > 0 ? { conflictedSections: deferredSections } : {}),
989
+ direction: 'pull', status: degraded ? 'partial' : 'success', appliedSections,
990
+ ...(pullSkipReason !== undefined ? { skipReason: pullSkipReason } : {}),
991
+ ...(pulledConflicted.length > 0 ? { conflictedSections: pulledConflicted } : {}),
992
+ ...(downlinkWarnings.length > 0 ? { warnings: downlinkWarnings } : {}),
993
+ ...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
901
994
  createdAt: nowIso, failureCountAtRun: 0,
902
995
  });
903
996
  await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
@@ -1044,6 +1137,25 @@ export class AutoSyncScheduler {
1044
1137
  return { kind: 'work', engine, remoteNew, localDirty, firstRun };
1045
1138
  }
1046
1139
 
1140
+ /**
1141
+ * P2(2026-11-14 真机事故):把「本轮被冲突挡下的分区」写进 sync-state.pendingMerge。
1142
+ *
1143
+ * 过去自动同步只在历史里留一句「冲突」,sync-state 里没有可挂入口的持久对象 ——
1144
+ * 首页「待裁决」徽章于是只有颜色没有去处,用户点不动、也不知道该去哪裁决。
1145
+ * 这里由引擎按**本轮实际合并过的远端快照 id** 落 pendingMerge(同远端快照连续冲突保留首次 since),
1146
+ * 界面据 /sync/status 的 pendingMerge 显示待裁决分区,首页那一行据此跳到同步页。
1147
+ *
1148
+ * 尽力而为:写待裁决失败绝不能把「远端有冲突」这一事实变成 failed(那会累加连续失败计数)。
1149
+ */
1150
+ private async recordPendingMerge(engine: SyncEngine, sections: SectionId[]): Promise<void> {
1151
+ if (sections.length === 0) return;
1152
+ try {
1153
+ await engine.recordPendingMerge(sections);
1154
+ } catch (err) {
1155
+ this.host.log.warn(`自动同步待裁决分区未能落盘:${err instanceof Error ? err.message : String(err)}`);
1156
+ }
1157
+ }
1158
+
1047
1159
  private async writeFinalConfig(
1048
1160
  base: AutosyncConfig,
1049
1161
  result: AutosyncRunResult,
@@ -1061,7 +1173,8 @@ export class AutoSyncScheduler {
1061
1173
  lastRunAt: nowIso,
1062
1174
  lastRunStatus: result.status,
1063
1175
  consecutiveFailures: result.consecutiveFailures,
1064
- lastRunHistoryId: historyId,
1176
+ // 历史被压掉的轮次没有新记录 id —— 保留上一条真记录的 id,绝不指向不存在的条目。
1177
+ lastRunHistoryId: this.historyDeduped ? (base.lastRunHistoryId ?? historyId) : historyId,
1065
1178
  lastRunMessage: result.error ?? '',
1066
1179
  lastRunSkipReason: skipReason,
1067
1180
  lastRunSkipCount: skipCount,
@@ -18,6 +18,7 @@ import type { MsgFunc } from '../core/messages.ts';
18
18
  import { joinFs } from './fs.ts';
19
19
  import type { SnapshotFs } from './fs.ts';
20
20
  import { loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.ts';
21
+ import type { SectionHashes } from './sync-state.ts';
21
22
  import type { SyncSnapshotMeta } from './transport.ts';
22
23
 
23
24
  export interface AdoptOwnRemoteHeadOptions {
@@ -64,6 +65,11 @@ export async function adoptOwnRemoteHead(opts: AdoptOwnRemoteHeadOptions): Promi
64
65
  if (typeof hash !== 'string' || hash === '') continue;
65
66
  state.sections[sid as SectionId] = { hash, updatedAt: meta.createdAt };
66
67
  }
68
+ // issue #140(G-44):被收养的快照自己就是「远端当前观测」——它的 sections 记进独立字段。
69
+ // 空对象(加密快照)⇒ 删除观测:判定层因此回落 id 比较,绝不拿 state.sections 顶上。
70
+ const remoteHashes: SectionHashes = { ...meta.sections };
71
+ if (Object.keys(remoteHashes).length > 0) state.lastRemoteSections = remoteHashes;
72
+ else delete state.lastRemoteSections;
67
73
  state.transport = opts.transport;
68
74
  await saveSyncState(opts.stateDir, state, opts.fsx);
69
75
  opts.warnings.push(opts.msg(ancestorKnown ? 'sync.pushBaselineAdopted' : 'sync.pushBaselineAdoptedNoAncestor', {
@@ -0,0 +1,135 @@
1
+ /**
2
+ * m-sync-flow:写基线的唯一实现(本地祖先副本 + sync-state)。
3
+ *
4
+ * 为什么单独成模块:这段逻辑是「祖先副本布局 + 远端指针 + 每分区 hash + 裁剪」的完整落盘决策,
5
+ * 不需要引擎的任何其他状态(只吃快照目录、通道身份与时间);留在 SyncEngine 里会顶穿体量棘轮。
6
+ *
7
+ * **两个 id 语义严格分开(P0-7),不要再混用同一个字段**:
8
+ * - `snapshotId`:本次基线的**本地**快照对象 id,同时是本地祖先副本的目录名(写入 `ancestorId`);
9
+ * - `opts.remoteSnapshotId`:该基线在**远端**对应的快照 id(写入 `lastSnapshotId`)。缺省 = snapshotId
10
+ * (push 路径两者天然相同);合并/应用路径**必须显式传**,否则 lastSnapshotId 会退化成「一个远端
11
+ * 并不存在的本地 id」→ hasNewRemoteSnapshot() 恒判「远端有新生」,每轮白跑 list + download + merge。
12
+ * 传入 `''` 表示「远端 id 未知」——宁可留空,也不要把本地 id 冒充成远端 id。
13
+ *
14
+ * **issue #140 / G-44**:`opts.remoteSections` 是**远端观测**(远端快照自己携带的分区哈希),
15
+ * 与传入的 `sections`(本机观测,用来算 hasLocalChanges 的基线)是两个不同来源。
16
+ * 早先的事故正是「一参两用」:拿本机 hash 当远端现状,判定就永远自洽、永远看不出远端真的变了。
17
+ */
18
+ import type { Platform, SectionData, SectionId } from '../schema/types.ts';
19
+ import type { MsgFunc } from '../core/messages.ts';
20
+ import { CURRENT_SCHEMA_VERSION } from '../schema/versions.ts';
21
+ import { DEFAULT_ANCESTOR_KEEP, pruneAncestors, writeAncestor, writeEncryptedAncestor } from './ancestor.ts';
22
+ import type { SnapshotFs } from './fs.ts';
23
+ import { encryptSectionsPayload } from './snapshot-crypto.ts';
24
+ import { hashSection, loadSyncState, saveSyncState } from './sync-state.ts';
25
+ import type { PendingMerge, SectionHashes } from './sync-state.ts';
26
+ import type { SyncSnapshot } from './transport.ts';
27
+
28
+ export interface RecordBaselineOptions {
29
+ writeAncestor?: boolean;
30
+ /** 提供即把祖先副本写成**密文**(密码仅本次内存使用;issue #107) */
31
+ ancestorPassword?: string;
32
+ remoteSnapshotId?: string;
33
+ /** 保留当前祖先副本与 ancestorId(缺省 false = 既有行为逐字不变) */
34
+ preserveAncestor?: boolean;
35
+ /** 待裁决冲突记录:null = 清除;缺省 = 不动该字段 */
36
+ pendingMerge?: PendingMerge | null;
37
+ /** P1-5:本轮**实际带走**的会话单元(提供即覆盖;缺省 = 保留原记录) */
38
+ sessionUnits?: string[];
39
+ /** P1-5:本轮累积的删除墓碑(提供即覆盖;缺省 = 保留原记录) */
40
+ deletedSessions?: string[];
41
+ /**
42
+ * issue #140:本次基线对应的**远端观测**(远端快照实际携带的分区哈希,G-44)。
43
+ *
44
+ * - 提供且非空 ⇒ 原样记录(只允许来自「真的看到了远端 sections」的调用点);
45
+ * - 提供但为空(加密快照)或未提供 ⇒ 指针若发生变化则**删除**既有观测(未知 ⇒ 判定回落 id);
46
+ * - 指针未变(preserveAncestor 的待裁决冲突)⇒ 保留既有观测(远端没动,观测仍成立)。
47
+ * 绝不允许由传入的 `sections`(本机观测)推导。
48
+ */
49
+ remoteSections?: SectionHashes;
50
+ }
51
+
52
+ /** 落盘所需的环境(引擎逐字段透传;此处不持有引擎实例)。 */
53
+ export interface RecordBaselineEnv {
54
+ fsx: SnapshotFs;
55
+ stateDir: string;
56
+ localSnapshotsDir?: string;
57
+ dshVersion: string;
58
+ platform: Platform;
59
+ transport: { type: string; ref: string };
60
+ now: () => Date;
61
+ msg: MsgFunc;
62
+ }
63
+
64
+ export interface RecordBaselineInput {
65
+ snapshotId: string;
66
+ /** 基线**恒为明文**(加密快照的基线 hash 也用明文算,供 hasLocalChanges 比较)。 */
67
+ sections: Partial<Record<SectionId, SectionData>>;
68
+ nowIso?: string;
69
+ opts?: RecordBaselineOptions;
70
+ env: RecordBaselineEnv;
71
+ }
72
+
73
+ export async function recordBaseline(input: RecordBaselineInput): Promise<void> {
74
+ const { snapshotId, sections, env } = input;
75
+ const opts = input.opts ?? {};
76
+ const ts = input.nowIso ?? env.now().toISOString();
77
+ const preserveAncestor = opts.preserveAncestor === true;
78
+ const ancestorPassword = opts.ancestorPassword;
79
+ const encryptedAncestor = ancestorPassword !== undefined && ancestorPassword !== '';
80
+ const writesAncestorCopy = !preserveAncestor && env.localSnapshotsDir !== undefined && opts.writeAncestor !== false;
81
+
82
+ // 1) 写本地祖先副本(如有 localSnapshotsDir)。
83
+ // ancestorPassword 提供 → 落**密文**祖先副本(issue #107:加密通道也能做三方合并);
84
+ // 否则落明文散文件布局(既有行为逐字不变)。
85
+ if (writesAncestorCopy && env.localSnapshotsDir !== undefined) {
86
+ const manifest: SyncSnapshot['manifest'] = {
87
+ schemaVersion: CURRENT_SCHEMA_VERSION,
88
+ dshVersion: env.dshVersion,
89
+ platform: env.platform,
90
+ sectionIds: Object.keys(sections) as SectionId[],
91
+ containsSecrets: false,
92
+ // 记录触发通道(git/webdav),供同步历史展示「由哪个通道触发」
93
+ transport: env.transport.type,
94
+ ...(encryptedAncestor ? { encrypted: true } : {}),
95
+ };
96
+ if (encryptedAncestor) {
97
+ const encryptedSections = await encryptSectionsPayload(sections, ancestorPassword);
98
+ await writeEncryptedAncestor(env.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections: encryptedSections }, env.fsx);
99
+ } else {
100
+ await writeAncestor(env.localSnapshotsDir, { id: snapshotId, createdAt: ts, manifest, sections }, env.fsx);
101
+ }
102
+ }
103
+
104
+ // 2) 更新 sync-state:远端指针 + 本地祖先目录名 + 每分区 hash/updatedAt + lastSyncAt + transport
105
+ const state = await loadSyncState(env.stateDir, env.fsx, env.msg);
106
+ const previousPointer = state.lastSnapshotId;
107
+ state.lastSnapshotId = opts.remoteSnapshotId ?? snapshotId;
108
+ // issue #140(G-44):远端观测只认调用方显式给出的「远端快照 sections」。
109
+ // 指针变了却拿不到观测 ⇒ 删除(下一轮判定回落 id 比较),绝不沿用上一份观测冒充现状。
110
+ if (opts.remoteSections !== undefined) {
111
+ if (Object.keys(opts.remoteSections).length > 0) state.lastRemoteSections = { ...opts.remoteSections };
112
+ else delete state.lastRemoteSections;
113
+ } else if (state.lastSnapshotId !== previousPointer) {
114
+ delete state.lastRemoteSections;
115
+ }
116
+ // preserveAncestor:祖先目录名一并保持不动(既不是 snapshotId,也不是 '')
117
+ if (!preserveAncestor) state.ancestorId = writesAncestorCopy ? snapshotId : '';
118
+ state.lastSyncAt = ts;
119
+ state.transport = { type: env.transport.type, ref: env.transport.ref };
120
+ // 基线纪律:null = 清除(全部裁决完);undefined = 不动该字段(既有调用方零感知)
121
+ if (opts.pendingMerge === null) delete state.pendingMerge;
122
+ else if (opts.pendingMerge !== undefined) state.pendingMerge = opts.pendingMerge;
123
+ // P1-5:只在调用方明确提供时覆盖(否则保留既有记录,绝不因某条路径不跟踪而清空)
124
+ if (opts.sessionUnits !== undefined) state.sessionUnits = [...opts.sessionUnits];
125
+ if (opts.deletedSessions !== undefined) state.deletedSessions = [...opts.deletedSessions];
126
+ for (const [sid, data] of Object.entries(sections)) {
127
+ state.sections[sid as SectionId] = { hash: hashSection(data as SectionData), updatedAt: ts };
128
+ }
129
+ await saveSyncState(env.stateDir, state, env.fsx);
130
+
131
+ // 3) 裁剪祖先副本(最近 N 个);preserveAncestor 时本轮没有新副本,不参与裁剪
132
+ if (!preserveAncestor && env.localSnapshotsDir !== undefined) {
133
+ await pruneAncestors(env.localSnapshotsDir, DEFAULT_ANCESTOR_KEEP, env.fsx);
134
+ }
135
+ }
@@ -82,6 +82,22 @@ test('blob-store: 缺 blob → 硬失败(绝不静默降级成空分区)', a
82
82
  await assert.rejects(() => refsToSection(refs, sink), /blob 缺失/);
83
83
  });
84
84
 
85
+ test('blob-store: blob 内容与引用哈希不符 → 硬失败,绝不把错误字节当会话写回(审计 P6-3)', async () => {
86
+ const sink = new MemBlobSink();
87
+ const refs = await sectionToBlobRefs(filesSection([['--p--/a/session.jsonl.zstd', 'REAL-BYTES']]), sink);
88
+ const hash = refs.blobRefs[0]?.blobHash;
89
+ assert.ok(hash !== undefined);
90
+ // 远端被改坏(同哈希槽位放另一段字节):长度也变了,sizeBytes 一并拦住
91
+ sink.blobs.set(hash, { bytes: new TextEncoder().encode('TAMPERED'), mtimeMs: Date.now() });
92
+ await assert.rejects(() => refsToSection(refs, sink), /校验不符/);
93
+
94
+ // 只坏在内容、长度凑巧相同:仍然靠 sha256 拦下
95
+ const sameLen = new TextEncoder().encode('TAMPERED-#'); // 与 'REAL-BYTES' 同为 10 字节
96
+ assert.equal(sameLen.byteLength, 10);
97
+ sink.blobs.set(hash, { bytes: sameLen, mtimeMs: Date.now() });
98
+ await assert.rejects(() => refsToSection(refs, sink), /校验不符/);
99
+ });
100
+
85
101
  test('blob-store: referencedBlobHashes 只认引用形态', () => {
86
102
  assert.equal(referencedBlobHashes(filesSection([['a', 'B']])).size, 0, '普通 FilesSection(含 data)不算引用');
87
103
  assert.deepEqual([...referencedBlobHashes({ version: 1, blobRefs: [{ relativePath: 'a', blobHash: 'h1', sizeBytes: 1 }] })], ['h1']);
@@ -98,6 +98,19 @@ export async function refsToSection(refs: BlobRefsSection, sink: BlobSink): Prom
98
98
  if (data === null) {
99
99
  throw new Error(engineMsg('sync.blobMissing', { hash: ref.blobHash, path: ref.relativePath }));
100
100
  }
101
+ // 内容寻址仓的引用自带 sha256(+ 字节数),取回后必须自证(审计 P6-3)。
102
+ // 注释承诺「远端仓被清理坏/被手工删过」必须硬失败,但此前只覆盖「删了」:
103
+ // 内容被改、半截写、base64 传输丢字符都会畅通无阻地把错误字节当成会话原样写回,
104
+ // 而「静默损坏」比「硬失败」更糟 —— 用户看不到任何错误,只发现对话内容变了。
105
+ const actualHash = sha256Hex(data);
106
+ if (actualHash !== ref.blobHash || (ref.sizeBytes !== undefined && data.byteLength !== ref.sizeBytes)) {
107
+ throw new Error(engineMsg('sync.blobCorrupt', {
108
+ hash: ref.blobHash,
109
+ path: ref.relativePath,
110
+ actual: actualHash,
111
+ size: String(data.byteLength),
112
+ }));
113
+ }
101
114
  files.push({ relativePath: ref.relativePath, data, contentHash: ref.blobHash });
102
115
  }
103
116
  return { version: 1, files };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * issue #140:同步「内容是否变化」判定层(唯一实现)。
3
+ *
4
+ * 为什么单独一个纯函数:拉取(hasNewRemoteSnapshot)与推送(push 是否新建快照)必须
5
+ * 用同一把尺子,否则会出现「拉取说没变、推送说变了」的自相矛盾状态。
6
+ *
7
+ * G-44:本文件只吃**调用方给出的远端观测**(SyncSnapshotMeta.sections),绝不接受
8
+ * 「本机基线」冒充远端现状 —— 那是 recordBaseline 一参两用的事故模式。
9
+ */
10
+ import test from 'node:test';
11
+ import assert from 'node:assert/strict';
12
+
13
+ import { diffSnapshotContent, hashSections } from './content-diff.ts';
14
+ import type { ManifestSummary, SyncSnapshotMeta } from './transport.ts';
15
+ import type { SectionData, SectionId } from '../schema/types.ts';
16
+
17
+ const manifest: ManifestSummary = {
18
+ schemaVersion: 3,
19
+ dshVersion: '0.0.0-test',
20
+ platform: 'win32',
21
+ sectionIds: ['settings'],
22
+ containsSecrets: false,
23
+ };
24
+
25
+ function meta(id: string, sections: Partial<Record<SectionId, string>>): SyncSnapshotMeta {
26
+ return { id, createdAt: '2026-11-14T00:00:00.000Z', sections, manifest };
27
+ }
28
+
29
+ const A = 'hash-a';
30
+ const B = 'hash-b';
31
+
32
+ test('diffSnapshotContent:远端最新与对照侧哈希相同 → same-content(changed=false)', () => {
33
+ const result = diffSnapshotContent(meta('s2', { settings: A, ui: B }), { settings: A, ui: B });
34
+ assert.equal(result.reason, 'same-content');
35
+ assert.equal(result.changed, false);
36
+ });
37
+
38
+ test('diffSnapshotContent:id 变了但分区哈希集合相同 → false(只看内容,不看 id)', () => {
39
+ // 同一内容被重新推了一次(旧行为每推一次一个新 id)——这不是「远端有新东西」。
40
+ assert.equal(diffSnapshotContent(meta('s3', { settings: A }), { settings: A }).changed, false);
41
+ });
42
+
43
+ test('diffSnapshotContent:任一分区哈希变化 → content-changed(changed=true)', () => {
44
+ const result = diffSnapshotContent(meta('s3', { settings: B }), { settings: A });
45
+ assert.equal(result.reason, 'content-changed');
46
+ assert.equal(result.changed, true);
47
+ });
48
+
49
+ test('diffSnapshotContent:分区键集合变化(新增/缺失)→ changed=true(集合相等才算没变)', () => {
50
+ // 远端多一个分区
51
+ assert.equal(diffSnapshotContent(meta('s3', { settings: A, ui: B }), { settings: A }).changed, true);
52
+ // 远端少一个分区
53
+ assert.equal(diffSnapshotContent(meta('s3', { settings: A }), { settings: A, ui: B }).changed, true);
54
+ });
55
+
56
+ test('diffSnapshotContent:远端 sections 为空(加密快照 / 旧通道不给哈希)→ unknown', () => {
57
+ const encrypted = diffSnapshotContent(meta('s9', {}), { settings: A });
58
+ assert.equal(encrypted.reason, 'unknown');
59
+ // unknown 的 changed 恒 false:调用方必须按 reason 回落(推送按旧行为新建、拉取比 id),
60
+ // 绝不能把「读不到」当成「没变」直接跳过。
61
+ assert.equal(encrypted.changed, false);
62
+ });
63
+
64
+ test('diffSnapshotContent:没有远端 / 没有对照侧 → unknown(绝不猜)', () => {
65
+ assert.equal(diffSnapshotContent(undefined, { settings: A }).reason, 'unknown');
66
+ assert.equal(diffSnapshotContent(null, { settings: A }).reason, 'unknown');
67
+ assert.equal(diffSnapshotContent(meta('s1', { settings: A }), undefined).reason, 'unknown');
68
+ assert.equal(diffSnapshotContent(meta('s1', { settings: A }), {}).reason, 'unknown');
69
+ });
70
+
71
+ test('diffSnapshotContent:local 优先于 baseline(推送场景传本次导出)', () => {
72
+ const remote = meta('s2', { settings: B });
73
+ const baseline = { settings: A };
74
+ const local = { settings: B }; // 本机已改成与远端一致
75
+ assert.equal(diffSnapshotContent(remote, baseline, local).changed, false);
76
+ // local 省略 → 用 baseline 比(拉取场景:比的是上次记录的远端观测)
77
+ assert.equal(diffSnapshotContent(remote, baseline).changed, true);
78
+ });
79
+
80
+ test('hashSections:逐分区签名(与 state.sections / 远端观测同一口径)', () => {
81
+ const sections: Partial<Record<SectionId, SectionData>> = {
82
+ settings: { value: { ui: 'dark' } } as unknown as SectionData,
83
+ ui: { value: { mode: 'dark' } } as unknown as SectionData,
84
+ };
85
+ const hashes = hashSections(sections);
86
+ assert.deepEqual(Object.keys(hashes).sort(), ['settings', 'ui']);
87
+ // 同内容两次 ⇒ 同哈希;改一个值 ⇒ 该分区哈希变
88
+ assert.deepEqual(hashSections(sections), hashes);
89
+ const changed = hashSections({ settings: { value: { ui: 'light' } } as unknown as SectionData });
90
+ assert.notEqual(changed.settings, hashes.settings);
91
+ });
92
+
93
+ test('hashSections:空载荷 → 空对象(调用方据此判 unknown,而不是「相同」)', () => {
94
+ assert.deepEqual(hashSections({}), {});
95
+ });