@narumitw/pi-sync 0.59.0 → 0.60.1

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 (327) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +25 -17
  3. package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
  4. package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
  5. package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
  6. package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
  7. package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-6LHIRS5R.ts} +30 -47
  8. package/dist/chunks/chunk-6LHIRS5R.ts.map +7 -0
  9. package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
  10. package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
  11. package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
  12. package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
  13. package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
  14. package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
  15. package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
  16. package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
  17. package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
  18. package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
  19. package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
  20. package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
  21. package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
  22. package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
  23. package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
  24. package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
  25. package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
  26. package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
  27. package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
  28. package/dist/chunks/chunk-JZKCOM62.ts +26 -0
  29. package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
  30. package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
  31. package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
  32. package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
  33. package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
  34. package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
  35. package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
  36. package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
  37. package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
  38. package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
  39. package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
  40. package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
  41. package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
  42. package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
  43. package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
  44. package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
  45. package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-FO4XBBHF.ts} +80 -86
  46. package/dist/chunks/command-handler-FO4XBBHF.ts.map +7 -0
  47. package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
  48. package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
  49. package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
  50. package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
  51. package/dist/chunks/continuous-storage-SQBAXACF.ts +27 -0
  52. package/dist/chunks/continuous-storage-SQBAXACF.ts.map +7 -0
  53. package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
  54. package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
  55. package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
  56. package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-AY5ZU6B4.ts} +180 -164
  57. package/dist/chunks/manager-ui-AY5ZU6B4.ts.map +7 -0
  58. package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
  59. package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
  60. package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
  61. package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
  62. package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
  63. package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
  64. package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
  65. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
  66. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
  67. package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
  68. package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
  69. package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
  70. package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
  71. package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
  72. package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
  73. package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
  74. package/dist/index.ts +269 -313
  75. package/dist/index.ts.map +4 -4
  76. package/docs/daemon-migration.md +93 -0
  77. package/docs/tui-contract.md +12 -0
  78. package/package.json +3 -6
  79. package/skills/configure-pi-sync/SKILL.md +1 -1
  80. package/skills/configure-pi-sync/references/configuration.md +19 -6
  81. package/src/backends/backend-factory.ts +2 -23
  82. package/src/backends/backend-identity.ts +5 -40
  83. package/src/backends/backend-types.ts +1 -81
  84. package/src/backends/git/git-backend.ts +6 -784
  85. package/src/backends/git/git-config.ts +8 -130
  86. package/src/backends/git/git-runner.ts +7 -255
  87. package/src/backends/git/git-storage.ts +14 -293
  88. package/src/backends/s3/s3-backend.ts +11 -523
  89. package/src/backends/s3/s3-client.ts +2 -399
  90. package/src/backends/s3/s3-conditions.ts +2 -67
  91. package/src/backends/snapshot-pointer.ts +2 -27
  92. package/src/backends/sync-backend.ts +6 -101
  93. package/src/backends/webdav/webdav-backend.ts +10 -622
  94. package/src/backends/webdav/webdav-client.ts +6 -370
  95. package/src/backends/webdav/webdav-config.ts +8 -82
  96. package/src/commands/command-execution.ts +40 -36
  97. package/src/commands/command.ts +23 -1
  98. package/src/daemon/apply-gate.ts +146 -0
  99. package/src/daemon/pi-client.ts +591 -0
  100. package/src/daemon/recovery.ts +103 -0
  101. package/src/paths.ts +12 -83
  102. package/src/settings/config-errors.ts +2 -6
  103. package/src/settings/config-file.ts +19 -693
  104. package/src/settings/config.ts +16 -263
  105. package/src/settings/settings-management.ts +11 -254
  106. package/src/settings/settings-store.ts +10 -48
  107. package/src/settings/settings-types.ts +1 -157
  108. package/src/settings/settings-validation.ts +17 -435
  109. package/src/snapshot/session-paths.ts +11 -111
  110. package/src/snapshot/snapshot-apply.ts +9 -322
  111. package/src/snapshot/snapshot-case-replacement.ts +6 -80
  112. package/src/snapshot/snapshot-codec.ts +2 -59
  113. package/src/snapshot/snapshot-exclude-safety.ts +2 -44
  114. package/src/snapshot/snapshot-mutation-queues.ts +6 -142
  115. package/src/snapshot/snapshot-paths.ts +2 -11
  116. package/src/snapshot/snapshot-root-transition.ts +6 -154
  117. package/src/snapshot/snapshot-transaction-directory.ts +5 -16
  118. package/src/snapshot/snapshot-transaction-plan.ts +2 -72
  119. package/src/snapshot/snapshot-transaction.ts +6 -946
  120. package/src/snapshot/snapshot-types.ts +1 -43
  121. package/src/snapshot/snapshot.ts +19 -447
  122. package/src/state/json-file.ts +2 -47
  123. package/src/state/lock-policy.ts +2 -2
  124. package/src/state/lock.ts +10 -292
  125. package/src/state/lockfile-fs.ts +2 -25
  126. package/src/state/merge-baseline-store.ts +8 -208
  127. package/src/state/mutation-directory-sync.ts +2 -34
  128. package/src/state/operation-availability.ts +7 -59
  129. package/src/state/state-directory.ts +8 -243
  130. package/src/state/state-types.ts +1 -25
  131. package/src/state/sync-state-store.ts +11 -75
  132. package/src/sync/agent-candidate.ts +7 -256
  133. package/src/sync/agent-plan.ts +2 -107
  134. package/src/sync/agent-policy.ts +10 -13
  135. package/src/sync/agent-refusal-retry.ts +2 -54
  136. package/src/sync/agent-request.ts +2 -19
  137. package/src/sync/agent-runner.ts +2 -191
  138. package/src/sync/agent-store.ts +7 -182
  139. package/src/sync/agent-sync.ts +2 -141
  140. package/src/sync/apply-review.ts +2 -63
  141. package/src/sync/automatic-sync.ts +55 -111
  142. package/src/sync/conflict-artifact-ownership.ts +2 -63
  143. package/src/sync/conflict-artifacts.ts +8 -195
  144. package/src/sync/conflict-groups.ts +2 -68
  145. package/src/sync/conflict-preview.ts +2 -56
  146. package/src/sync/conflict-resolution.ts +2 -93
  147. package/src/sync/conflict-retention.ts +2 -72
  148. package/src/sync/conflict-review.ts +3 -92
  149. package/src/sync/content-conflicts.ts +2 -73
  150. package/src/sync/continuous-errors.ts +7 -85
  151. package/src/sync/continuous-lease.ts +2 -216
  152. package/src/sync/continuous-record.ts +10 -261
  153. package/src/sync/continuous-storage.ts +12 -64
  154. package/src/sync/continuous-sync.ts +2 -563
  155. package/src/sync/continuous-watch.ts +2 -61
  156. package/src/sync/exclude-policy.ts +6 -84
  157. package/src/sync/field-migration.ts +2 -39
  158. package/src/sync/file-merge-planner.ts +2 -143
  159. package/src/sync/json-document.ts +7 -184
  160. package/src/sync/local-field-policy.ts +2 -29
  161. package/src/sync/local-fields.ts +9 -119
  162. package/src/sync/merge-apply.ts +2 -439
  163. package/src/sync/merge-journal.ts +10 -228
  164. package/src/sync/merge-transfer-error.ts +2 -72
  165. package/src/sync/merged-sync.ts +2 -919
  166. package/src/sync/mutation-owner.ts +2 -22
  167. package/src/sync/package-merge.ts +2 -87
  168. package/src/sync/partial-progress.ts +2 -55
  169. package/src/sync/remote-snapshot.ts +7 -79
  170. package/src/sync/session-merge.ts +2 -194
  171. package/src/sync/settings-conflicts.ts +2 -64
  172. package/src/sync/settings-merge.ts +6 -121
  173. package/src/sync/signals.ts +2 -8
  174. package/src/sync/startup-check.ts +15 -31
  175. package/src/sync/startup-timings.ts +2 -94
  176. package/src/sync/sync-decision.ts +3 -111
  177. package/src/sync/sync-error-guidance.ts +2 -46
  178. package/src/sync/sync-errors.ts +7 -23
  179. package/src/sync/sync-inspection.ts +10 -59
  180. package/src/sync/sync-local.ts +2 -44
  181. package/src/sync/sync-mutations.ts +10 -788
  182. package/src/sync/sync-operations.ts +32 -11
  183. package/src/sync/sync-policy.ts +34 -474
  184. package/src/sync/sync-queries.ts +2 -247
  185. package/src/sync/sync-state.ts +18 -157
  186. package/src/sync/text-merge.ts +10 -133
  187. package/src/sync-extension.ts +192 -142
  188. package/src/ui/manager-state.ts +35 -23
  189. package/src/ui/manager-ui.ts +80 -36
  190. package/src/ui/sync-attention.ts +7 -49
  191. package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
  192. package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
  193. package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
  194. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
  195. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
  196. package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
  197. package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
  198. package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
  199. package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
  200. package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
  201. package/dist/chunks/chunk-25QCU3LY.ts +0 -220
  202. package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
  203. package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
  204. package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
  205. package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
  206. package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
  207. package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
  208. package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
  209. package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
  210. package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
  211. package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
  212. package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
  213. package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
  214. package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
  215. package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
  216. package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
  217. package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
  218. package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
  219. package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
  220. package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
  221. package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
  222. package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
  223. package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
  224. package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
  225. package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
  226. package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
  227. package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
  228. package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
  229. package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
  230. package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
  231. package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
  232. package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
  233. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  234. package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
  235. package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
  236. package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
  237. package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
  238. package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
  239. package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
  240. package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
  241. package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
  242. package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
  243. package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
  244. package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
  245. package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
  246. package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
  247. package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
  248. package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
  249. package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
  250. package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
  251. package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
  252. package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
  253. package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
  254. package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
  255. package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
  256. package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
  257. package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
  258. package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
  259. package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
  260. package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
  261. package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
  262. package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
  263. package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
  264. package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
  265. package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
  266. package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
  267. package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
  268. package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
  269. package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
  270. package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
  271. package/dist/chunks/chunk-VPODHKOX.ts +0 -229
  272. package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
  273. package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
  274. package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
  275. package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
  276. package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
  277. package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
  278. package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
  279. package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
  280. package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
  281. package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
  282. package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
  283. package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
  284. package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
  285. package/dist/chunks/chunk-YEULK7MK.ts +0 -415
  286. package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
  287. package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
  288. package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
  289. package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
  290. package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
  291. package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
  292. package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
  293. package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
  294. package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
  295. package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
  296. package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
  297. package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
  298. package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
  299. package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
  300. package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
  301. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
  302. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
  303. package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
  304. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
  305. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
  306. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
  307. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
  308. package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
  309. package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
  310. package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
  311. package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
  312. package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
  313. package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
  314. package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
  315. package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
  316. package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
  317. package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
  318. package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
  319. package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
  320. package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
  321. /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
  322. /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
  323. /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
  324. /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
  325. /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
  326. /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
  327. /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
@@ -1,919 +1,2 @@
1
- import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { createSyncBackend, type SyncBackendFactory } from "../backends/backend-factory.js";
3
- import {
4
- expectedRemoteHead,
5
- type RemoteHead,
6
- type SyncBackend,
7
- SyncBackendConflictError,
8
- } from "../backends/sync-backend.js";
9
- import type { CommandOptions } from "../commands/command-types.js";
10
- import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
11
- import type { AnySyncConfig } from "../settings/settings-types.js";
12
- import {
13
- effectiveSessionRoot,
14
- requireStableMergeSessionRoot,
15
- snapshotOptionsForContext,
16
- } from "../snapshot/session-paths.js";
17
- import {
18
- createSnapshot,
19
- filterSnapshotForConfigPolicy,
20
- mergeRemotePreservedFiles,
21
- regenerateSnapshotIdentity,
22
- scanSnapshot,
23
- } from "../snapshot/snapshot.js";
24
- import type { Snapshot } from "../snapshot/snapshot-types.js";
25
- import {
26
- hasCurrentMergeBaseline,
27
- pruneMergeBaselines,
28
- readMergeAncestors,
29
- stageMergeBaseline,
30
- } from "../state/merge-baseline-store.js";
31
- import {
32
- readStateForConfig,
33
- statePathForConfig,
34
- syncStateFingerprint,
35
- writeStateForConfig,
36
- } from "../state/sync-state-store.js";
37
- import { confirmMergeReview } from "../ui/merge-review.js";
38
- import { mergedSyncSummary } from "../ui/merged-sync-summary.js";
39
- import { safeTerminalText } from "../ui/terminal-text.js";
40
- import { startupTransferEnabled } from "./agent-policy.js";
41
- import { releaseConflictArtifacts } from "./conflict-artifact-ownership.js";
42
- import {
43
- type CreatedConflictArtifact,
44
- conflictGroups,
45
- readConflictArtifact,
46
- saveConflictArtifact,
47
- } from "./conflict-artifacts.js";
48
- import { type ConflictResolution, resolveReviewedGroup } from "./conflict-resolution.js";
49
- import { pruneCompletedConflicts } from "./conflict-retention.js";
50
- import { resolveContentConflicts } from "./content-conflicts.js";
51
- import { ContinuousError } from "./continuous-errors.js";
52
- import { planFileMerge } from "./file-merge-planner.js";
53
- import { overlayLocalFields, portableSnapshot, sameLocalFields } from "./local-fields.js";
54
- import { applyMergedSnapshot, preflightMergedTargets } from "./merge-apply.js";
55
- import {
56
- clearMergeJournal,
57
- type MergeJournal,
58
- mergeJournalIdentity,
59
- readMergeJournal,
60
- writeMergeJournal,
61
- } from "./merge-journal.js";
62
- import { mergeTransferError } from "./merge-transfer-error.js";
63
- import { acceptedMergeFiles, type PartialProgress, progressState } from "./partial-progress.js";
64
- import {
65
- formatRemoteSelectionStatus,
66
- readSnapshotForHead,
67
- requireCompatibleRemoteSelection,
68
- } from "./remote-snapshot.js";
69
- import { resolveSettingsConflicts } from "./settings-conflicts.js";
70
- import { createStartupTimings, type StartupTimings } from "./startup-timings.js";
71
- import { createSyncDecision } from "./sync-decision.js";
72
- import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
73
- import { configuredSnapshotPathMatcher, inspectRemoteSelection, syncSessionsSelected } from "./sync-policy.js";
74
- import { fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged } from "./sync-state.js";
75
- import { TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
76
-
77
- const MAX_ATTEMPTS = 3;
78
-
79
- /** Established-baseline sync only. First-source selection remains in the existing command flow. */
80
- export async function mergeSync(
81
- ctx: ExtensionContext | ExtensionCommandContext,
82
- options: CommandOptions,
83
- factory: SyncBackendFactory = createSyncBackend,
84
- resolution?: ConflictResolution,
85
- ) {
86
- const timings = options.startupTimings ?? createStartupTimings();
87
- const sessionOwner = captureMutationOwner(ctx, options.signal);
88
- const validateOwner = (config?: AnySyncConfig) => {
89
- sessionOwner();
90
- options.background?.validate(config);
91
- };
92
- const isCurrent = () => {
93
- try {
94
- validateOwner();
95
- return true;
96
- } catch {
97
- return false;
98
- }
99
- };
100
- const validateRetryAuthorization = (config: AnySyncConfig) => {
101
- if (
102
- options.agentRetryRefusal &&
103
- (!config.agentMode || options.auto || options.background || !ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
104
- )
105
- throw new Error("Refused-candidate retry requires foreground Autonomous sync in TUI or RPC.");
106
- };
107
- const config = await loadConfig(options.setup);
108
- validateOwner(config);
109
- validateRetryAuthorization(config);
110
- const configToken = syncCheckConfigFingerprint(config);
111
- const modelToken = JSON.stringify(ctx.model);
112
- const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : undefined;
113
- validateOwner();
114
- const snapshotOptions = {
115
- ...snapshotOptionsForContext(ctx, config),
116
- sessionDir: sessionRoot,
117
- signal: options.signal,
118
- };
119
- const validate = () =>
120
- timings.measure("transfer authorization", async () => {
121
- validateOwner();
122
- const latest = await loadConfig(options.setup);
123
- validateOwner(latest);
124
- validateRetryAuthorization(latest);
125
- if (configToken !== syncCheckConfigFingerprint(latest))
126
- throw new Error("Sync setup or settings changed during transfer; reopen sync.");
127
- if (sessionRoot !== undefined) {
128
- const currentRoot = await effectiveSessionRoot(ctx);
129
- validateOwner();
130
- if (currentRoot !== sessionRoot)
131
- throw new Error("Session storage root changed during transfer; evidence retained for review.");
132
- }
133
- if (config.agentMode && JSON.stringify(ctx.model) !== modelToken)
134
- throw new Error("Autonomous sync paused: selected model changed during transfer.");
135
- if (options.auto && (!startupTransferEnabled(latest) || !ctx.isIdle()))
136
- throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
137
- });
138
- await validate();
139
- const backend = await timings.measure("transfer backend initialization", () => factory(config));
140
- await validate();
141
- const pending = await timings.measure("transfer journal read", () => readMergeJournal(config));
142
- await validate();
143
- if (pending && options.agentRetryRefusal)
144
- throw new Error("A pending merge journal requires ordinary Sync now before retrying a refused candidate.");
145
- if (pending) {
146
- const recovered = await timings.measure("transfer journal recovery", () =>
147
- completeJournal(
148
- ctx,
149
- config,
150
- backend,
151
- pending,
152
- validate,
153
- timings,
154
- options.signal,
155
- options.auto,
156
- options.background?.validate,
157
- ),
158
- );
159
- if (!recovered) {
160
- if ((options.auto || !options.silent) && !options.signal?.aborted)
161
- ctx.ui.notify(
162
- "Interrupted candidate is not active; local content and baseline were unchanged. Evidence was reconciled without retrying publication. Run sync again for a fresh plan.",
163
- "warning",
164
- );
165
- return "cancelled" as const;
166
- }
167
- if ((options.auto || !options.silent) && !options.signal?.aborted)
168
- ctx.ui.notify("Recovered the committed merged transfer. Run sync again to inspect newer changes.", "info");
169
- return "applied" as const;
170
- }
171
- // Recovery above never publishes. This gate applies only to new autonomous transfers.
172
- if ((options.auto || config.agentMode) && backend.capability === "read-check-write-verify") {
173
- throw new Error(
174
- "Automatic transfer requires conditional publication or a lease; this backend supports only read/check/write/verify. Disable Autonomous sync and use manual sync.",
175
- );
176
- }
177
- const textBudget = { remaining: TEXT_MERGE_WORK_LIMIT };
178
- const createdArtifacts: CreatedConflictArtifact[] = [];
179
- const ownedStatePath = statePathForConfig(config);
180
- try {
181
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
182
- await validate();
183
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
184
- if (state.unresolved?.length && !config.partialSync)
185
- throw new Error(
186
- "Partial progress remains unresolved; re-enable partial sync or review an explicit force direction.",
187
- );
188
- const localRaw = await timings.measure("transfer local snapshot", () =>
189
- createSnapshot(config.snapshotIdentity, snapshotOptions),
190
- );
191
- const local = portableSnapshot(localRaw, config.localFields);
192
- if (!sameLocalFields(state.localFields, config.localFields))
193
- throw new Error("Local-field rules changed; review and confirm a directional migration first.");
194
- const head = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
195
- await validate();
196
- // This is a read-only shortcut, never authority to apply or publish. Pending
197
- // journals were handled above. Legacy/partial baselines retain the full path.
198
- if (
199
- options.auto &&
200
- !resolution &&
201
- !config.partialSync &&
202
- head &&
203
- state.lastAppliedSnapshot &&
204
- state.lastRemoteRevision &&
205
- !state.unresolved?.length &&
206
- head.snapshotId === state.lastAppliedSnapshot &&
207
- backend.sameRevision(head.revision, state.lastRemoteRevision) &&
208
- inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude).kind ===
209
- "same" &&
210
- matchesAcceptedState(state, config, head, local)
211
- ) {
212
- const unchanged = await timings.measure("transfer unchanged verification", async () => {
213
- if (!(await hasCurrentMergeBaseline(config, local, state))) return false;
214
- await validate();
215
- const currentLocal = await timings.measure("transfer local snapshot", () =>
216
- createSnapshot(config.snapshotIdentity, snapshotOptions),
217
- );
218
- await validate();
219
- const currentState = await timings.measure("transfer state read", () => readStateForConfig(config));
220
- await validate();
221
- return (
222
- sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) &&
223
- syncStateFingerprint(currentState) === syncStateFingerprint(state)
224
- );
225
- });
226
- await validate();
227
- if (unchanged) {
228
- timings.markUnchanged();
229
- return "applied" as const;
230
- }
231
- }
232
- const rawRemote = head
233
- ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal))
234
- : undefined;
235
- await validate();
236
- if (rawRemote) {
237
- const files = [...local.files, ...rawRemote.files];
238
- if (
239
- files.length > 16_384 ||
240
- files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024
241
- ) {
242
- throw new Error(
243
- "Merged transfer exceeds the 64 MiB / 16,384 input-file bound; review an explicit push or pull instead.",
244
- );
245
- }
246
- }
247
- const remote = rawRemote
248
- ? portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config), rawRemote.localFields)
249
- : undefined;
250
- if (rawRemote) {
251
- requireCompatibleRemoteSelection(config, rawRemote);
252
- const validation = await timings.measure("transfer merge planning", () =>
253
- planFileMerge({
254
- baseline: state.lastFileHashes,
255
- local: local.files,
256
- remote: rawRemote.files,
257
- selectionCompatible: true,
258
- }),
259
- );
260
- await validate();
261
- const managedPaths = new Set([
262
- ...Object.keys(state.lastFileHashes),
263
- ...[...local.files, ...(remote?.files ?? [])].map((file) => file.path),
264
- ]);
265
- if (
266
- validation.kind === "planned" &&
267
- validation.conflicts.some(
268
- (item) => item.reason === "path-collision" && (!config.partialSync || !managedPaths.has(item.path)),
269
- )
270
- )
271
- throw new Error("Remote snapshot contains path collisions; review a directional recovery before merging.");
272
- }
273
- const review = (
274
- message: string,
275
- kind: "both-changed" | "remote-empty" | "remote-or-policy-changed" = "both-changed",
276
- ) =>
277
- createSyncDecision({
278
- kind,
279
- config,
280
- state,
281
- local,
282
- remote,
283
- localChanged: hasLocalChanges(local, state, config),
284
- remoteChanged: remote ? hasRemoteChanges(remote, state, config) : Boolean(state.lastAppliedSnapshot),
285
- directMessage: message,
286
- });
287
- if (!state.lastAppliedSnapshot) throw review("Choose the initial source before enabling automatic transfer.");
288
- if (syncPolicyChanged(state, config))
289
- throw review("Included content changed; review the selection before merging.", "remote-or-policy-changed");
290
- if (!head || !remote || !rawRemote)
291
- throw review("The established remote is missing; choose an explicit recovery direction.", "remote-empty");
292
- const selectionState = inspectRemoteSelection(config.include, rawRemote, config.exclude);
293
- const selectionCompatible = selectionState.kind === "same";
294
- let plan = await timings.measure("transfer merge planning", () =>
295
- planFileMerge({
296
- baseline: state.lastFileHashes,
297
- local: local.files,
298
- remote: remote.files,
299
- selectionCompatible,
300
- protectedPaths: protectedSessionPaths(ctx, sessionRoot),
301
- }),
302
- );
303
- await validate();
304
- let resolved = { plan, fields: [] as string[] };
305
- if (config.mergeSettings || config.agentMode) {
306
- try {
307
- resolved = await timings.measure("transfer settings merge", () =>
308
- resolveSettingsConflicts(config, state, local, remote, plan),
309
- );
310
- } catch (error) {
311
- if (!config.partialSync) throw error;
312
- }
313
- }
314
- await validate();
315
- plan = await timings.measure("transfer content merge", () =>
316
- resolveContentConflicts(config, state, local, remote, resolved.plan, protectedSessionPaths(ctx, sessionRoot), {
317
- textBudget,
318
- signal: options.signal,
319
- }),
320
- );
321
- await validate();
322
- if (resolution) {
323
- plan = await resolveReviewedGroup(
324
- config,
325
- backend,
326
- state,
327
- local,
328
- remote,
329
- head,
330
- plan,
331
- resolution,
332
- protectedSessionPaths(ctx, sessionRoot),
333
- );
334
- await validate();
335
- }
336
- if (config.agentMode && !resolution) {
337
- const { resolveAgentPlan } = await import("./agent-plan.js");
338
- await validate();
339
- plan = await resolveAgentPlan(
340
- ctx,
341
- options,
342
- config,
343
- backend,
344
- state,
345
- local,
346
- localRaw,
347
- remote,
348
- head,
349
- plan,
350
- snapshotOptions,
351
- validate,
352
- );
353
- await validate();
354
- if (plan.kind !== "planned" || (plan.conflicts.length && !config.partialSync))
355
- throw new ContinuousError(
356
- "unsafe",
357
- "Autonomous sync paused: unsupported or refused conflict groups remain; no transfer was performed.",
358
- );
359
- }
360
- if (
361
- plan.kind !== "planned" ||
362
- (plan.conflicts.length && (!config.partialSync || (options.auto && !config.agentMode)))
363
- ) {
364
- const decision = review(
365
- selectionCompatible
366
- ? `Conflicting or protected paths require review; no merged transfer was performed. Use /sync diff and an explicit direction.${resolved.fields.length ? ` Settings fields: ${resolved.fields.map(safeTerminalText).join(", ")}` : ""}`
367
- : "Remote selection metadata is unavailable; review the included content and choose an explicit direction before merging.",
368
- selectionCompatible ? "both-changed" : "remote-or-policy-changed",
369
- );
370
- if (!selectionCompatible)
371
- decision.decision.review += `\n\n${formatRemoteSelectionStatus(selectionState)}\nAn explicit direction adopts this setup's included-content policy; no automatic merge was performed.`;
372
- throw decision;
373
- }
374
- if (plan.kind !== "planned") throw new Error("Cannot partition an unverified merge plan.");
375
- const groups = conflictGroups(plan, config);
376
- const withheld = new Set(groups.flatMap((group) => group.paths));
377
- // Transfer plans defer artifact writes until approved review and freshness guards pass.
378
- // A no-transfer manual inspection can persist referenced conflict state directly.
379
- const persistProgress = async (): Promise<PartialProgress | undefined> => {
380
- if (!groups.length) return;
381
- let ancestors: import("../snapshot/snapshot-types.js").SnapshotFile[] = [];
382
- try {
383
- const configured = configuredSnapshotPathMatcher(config);
384
- ancestors = ((await readMergeAncestors(config, state)) ?? []).filter(
385
- (file) => withheld.has(file.path) && configured(file.path),
386
- );
387
- } catch {
388
- /* Retain unknown evidence; absence remains explicit. */
389
- }
390
- await validate();
391
- const previousArtifacts = new Map<
392
- string,
393
- {
394
- artifact: Awaited<ReturnType<typeof readConflictArtifact>>;
395
- local: ReturnType<typeof fileHashMap>;
396
- remote: ReturnType<typeof fileHashMap>;
397
- }
398
- >();
399
- for (const token of new Set(state.unresolved?.map((group) => group.artifact) ?? [])) {
400
- try {
401
- const artifact = await readConflictArtifact(config, backend.identity, token);
402
- previousArtifacts.set(token, {
403
- artifact,
404
- local: fileHashMap(artifact.local),
405
- remote: fileHashMap(artifact.remote),
406
- });
407
- } catch {
408
- /* Unknown evidence retained, never reused. */
409
- }
410
- await validate();
411
- }
412
- const localHashes = fileHashMap(local);
413
- const remoteHashes = fileHashMap(remote);
414
- const previousGroups = new Map(state.unresolved?.map((item) => [JSON.stringify(item.paths), item]));
415
- const pending = groups.map((group) => {
416
- const previous = previousGroups.get(JSON.stringify(group.paths));
417
- const original = previous ? previousArtifacts.get(previous.artifact) : undefined;
418
- if (!original || !previous) return { group };
419
- return group.paths.every(
420
- (filePath) =>
421
- localHashes[filePath] === original.local[filePath] &&
422
- remoteHashes[filePath] === original.remote[filePath] &&
423
- state.lastFileHashes[filePath] === original.artifact.state.lastFileHashes[filePath],
424
- )
425
- ? { group, artifact: previous.artifact }
426
- : { group };
427
- });
428
- let artifact: string | undefined;
429
- const newGroups = pending.filter((item) => !item.artifact).map((item) => item.group);
430
- const newPaths = new Set(newGroups.flatMap((group) => group.paths));
431
- if (newGroups.length)
432
- artifact = await saveConflictArtifact(
433
- config,
434
- backend.identity,
435
- {
436
- state,
437
- local: { ...local, files: local.files.filter((file) => newPaths.has(file.path)) },
438
- remote: { ...remote, files: remote.files.filter((file) => newPaths.has(file.path)) },
439
- ancestors: ancestors.filter((file) => newPaths.has(file.path)),
440
- groups: newGroups,
441
- observed: { snapshotId: head.snapshotId, revision: head.revision },
442
- },
443
- captureMutationOwner(ctx, options.signal),
444
- (created) => createdArtifacts.push(created),
445
- );
446
- await validate();
447
- return {
448
- previous: state,
449
- groups: pending.map((item) => ({ paths: item.group.paths, artifact: item.artifact ?? artifact ?? "" })),
450
- };
451
- };
452
- let progress: PartialProgress | undefined;
453
- const accepted = regenerateSnapshotIdentity({
454
- ...local,
455
- files: acceptedMergeFiles(plan.decisions, local.files, withheld),
456
- });
457
- const after = overlayLocalFields(accepted, localRaw, config.localFields);
458
- if (syncSessionsSelected(config)) requireStableMergeSessionRoot(localRaw, after);
459
- const publication = regenerateSnapshotIdentity({
460
- ...accepted,
461
- version: accepted.version === 4 ? 4 : config.partialSync ? 3 : accepted.version,
462
- files: [
463
- ...accepted.files.filter((file) => !withheld.has(file.path)),
464
- ...remote.files.filter((file) => withheld.has(file.path)),
465
- ],
466
- });
467
- const upload = mergeRemotePreservedFiles(publication, rawRemote, config);
468
- const publish =
469
- !sameHashes(fileHashMap(publication), fileHashMap(remote)) ||
470
- Boolean(config.partialSync && rawRemote.version !== 3 && rawRemote.version !== 4);
471
- const apply = !sameHashes(fileHashMap(localRaw), fileHashMap(after));
472
- if (!publish && !apply) {
473
- const beforeEvidence = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
474
- await validate();
475
- if (!beforeEvidence || !backend.sameRevision(beforeEvidence.revision, head.revision))
476
- throw new ContinuousError(
477
- "stale",
478
- "Remote changed before baseline acceptance; retry from a fresh observation.",
479
- );
480
- progress = await persistProgress();
481
- await validate();
482
- const currentLocal = await timings.measure("transfer local snapshot", () =>
483
- createSnapshot(config.snapshotIdentity, snapshotOptions),
484
- );
485
- await validate();
486
- if (
487
- !sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) ||
488
- syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !==
489
- syncStateFingerprint(state)
490
- )
491
- throw new ContinuousError(
492
- "stale",
493
- "Local content or baseline changed before baseline acceptance; retry from a fresh observation.",
494
- );
495
- await validate();
496
- const currentHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
497
- await validate();
498
- if (!currentHead || !backend.sameRevision(currentHead.revision, head.revision))
499
- throw new ContinuousError(
500
- "stale",
501
- "Remote changed before baseline acceptance; retry from a fresh observation.",
502
- );
503
- await options.agentAcceptance?.commitCandidate?.();
504
- await validate();
505
- await timings.measure("transfer baseline write", () =>
506
- writeAcceptedState(config, head, accepted, validate, progress),
507
- );
508
- await timings.measure("transfer cleanup", () =>
509
- pruneMergeBaselines(
510
- config,
511
- acceptedState(config, head, accepted, progress),
512
- captureMutationOwner(ctx, options.signal),
513
- ),
514
- );
515
- await validate();
516
- await timings.measure("transfer cleanup", () =>
517
- pruneCompletedConflicts(
518
- config,
519
- backend.identity,
520
- acceptedState(config, head, accepted, progress),
521
- accepted,
522
- remote,
523
- captureMutationOwner(ctx, options.signal),
524
- ),
525
- );
526
- await validate();
527
- if (!options.silent)
528
- ctx.ui.notify(
529
- progress
530
- ? `No independent transfer required; ${groups.length} conflict groups remain withheld. Review /sync conflicts.`
531
- : "Pi Sync is already up to date.",
532
- progress ? "warning" : "info",
533
- );
534
- return "applied" as const;
535
- }
536
- await timings.measure("transfer preflight", () =>
537
- preflightMergedTargets(localRaw, after, snapshotOptions, ctx.sessionManager.getSessionFile?.()),
538
- );
539
- await validate();
540
- if (!config.skipSecretScan && scanSnapshot(upload).length)
541
- throw new ContinuousError(
542
- "unsafe",
543
- "Refusing to merge possible secrets. Review managed content before syncing.",
544
- );
545
- if (!options.yes && !config.agentMode) {
546
- const summary = mergedSyncSummary({
547
- setupName: config.setupName,
548
- destination: backend.destination,
549
- localBefore: localRaw,
550
- localAfter: after,
551
- remoteBefore: rawRemote,
552
- remoteAfter: upload,
553
- publish,
554
- sessions: syncSessionsSelected(config),
555
- groups,
556
- decisions: plan.decisions,
557
- capability: backend.capability,
558
- });
559
- if (
560
- !(await confirmMergeReview(
561
- ctx,
562
- summary.title,
563
- summary.content,
564
- options.signal,
565
- isCurrent,
566
- summary.confirmationLabel,
567
- summary.lines,
568
- ))
569
- )
570
- return "cancelled" as const;
571
- }
572
- await validate();
573
- const refreshed = await timings.measure("transfer local snapshot", () =>
574
- createSnapshot(config.snapshotIdentity, snapshotOptions),
575
- );
576
- if (!sameHashes(fileHashMap(refreshed), fileHashMap(localRaw)))
577
- throw new ContinuousError("stale", "Local content changed during review; no merged transfer was performed.");
578
- if (
579
- syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !==
580
- syncStateFingerprint(state)
581
- )
582
- throw new ContinuousError("stale", "Sync baseline changed during review; retry from a fresh observation.");
583
- await validate();
584
- const refreshedHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
585
- await validate();
586
- if (!refreshedHead || !backend.sameRevision(refreshedHead.revision, head.revision))
587
- throw new ContinuousError("stale", "Remote changed during review; no merged transfer was performed.");
588
- await options.agentAcceptance?.commitCandidate?.();
589
- await validate();
590
- progress = await persistProgress();
591
- await validate();
592
- const backup = await timings.measure("transfer backup", () =>
593
- backupLocal(config.snapshotIdentity, snapshotOptions, options.signal),
594
- );
595
- await validate();
596
- const journal: MergeJournal = {
597
- version: 1,
598
- identity: mergeJournalIdentity(config, backend.identity),
599
- before: localRaw,
600
- after,
601
- accepted,
602
- ...(progress ? { progress } : {}),
603
- upload: publish ? upload : rawRemote,
604
- expectedHead: head,
605
- backup,
606
- stateIdentity: syncStateFingerprint(state),
607
- ...(sessionRoot !== undefined ? { sessionRoot } : {}),
608
- ...(!publish ? { committedHead: head, applyOnly: true } : {}),
609
- };
610
- await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
611
- // No backend call has begun: a stale candidate can be retired without ambiguous publication.
612
- const atCommitState = syncStateFingerprint(
613
- await timings.measure("transfer state read", () => readStateForConfig(config)),
614
- );
615
- await validate();
616
- const atCommit = await timings.measure("transfer local snapshot", () =>
617
- createSnapshot(config.snapshotIdentity, snapshotOptions),
618
- );
619
- await validate();
620
- if (!sameHashes(fileHashMap(atCommit), fileHashMap(localRaw)) || atCommitState !== journal.stateIdentity) {
621
- await validate();
622
- await clearMergeJournal(config);
623
- throw new ContinuousError(
624
- "stale",
625
- "Local content or baseline changed before publication; candidate retired without transfer. Review a fresh sync.",
626
- );
627
- }
628
- // Backup/journal awaits can also change physical identity without changing any bytes.
629
- try {
630
- await timings.measure("transfer preflight", () =>
631
- preflightMergedTargets(atCommit, after, snapshotOptions, ctx.sessionManager.getSessionFile?.()),
632
- );
633
- await validate();
634
- } catch (error) {
635
- await validate();
636
- await clearMergeJournal(config);
637
- throw error;
638
- }
639
- try {
640
- if (publish) {
641
- const result = await timings.measure("transfer remote publication", () =>
642
- backend.publishSnapshot(upload, expectedRemoteHead(head), {
643
- signal: options.signal,
644
- onCommit: options.onCommit,
645
- }),
646
- );
647
- journal.committedHead = result.head;
648
- journal.warnings = result.warnings;
649
- await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
650
- } else options.onCommit?.();
651
- } catch (error) {
652
- if (
653
- error instanceof SyncBackendConflictError &&
654
- error.phase === "before-commit" &&
655
- !error.candidateMayHaveBeenActive
656
- ) {
657
- await clearMergeJournal(config);
658
- if (attempt + 1 < MAX_ATTEMPTS) continue;
659
- throw new Error("Remote changed before commit in all three attempts; retry later.", { cause: error });
660
- }
661
- // Cancellation before publication is safe only if no backend attempt began.
662
- // Every uncertain/after-commit outcome retains evidence and is never blindly retried.
663
- throw mergeTransferError(error, config.backend);
664
- }
665
- const completed = await timings.measure("transfer journal recovery", () =>
666
- completeJournal(
667
- ctx,
668
- config,
669
- backend,
670
- journal,
671
- validate,
672
- timings,
673
- options.signal,
674
- options.auto,
675
- options.background?.validate,
676
- ),
677
- );
678
- if (!completed) {
679
- if (!options.signal?.aborted && (options.auto || !options.silent))
680
- ctx.ui.notify(
681
- "Remote changed before local apply; candidate retired without transfer. Run sync again.",
682
- "warning",
683
- );
684
- return "cancelled" as const;
685
- }
686
- if (!options.signal?.aborted && (options.auto || !options.silent))
687
- ctx.ui.notify(
688
- [
689
- `Synced independent changes for “${safeTerminalText(config.setupName)}”. ${apply ? "Local files changed; reload or restart Pi when ready to use changed resources." : "Remote updated."} No automatic reload.`,
690
- ...(progress
691
- ? [
692
- `Partial progress: ${groups.length} dependency groups remain unresolved; neither side's withheld versions or baseline hashes were replaced. Review /sync conflicts.`,
693
- ]
694
- : []),
695
- ...(journal.warnings ?? []).map(safeTerminalText),
696
- ].join("\n"),
697
- progress || journal.warnings?.length ? "warning" : "info",
698
- );
699
- return "applied" as const;
700
- }
701
- } finally {
702
- await timings.measure("transfer cleanup", () => releaseConflictArtifacts(config, ownedStatePath, createdArtifacts));
703
- }
704
- }
705
-
706
- async function completeJournal(
707
- ctx: ExtensionContext | ExtensionCommandContext,
708
- config: AnySyncConfig,
709
- backend: SyncBackend,
710
- journal: MergeJournal,
711
- validate: () => Promise<void>,
712
- timings: StartupTimings,
713
- signal?: AbortSignal,
714
- auto = false,
715
- validateBackground?: () => void,
716
- ) {
717
- if (
718
- journal.identity !== mergeJournalIdentity(config, backend.identity) ||
719
- !sameLocalFields(journal.upload.localFields, config.localFields)
720
- )
721
- throw new Error(
722
- "Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery.",
723
- );
724
- await validate();
725
- const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : undefined;
726
- await validate();
727
- if (sessionRoot !== undefined && journal.sessionRoot !== sessionRoot) {
728
- throw new Error(
729
- "Merge journal session root is missing or differs from this context; preserve evidence and use reviewed directional recovery.",
730
- );
731
- }
732
- const snapshotOptions = { ...snapshotOptionsForContext(ctx, config), sessionDir: sessionRoot, signal };
733
- const head = await timings.measure("transfer remote head", () => backend.readHead(signal));
734
- if (
735
- !journal.committedHead &&
736
- head &&
737
- (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
738
- backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))
739
- ) {
740
- await validate();
741
- const local = await timings.measure("transfer local snapshot", () =>
742
- createSnapshot(config.snapshotIdentity, snapshotOptions),
743
- );
744
- if (
745
- !sameHashes(fileHashMap(local), fileHashMap(journal.before)) ||
746
- syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !==
747
- journal.stateIdentity
748
- ) {
749
- throw new Error(
750
- "Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery.",
751
- );
752
- }
753
- await clearMergeJournal(config);
754
- return false;
755
- }
756
- await validate();
757
- // Baseline publication is the durable completion boundary. A later remote revision
758
- // cannot undo that acceptance; retire only the journal for the recorded commit.
759
- if (journal.committedHead && (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
760
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
761
- await validate();
762
- if (
763
- matchesAcceptedState(state, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)
764
- ) {
765
- await clearMergeJournal(config);
766
- await validate();
767
- await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
768
- await validate();
769
- return true;
770
- }
771
- }
772
- if (journal.applyOnly && (!head || !backend.sameRevision(head.revision, journal.expectedHead.revision))) {
773
- const local = await timings.measure("transfer local snapshot", () =>
774
- createSnapshot(config.snapshotIdentity, snapshotOptions),
775
- );
776
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
777
- await validate();
778
- if (
779
- sameHashes(fileHashMap(local), fileHashMap(journal.before)) &&
780
- syncStateFingerprint(state) === journal.stateIdentity
781
- ) {
782
- await clearMergeJournal(config);
783
- return false;
784
- }
785
- throw new Error("Apply-only remote head advanced after local changes; preserve the journal for reviewed recovery.");
786
- }
787
- if (
788
- !head ||
789
- head.snapshotId !== journal.upload.id ||
790
- (journal.committedHead && !backend.sameRevision(head.revision, journal.committedHead.revision))
791
- ) {
792
- throw new Error(
793
- "Publication outcome cannot be reconciled with the current remote head. Journal and backup retained; do not retry publication or restore old bytes blindly.",
794
- );
795
- }
796
- const observed = await timings.measure("transfer snapshot download", () =>
797
- readSnapshotForHead(backend, head, signal),
798
- );
799
- requireCompatibleRemoteSelection(config, observed);
800
- if (
801
- !sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) ||
802
- JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection)
803
- )
804
- throw new Error("Remote snapshot does not match the recorded merge publication.");
805
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
806
- if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
807
- await validate();
808
- await clearMergeJournal(config);
809
- await validate();
810
- await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
811
- await validate();
812
- return true;
813
- }
814
- if (syncStateFingerprint(state) !== journal.stateIdentity) {
815
- throw new Error("Sync baseline changed after the interrupted merge; preserve its journal and review recovery.");
816
- }
817
- if (inspectRemoteSelection(config.include, observed, config.exclude).kind !== "same")
818
- throw new Error(
819
- "Pending merge has unavailable remote selection metadata; preserve its journal and choose a reviewed explicit direction.",
820
- );
821
- if (syncSessionsSelected(config)) requireStableMergeSessionRoot(journal.before, journal.after);
822
- await validate();
823
- const validateOwner = captureMutationOwner(ctx, signal);
824
- const validateMutation = () => {
825
- validateOwner();
826
- validateBackground?.();
827
- if (auto && !ctx.isIdle()) throw new Error("Automatic file apply is no longer idle; evidence retained.");
828
- };
829
- await timings.measure("transfer local apply", () =>
830
- applyMergedSnapshot(
831
- journal.before,
832
- journal.after,
833
- protectedSessionPaths(ctx, sessionRoot),
834
- { ...snapshotOptions, validateMutation },
835
- validate,
836
- ctx.sessionManager.getSessionFile?.(),
837
- ),
838
- );
839
- await validate();
840
- const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
841
- await validate();
842
- if (!headAtAcceptance || !backend.sameRevision(headAtAcceptance.revision, head.revision))
843
- throw new Error("Remote changed during merged apply; journal and backup retained for review.");
844
- await timings.measure("transfer baseline write", () =>
845
- writeAcceptedState(config, head, journal.accepted ?? journal.after, validate, journal.progress),
846
- );
847
- await validate();
848
- await clearMergeJournal(config);
849
- await validate();
850
- await timings.measure("transfer cleanup", () =>
851
- pruneMergeBaselines(
852
- config,
853
- acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
854
- captureMutationOwner(ctx, signal),
855
- ),
856
- );
857
- await validate();
858
- await timings.measure("transfer cleanup", () =>
859
- pruneCompletedConflicts(
860
- config,
861
- backend.identity,
862
- acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
863
- journal.accepted ?? journal.after,
864
- journal.upload,
865
- captureMutationOwner(ctx, signal),
866
- ),
867
- );
868
- await validate();
869
- return true;
870
- }
871
-
872
- // Older valid journals may have accepted noncanonical JSON before projection normalization.
873
- function matchesAcceptedState(
874
- state: Awaited<ReturnType<typeof readStateForConfig>>,
875
- config: AnySyncConfig,
876
- head: RemoteHead,
877
- snapshot: Snapshot,
878
- progress?: PartialProgress,
879
- ) {
880
- return [true, false].some(
881
- (canonical) =>
882
- syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical)),
883
- );
884
- }
885
-
886
- function acceptedState(
887
- config: AnySyncConfig,
888
- head: RemoteHead,
889
- snapshot: Snapshot,
890
- progress?: PartialProgress,
891
- canonical = true,
892
- ) {
893
- if (progress) return progressState(config, head, snapshot, progress);
894
- return {
895
- version: 1,
896
- profile: config.snapshotIdentity,
897
- lastAppliedSnapshot: head.snapshotId,
898
- lastRemoteRevision: head.revision,
899
- lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
900
- include: [...config.include],
901
- ...(config.exclude === undefined ? {} : { exclude: [...config.exclude] }),
902
- ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
903
- };
904
- }
905
-
906
- async function writeAcceptedState(
907
- config: AnySyncConfig,
908
- head: RemoteHead,
909
- snapshot: Snapshot,
910
- validate: () => Promise<void>,
911
- progress?: PartialProgress,
912
- ) {
913
- const accepted = portableSnapshot(snapshot, config.localFields);
914
- const state = acceptedState(config, head, accepted, progress);
915
- await stageMergeBaseline(config, accepted, state, progress?.previous);
916
- await validate();
917
- await writeStateForConfig(config, state);
918
- await validate();
919
- }
1
+ export type * from "@narumitw/sync-daemon/engine/sync/merged-sync";
2
+ export { mergeSync } from "@narumitw/sync-daemon/engine/sync/merged-sync";