@narumitw/pi-sync 0.70.6 → 0.71.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 (734) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +34 -105
  3. package/dist/chunks/agent-plan-A6CS3XXA.ts +337 -0
  4. package/dist/chunks/agent-plan-A6CS3XXA.ts.map +7 -0
  5. package/dist/chunks/chunk-2BMTS5OW.ts +229 -0
  6. package/dist/chunks/chunk-2BMTS5OW.ts.map +7 -0
  7. package/dist/chunks/chunk-2G6GTIWW.ts +188 -0
  8. package/dist/chunks/chunk-2G6GTIWW.ts.map +7 -0
  9. package/dist/chunks/chunk-2YHXXWUF.ts +18 -0
  10. package/dist/chunks/chunk-2YHXXWUF.ts.map +7 -0
  11. package/dist/chunks/chunk-3GL7LBNB.ts +3 -0
  12. package/dist/chunks/chunk-3M3KQFSQ.ts +215 -0
  13. package/dist/chunks/chunk-3M3KQFSQ.ts.map +7 -0
  14. package/dist/chunks/chunk-3PFWVSV3.ts +3 -0
  15. package/dist/chunks/chunk-4S5CGN4M.ts +54 -0
  16. package/dist/chunks/chunk-4S5CGN4M.ts.map +7 -0
  17. package/dist/chunks/{chunk-H7VOTY5N.ts → chunk-53AFFVTT.ts} +2 -24
  18. package/dist/chunks/{chunk-H7VOTY5N.ts.map → chunk-53AFFVTT.ts.map} +1 -1
  19. package/dist/chunks/chunk-53IKSWLZ.ts +3 -0
  20. package/dist/chunks/{chunk-ZWP6HAYV.ts → chunk-5ERTMRNE.ts} +1 -1
  21. package/dist/chunks/chunk-5ERTMRNE.ts.map +7 -0
  22. package/dist/chunks/chunk-5WUWHDCJ.ts +12 -0
  23. package/dist/chunks/chunk-5WUWHDCJ.ts.map +7 -0
  24. package/dist/chunks/{chunk-WRS3SUNZ.ts → chunk-6VGQ6THO.ts} +8 -10
  25. package/dist/chunks/{chunk-WRS3SUNZ.ts.map → chunk-6VGQ6THO.ts.map} +1 -1
  26. package/dist/chunks/chunk-6WVJIIXQ.ts +154 -0
  27. package/dist/chunks/chunk-6WVJIIXQ.ts.map +7 -0
  28. package/dist/chunks/chunk-A3NEEVNA.ts +3 -0
  29. package/dist/chunks/chunk-A7KJUFLX.ts +2120 -0
  30. package/dist/chunks/chunk-A7KJUFLX.ts.map +7 -0
  31. package/dist/chunks/{chunk-4A34OGXY.ts → chunk-AA2G3HTW.ts} +12 -16
  32. package/dist/chunks/{chunk-4A34OGXY.ts.map → chunk-AA2G3HTW.ts.map} +1 -1
  33. package/dist/chunks/chunk-AITZUACB.ts +3 -0
  34. package/dist/chunks/chunk-AVLYLWA7.ts +1414 -0
  35. package/dist/chunks/chunk-AVLYLWA7.ts.map +7 -0
  36. package/dist/chunks/chunk-B4JNUYZ2.ts +12 -0
  37. package/dist/chunks/chunk-B4JNUYZ2.ts.map +7 -0
  38. package/dist/chunks/chunk-BEO3THWZ.ts +3 -0
  39. package/dist/chunks/chunk-BEO3THWZ.ts.map +7 -0
  40. package/dist/chunks/chunk-C2YD64T6.ts +167 -0
  41. package/dist/chunks/chunk-C2YD64T6.ts.map +7 -0
  42. package/dist/chunks/chunk-C66HLRRZ.ts +72 -0
  43. package/dist/chunks/chunk-C66HLRRZ.ts.map +7 -0
  44. package/dist/chunks/chunk-CFXAA65U.ts +53 -0
  45. package/dist/chunks/chunk-CFXAA65U.ts.map +7 -0
  46. package/dist/chunks/chunk-D34Y5JSL.ts +152 -0
  47. package/dist/chunks/chunk-D34Y5JSL.ts.map +7 -0
  48. package/dist/chunks/chunk-D3DMJSFU.ts +125 -0
  49. package/dist/chunks/chunk-D3DMJSFU.ts.map +7 -0
  50. package/dist/chunks/chunk-DFC3WJP5.ts +3 -0
  51. package/dist/chunks/chunk-DFC3WJP5.ts.map +7 -0
  52. package/dist/chunks/chunk-DH52CVRD.ts +2499 -0
  53. package/dist/chunks/chunk-DH52CVRD.ts.map +7 -0
  54. package/dist/chunks/chunk-DLA5RPFP.ts +50 -0
  55. package/dist/chunks/chunk-DLA5RPFP.ts.map +7 -0
  56. package/dist/chunks/chunk-ES4FIIHZ.ts +50 -0
  57. package/dist/chunks/chunk-ES4FIIHZ.ts.map +7 -0
  58. package/dist/chunks/chunk-ESUMO4TW.ts +55 -0
  59. package/dist/chunks/chunk-ESUMO4TW.ts.map +7 -0
  60. package/dist/chunks/chunk-FIEW5453.ts +77 -0
  61. package/dist/chunks/chunk-FIEW5453.ts.map +7 -0
  62. package/dist/chunks/chunk-FT45DX6E.ts +163 -0
  63. package/dist/chunks/chunk-FT45DX6E.ts.map +7 -0
  64. package/dist/chunks/chunk-G7U6BPP4.ts +137 -0
  65. package/dist/chunks/chunk-G7U6BPP4.ts.map +7 -0
  66. package/dist/chunks/{chunk-5BE6LBDC.ts → chunk-GC5XDUVA.ts} +25 -34
  67. package/dist/chunks/{chunk-5BE6LBDC.ts.map → chunk-GC5XDUVA.ts.map} +3 -3
  68. package/dist/chunks/{chunk-VERMBZGL.ts → chunk-GDA35HWZ.ts} +12 -14
  69. package/dist/chunks/{chunk-VERMBZGL.ts.map → chunk-GDA35HWZ.ts.map} +1 -1
  70. package/dist/chunks/chunk-HOFEC5FH.ts +54 -0
  71. package/dist/chunks/chunk-HOFEC5FH.ts.map +7 -0
  72. package/dist/chunks/{chunk-WE3KJ7JS.ts → chunk-IFJXUHHC.ts} +7 -7
  73. package/dist/chunks/chunk-INUH2UXN.ts +53 -0
  74. package/dist/chunks/chunk-INUH2UXN.ts.map +7 -0
  75. package/dist/chunks/chunk-JPLT2DG6.ts +122 -0
  76. package/dist/chunks/chunk-JPLT2DG6.ts.map +7 -0
  77. package/dist/chunks/chunk-KDTDGAOM.ts +76 -0
  78. package/dist/chunks/chunk-KDTDGAOM.ts.map +7 -0
  79. package/dist/chunks/chunk-LBDUDSHD.ts +3 -0
  80. package/dist/chunks/chunk-LBDUDSHD.ts.map +7 -0
  81. package/dist/chunks/{chunk-VQTYTUBU.ts → chunk-LHQIQIWL.ts} +4 -22
  82. package/dist/chunks/chunk-LHQIQIWL.ts.map +7 -0
  83. package/dist/chunks/chunk-MHERAG42.ts +150 -0
  84. package/dist/chunks/chunk-MHERAG42.ts.map +7 -0
  85. package/dist/chunks/chunk-MS6HLJFR.ts +61 -0
  86. package/dist/chunks/chunk-MS6HLJFR.ts.map +7 -0
  87. package/dist/chunks/{chunk-AXN3B5KC.ts → chunk-MTUR4H7S.ts} +31 -41
  88. package/dist/chunks/chunk-MTUR4H7S.ts.map +7 -0
  89. package/dist/chunks/chunk-NFW5HLKA.ts +84 -0
  90. package/dist/chunks/chunk-NFW5HLKA.ts.map +7 -0
  91. package/dist/chunks/chunk-NFZMKZ2D.ts +345 -0
  92. package/dist/chunks/chunk-NFZMKZ2D.ts.map +7 -0
  93. package/dist/chunks/chunk-OTI4XVCS.ts +618 -0
  94. package/dist/chunks/chunk-OTI4XVCS.ts.map +7 -0
  95. package/dist/chunks/chunk-QIL27OLJ.ts +28 -0
  96. package/dist/chunks/chunk-QIL27OLJ.ts.map +7 -0
  97. package/dist/chunks/chunk-QJTU5SCJ.ts +27 -0
  98. package/dist/chunks/chunk-QJTU5SCJ.ts.map +7 -0
  99. package/dist/chunks/chunk-QNU4RFCN.ts +225 -0
  100. package/dist/chunks/chunk-QNU4RFCN.ts.map +7 -0
  101. package/dist/chunks/chunk-QRSESWT2.ts +26 -0
  102. package/dist/chunks/chunk-QRSESWT2.ts.map +7 -0
  103. package/dist/chunks/chunk-RFJWUIV5.ts +1622 -0
  104. package/dist/chunks/chunk-RFJWUIV5.ts.map +7 -0
  105. package/dist/chunks/chunk-RRFW2UAD.ts +347 -0
  106. package/dist/chunks/chunk-RRFW2UAD.ts.map +7 -0
  107. package/dist/chunks/chunk-SD3D6BTF.ts +3 -0
  108. package/dist/chunks/chunk-SD3D6BTF.ts.map +7 -0
  109. package/dist/chunks/chunk-SPRHJBJC.ts +17 -0
  110. package/dist/chunks/chunk-SPRHJBJC.ts.map +7 -0
  111. package/dist/chunks/chunk-T22OVZSI.ts +347 -0
  112. package/dist/chunks/chunk-T22OVZSI.ts.map +7 -0
  113. package/dist/chunks/chunk-TAOYC2YG.ts +113 -0
  114. package/dist/chunks/chunk-TAOYC2YG.ts.map +7 -0
  115. package/dist/chunks/chunk-U6CORBHU.ts +205 -0
  116. package/dist/chunks/chunk-U6CORBHU.ts.map +7 -0
  117. package/dist/chunks/chunk-ULNEZ53E.ts +105 -0
  118. package/dist/chunks/chunk-ULNEZ53E.ts.map +7 -0
  119. package/dist/chunks/chunk-UPP54ATP.ts +3 -0
  120. package/dist/chunks/chunk-UPP54ATP.ts.map +7 -0
  121. package/dist/chunks/chunk-V66NV2HZ.ts +70 -0
  122. package/dist/chunks/chunk-V66NV2HZ.ts.map +7 -0
  123. package/dist/chunks/chunk-W3YS4Y2Q.ts +545 -0
  124. package/dist/chunks/chunk-W3YS4Y2Q.ts.map +7 -0
  125. package/dist/chunks/chunk-WETDHZAD.ts +815 -0
  126. package/dist/chunks/chunk-WETDHZAD.ts.map +7 -0
  127. package/dist/chunks/chunk-WT2722L4.ts +61 -0
  128. package/dist/chunks/chunk-WT2722L4.ts.map +7 -0
  129. package/dist/chunks/chunk-XHJ3AVIT.ts +12 -0
  130. package/dist/chunks/chunk-XHJ3AVIT.ts.map +7 -0
  131. package/dist/chunks/{chunk-HFMGK6A6.ts → chunk-YLVRV6NM.ts} +5 -5
  132. package/dist/chunks/chunk-YV776ZPN.ts +49 -0
  133. package/dist/chunks/chunk-YV776ZPN.ts.map +7 -0
  134. package/dist/chunks/chunk-YVHXQZIH.ts +411 -0
  135. package/dist/chunks/chunk-YVHXQZIH.ts.map +7 -0
  136. package/dist/chunks/chunk-ZWJMVLQ3.ts +3 -0
  137. package/dist/chunks/chunk-ZWJMVLQ3.ts.map +7 -0
  138. package/dist/chunks/chunk-ZWOKNJDT.ts +25 -0
  139. package/dist/chunks/chunk-ZWOKNJDT.ts.map +7 -0
  140. package/dist/chunks/{command-handler-GERC7LOE.ts → command-handler-SMARANCT.ts} +128 -155
  141. package/dist/chunks/command-handler-SMARANCT.ts.map +7 -0
  142. package/dist/chunks/{chunk-LNZRNXNQ.ts → config-PUZS2ZBP.ts} +15 -6
  143. package/dist/chunks/config-PUZS2ZBP.ts.map +7 -0
  144. package/dist/chunks/conflict-artifacts-77PI6IXK.ts +33 -0
  145. package/dist/chunks/conflict-artifacts-77PI6IXK.ts.map +7 -0
  146. package/dist/chunks/conflict-review-HHGVL5TP.ts +188 -0
  147. package/dist/chunks/conflict-review-HHGVL5TP.ts.map +7 -0
  148. package/dist/chunks/conflict-review-OO57TGMR.ts +40 -0
  149. package/dist/chunks/conflict-review-OO57TGMR.ts.map +7 -0
  150. package/dist/chunks/continuous-record-QIIFQNKP.ts +277 -0
  151. package/dist/chunks/continuous-record-QIIFQNKP.ts.map +7 -0
  152. package/dist/chunks/debug-check-ETFFIDW5.ts +14 -0
  153. package/dist/chunks/debug-check-ETFFIDW5.ts.map +7 -0
  154. package/dist/chunks/debug-log-QGBO6XHF.ts +17 -0
  155. package/dist/chunks/debug-log-QGBO6XHF.ts.map +7 -0
  156. package/dist/chunks/debug-tool-execution-AIQAGPMJ.ts +95 -0
  157. package/dist/chunks/debug-tool-execution-AIQAGPMJ.ts.map +7 -0
  158. package/dist/chunks/{diff-review-GB4NO53B.ts → diff-review-QRHOHG5C.ts} +12 -5
  159. package/dist/chunks/diff-review-QRHOHG5C.ts.map +7 -0
  160. package/dist/chunks/{file-selection-DGC5UJVI.ts → file-selection-ZEBPDRHG.ts} +33 -16
  161. package/dist/chunks/{file-selection-DGC5UJVI.ts.map → file-selection-ZEBPDRHG.ts.map} +1 -1
  162. package/dist/chunks/git-backend-I2IJ5ULJ.ts +1151 -0
  163. package/dist/chunks/git-backend-I2IJ5ULJ.ts.map +7 -0
  164. package/dist/chunks/initialization-XGYWRNPQ.ts +106 -0
  165. package/dist/chunks/initialization-XGYWRNPQ.ts.map +7 -0
  166. package/dist/chunks/local-diff-review-OGZM3TA7.ts +525 -0
  167. package/dist/chunks/local-diff-review-OGZM3TA7.ts.map +7 -0
  168. package/dist/chunks/local-fields-PIKOEXWR.ts +31 -0
  169. package/dist/chunks/local-fields-PIKOEXWR.ts.map +7 -0
  170. package/dist/chunks/manager-result-dispatcher-72YGSLHL.ts +42 -0
  171. package/dist/chunks/manager-result-dispatcher-72YGSLHL.ts.map +7 -0
  172. package/dist/chunks/{manager-ui-3CQU37XY.ts → manager-ui-5SXPS4SE.ts} +130 -92
  173. package/dist/chunks/manager-ui-5SXPS4SE.ts.map +7 -0
  174. package/dist/chunks/merge-baseline-store-MI7SHGDH.ts +26 -0
  175. package/dist/chunks/merge-baseline-store-MI7SHGDH.ts.map +7 -0
  176. package/dist/chunks/merge-journal-46QC5N7D.ts +38 -0
  177. package/dist/chunks/merge-journal-46QC5N7D.ts.map +7 -0
  178. package/dist/chunks/{merge-review-DXSERTCK.ts → merge-review-RMDYVNBK.ts} +2 -2
  179. package/dist/chunks/remote-selection-ui-4BXJAZUD.ts +41 -0
  180. package/dist/chunks/remote-selection-ui-4BXJAZUD.ts.map +7 -0
  181. package/dist/chunks/s3-backend-ZRMOWH5R.ts +866 -0
  182. package/dist/chunks/s3-backend-ZRMOWH5R.ts.map +7 -0
  183. package/dist/chunks/session-push-55IV4IW3.ts +101 -0
  184. package/dist/chunks/session-push-55IV4IW3.ts.map +7 -0
  185. package/dist/chunks/setup-switch-DXDUBDQI.ts +43 -0
  186. package/dist/chunks/setup-switch-DXDUBDQI.ts.map +7 -0
  187. package/dist/chunks/{setup-wizard-FRIR2EOR.ts → setup-wizard-ICPQERAE.ts} +34 -18
  188. package/dist/chunks/{setup-wizard-FRIR2EOR.ts.map → setup-wizard-ICPQERAE.ts.map} +1 -1
  189. package/dist/chunks/{snapshot-ZUJJZCFW.ts → snapshot-HDARHOQZ.ts} +14 -8
  190. package/dist/chunks/snapshot-HDARHOQZ.ts.map +7 -0
  191. package/dist/chunks/snapshot-LZ6XKFA4.ts +63 -0
  192. package/dist/chunks/snapshot-LZ6XKFA4.ts.map +7 -0
  193. package/dist/chunks/snapshot-transaction-LYR5OFLR.ts +27 -0
  194. package/dist/chunks/snapshot-transaction-LYR5OFLR.ts.map +7 -0
  195. package/dist/chunks/sync-inspection-N6TELULU.ts +29 -0
  196. package/dist/chunks/sync-inspection-N6TELULU.ts.map +7 -0
  197. package/dist/chunks/sync-inspection-PMEXXLDK.ts +26 -0
  198. package/dist/chunks/sync-inspection-PMEXXLDK.ts.map +7 -0
  199. package/dist/chunks/sync-operations-KKSIS2CI.ts +69 -0
  200. package/dist/chunks/sync-operations-KKSIS2CI.ts.map +7 -0
  201. package/dist/chunks/sync-operations-VSMA5GSA.ts +47 -0
  202. package/dist/chunks/sync-operations-VSMA5GSA.ts.map +7 -0
  203. package/dist/chunks/{sync-state-QIT64TKV.ts → sync-state-72ZDKUQW.ts} +13 -5
  204. package/dist/chunks/sync-state-72ZDKUQW.ts.map +7 -0
  205. package/dist/chunks/{sync-state-store-TZE7XDV5.ts → sync-state-store-YTMAZQ3Z.ts} +8 -2
  206. package/dist/chunks/sync-state-store-YTMAZQ3Z.ts.map +7 -0
  207. package/dist/chunks/webdav-backend-3AZOECVQ.ts +948 -0
  208. package/dist/chunks/webdav-backend-3AZOECVQ.ts.map +7 -0
  209. package/dist/index.ts +286 -421
  210. package/dist/index.ts.map +4 -4
  211. package/docs/agent-continuous-hardening.md +3 -1
  212. package/docs/agent-quality-verification.md +3 -1
  213. package/docs/continuous-sync-verification.md +1 -1
  214. package/docs/daemon-migration.md +3 -1
  215. package/docs/daemon-retirement.md +15 -0
  216. package/docs/merge-implementation-audit.md +2 -0
  217. package/docs/settings-merge-audit.md +1 -1
  218. package/docs/tui-contract.md +12 -14
  219. package/package.json +1 -3
  220. package/skills/configure-pi-sync/SKILL.md +14 -60
  221. package/skills/configure-pi-sync/references/configuration.md +38 -46
  222. package/src/backends/backend-factory.ts +2 -2
  223. package/src/backends/backend-identity.ts +2 -2
  224. package/src/backends/backend-types.ts +1 -1
  225. package/src/backends/git/git-backend.ts +2 -2
  226. package/src/backends/git/git-config.ts +2 -2
  227. package/src/backends/git/git-runner.ts +2 -2
  228. package/src/backends/git/git-storage.ts +2 -2
  229. package/src/backends/s3/s3-backend.ts +2 -2
  230. package/src/backends/s3/s3-client.ts +2 -2
  231. package/src/backends/s3/s3-conditions.ts +2 -2
  232. package/src/backends/snapshot-pointer.ts +2 -2
  233. package/src/backends/sync-backend.ts +2 -2
  234. package/src/backends/webdav/webdav-backend.ts +2 -2
  235. package/src/backends/webdav/webdav-client.ts +2 -2
  236. package/src/backends/webdav/webdav-config.ts +2 -2
  237. package/src/commands/command-execution.ts +66 -62
  238. package/src/commands/command-handler.ts +3 -10
  239. package/src/commands/command-types.ts +1 -0
  240. package/src/commands/command.ts +3 -24
  241. package/src/engine/backends/backend-factory.ts +23 -0
  242. package/src/engine/backends/backend-identity.ts +40 -0
  243. package/src/engine/backends/backend-types.ts +75 -0
  244. package/src/engine/backends/git/git-backend.ts +863 -0
  245. package/src/engine/backends/git/git-config.ts +130 -0
  246. package/src/engine/backends/git/git-runner.ts +260 -0
  247. package/src/engine/backends/git/git-storage.ts +295 -0
  248. package/src/engine/backends/publication-encoding.ts +19 -0
  249. package/src/engine/backends/s3/s3-backend.ts +528 -0
  250. package/src/engine/backends/s3/s3-client.ts +398 -0
  251. package/src/engine/backends/s3/s3-conditions.ts +64 -0
  252. package/src/engine/backends/snapshot-pointer.ts +26 -0
  253. package/src/engine/backends/sync-backend.ts +133 -0
  254. package/src/engine/backends/webdav/webdav-backend.ts +691 -0
  255. package/src/engine/backends/webdav/webdav-client.ts +390 -0
  256. package/src/engine/backends/webdav/webdav-config.ts +82 -0
  257. package/src/engine/commands/command-types.ts +37 -0
  258. package/src/engine/debug-check.ts +83 -0
  259. package/src/engine/debug-log.ts +272 -0
  260. package/src/engine/diff-review-types.ts +16 -0
  261. package/src/engine/foreground-transfer.ts +15 -0
  262. package/src/engine/host.ts +95 -0
  263. package/src/engine/paths.ts +90 -0
  264. package/src/engine/record.ts +3 -0
  265. package/src/engine/settings/config-errors.ts +6 -0
  266. package/src/engine/settings/config-file.ts +907 -0
  267. package/src/engine/settings/config.ts +315 -0
  268. package/src/engine/settings/retired-ignore-policy.ts +15 -0
  269. package/src/engine/settings/retired-ignore-recovery.ts +18 -0
  270. package/src/engine/settings/settings-management.ts +261 -0
  271. package/src/engine/settings/settings-store.ts +48 -0
  272. package/src/engine/settings/settings-types.ts +164 -0
  273. package/src/engine/settings/settings-validation.ts +472 -0
  274. package/src/engine/snapshot/session-paths.ts +179 -0
  275. package/src/engine/snapshot/snapshot-apply.ts +443 -0
  276. package/src/engine/snapshot/snapshot-bounds.ts +23 -0
  277. package/src/engine/snapshot/snapshot-capture-limit.ts +110 -0
  278. package/src/engine/snapshot/snapshot-case-replacement.ts +77 -0
  279. package/src/engine/snapshot/snapshot-codec.ts +69 -0
  280. package/src/engine/snapshot/snapshot-difference.ts +25 -0
  281. package/src/engine/snapshot/snapshot-entry-projection.ts +101 -0
  282. package/src/engine/snapshot/snapshot-exclude-safety.ts +203 -0
  283. package/src/engine/snapshot/snapshot-mutation-queues.ts +152 -0
  284. package/src/engine/snapshot/snapshot-paths.ts +11 -0
  285. package/src/engine/snapshot/snapshot-payload.ts +50 -0
  286. package/src/engine/snapshot/snapshot-reviewed-preimages.ts +68 -0
  287. package/src/engine/snapshot/snapshot-root-transition.ts +170 -0
  288. package/src/engine/snapshot/snapshot-transaction-directory.ts +16 -0
  289. package/src/engine/snapshot/snapshot-transaction-images.ts +424 -0
  290. package/src/engine/snapshot/snapshot-transaction-plan.ts +69 -0
  291. package/src/engine/snapshot/snapshot-transaction-policy.ts +278 -0
  292. package/src/engine/snapshot/snapshot-transaction-stage.ts +342 -0
  293. package/src/engine/snapshot/snapshot-transaction-verification.ts +109 -0
  294. package/src/engine/snapshot/snapshot-transaction.ts +961 -0
  295. package/src/engine/snapshot/snapshot-types.ts +67 -0
  296. package/src/engine/snapshot/snapshot.ts +847 -0
  297. package/src/engine/state/json-file.ts +46 -0
  298. package/src/engine/state/lock.ts +421 -0
  299. package/src/engine/state/lockfile-fs.ts +25 -0
  300. package/src/engine/state/merge-baseline-store.ts +213 -0
  301. package/src/engine/state/mutation-directory-sync.ts +33 -0
  302. package/src/engine/state/operation-availability.ts +59 -0
  303. package/src/engine/state/state-directory.ts +245 -0
  304. package/src/engine/state/state-types.ts +26 -0
  305. package/src/engine/state/sync-state-store.ts +77 -0
  306. package/src/engine/sync/agent-candidate.ts +252 -0
  307. package/src/engine/sync/agent-plan.ts +114 -0
  308. package/{dist/daemon/dist/engine/sync/agent-policy.js → src/engine/sync/agent-policy.ts} +5 -3
  309. package/src/engine/sync/agent-refusal-retry.ts +53 -0
  310. package/src/engine/sync/agent-request.ts +17 -0
  311. package/src/engine/sync/agent-runner.ts +208 -0
  312. package/src/engine/sync/agent-store.ts +175 -0
  313. package/src/engine/sync/agent-sync.ts +145 -0
  314. package/src/engine/sync/apply-review.ts +63 -0
  315. package/src/engine/sync/conflict-artifact-ownership.ts +58 -0
  316. package/src/engine/sync/conflict-artifacts.ts +193 -0
  317. package/src/engine/sync/conflict-groups.ts +67 -0
  318. package/src/engine/sync/conflict-preview.ts +54 -0
  319. package/src/engine/sync/conflict-resolution.ts +93 -0
  320. package/src/engine/sync/conflict-retention.ts +71 -0
  321. package/src/engine/sync/conflict-review.ts +95 -0
  322. package/src/engine/sync/content-conflicts.ts +73 -0
  323. package/src/engine/sync/continuous-errors.ts +91 -0
  324. package/src/engine/sync/continuous-lease.ts +213 -0
  325. package/src/engine/sync/continuous-record.ts +255 -0
  326. package/src/engine/sync/continuous-storage.ts +63 -0
  327. package/src/engine/sync/continuous-sync.ts +646 -0
  328. package/src/engine/sync/continuous-watch.ts +123 -0
  329. package/src/engine/sync/diff-review-capture.ts +259 -0
  330. package/src/engine/sync/diff-review-preview.ts +111 -0
  331. package/src/engine/sync/diff-review-store.ts +72 -0
  332. package/src/engine/sync/directional-action.ts +169 -0
  333. package/src/engine/sync/directional-conflict.ts +53 -0
  334. package/src/engine/sync/exclude-policy.ts +88 -0
  335. package/src/engine/sync/field-migration.ts +39 -0
  336. package/src/engine/sync/file-merge-planner.ts +138 -0
  337. package/src/engine/sync/initialization.ts +81 -0
  338. package/src/engine/sync/json-document.ts +179 -0
  339. package/src/engine/sync/local-field-policy.ts +28 -0
  340. package/src/engine/sync/local-fields.ts +171 -0
  341. package/src/engine/sync/merge-acceptance.ts +56 -0
  342. package/src/engine/sync/merge-apply.ts +585 -0
  343. package/src/engine/sync/merge-journal.ts +259 -0
  344. package/src/engine/sync/merge-transfer-error.ts +68 -0
  345. package/src/engine/sync/merged-sync.ts +912 -0
  346. package/src/engine/sync/mutation-owner.ts +22 -0
  347. package/src/engine/sync/package-merge.ts +81 -0
  348. package/src/engine/sync/partial-progress.ts +56 -0
  349. package/src/engine/sync/pull-outcome.ts +16 -0
  350. package/src/engine/sync/push-review.ts +47 -0
  351. package/src/engine/sync/remote-snapshot.ts +185 -0
  352. package/src/engine/sync/resolver-stream.ts +34 -0
  353. package/src/engine/sync/session-merge.ts +192 -0
  354. package/src/engine/sync/session-push.ts +68 -0
  355. package/src/engine/sync/settings-conflicts.ts +64 -0
  356. package/src/engine/sync/settings-merge.ts +118 -0
  357. package/src/engine/sync/signals.ts +8 -0
  358. package/src/engine/sync/startup-recovery-evidence.ts +37 -0
  359. package/src/engine/sync/startup-timings.ts +135 -0
  360. package/src/engine/sync/sync-decision.ts +134 -0
  361. package/src/engine/sync/sync-error-guidance.ts +56 -0
  362. package/src/engine/sync/sync-errors.ts +50 -0
  363. package/src/engine/sync/sync-inspection.ts +61 -0
  364. package/src/engine/sync/sync-loaders.ts +14 -0
  365. package/src/engine/sync/sync-local.ts +117 -0
  366. package/src/engine/sync/sync-mutations.ts +940 -0
  367. package/src/engine/sync/sync-operations.ts +10 -0
  368. package/src/engine/sync/sync-policy.ts +695 -0
  369. package/src/engine/sync/sync-queries.ts +404 -0
  370. package/src/engine/sync/sync-rollback.ts +245 -0
  371. package/src/engine/sync/sync-state.ts +197 -0
  372. package/src/engine/sync/text-merge.ts +132 -0
  373. package/src/engine/sync/transfer-freshness.ts +151 -0
  374. package/src/engine/sync/transfer-size-limits.ts +100 -0
  375. package/src/engine/types.ts +45 -0
  376. package/src/engine/ui/merge-review.ts +14 -0
  377. package/src/engine/ui/merged-sync-summary.ts +111 -0
  378. package/src/engine/ui/sync-format.ts +222 -0
  379. package/src/engine/ui/sync-status.ts +29 -0
  380. package/src/engine/ui/terminal-text.ts +9 -0
  381. package/src/engine/ui/transfer-changes.ts +32 -0
  382. package/src/engine/ui/transfer-review.ts +28 -0
  383. package/src/paths.ts +2 -2
  384. package/src/runtime/identity.ts +152 -0
  385. package/src/runtime/legacy-owner.ts +223 -0
  386. package/src/runtime/lifecycle.ts +17 -0
  387. package/src/runtime/local-host.ts +157 -0
  388. package/src/{daemon/session-presence.ts → runtime/session-presence-binding.ts} +1 -2
  389. package/src/runtime/session-presence.ts +258 -0
  390. package/src/settings/config-errors.ts +2 -2
  391. package/src/settings/config-file.ts +2 -2
  392. package/src/settings/config.ts +2 -2
  393. package/src/settings/settings-management.ts +2 -2
  394. package/src/settings/settings-store.ts +2 -2
  395. package/src/settings/settings-types.ts +1 -1
  396. package/src/settings/settings-validation.ts +2 -2
  397. package/src/snapshot/session-paths.ts +2 -2
  398. package/src/snapshot/snapshot-apply.ts +2 -2
  399. package/src/snapshot/snapshot-case-replacement.ts +2 -2
  400. package/src/snapshot/snapshot-codec.ts +2 -2
  401. package/src/snapshot/snapshot-exclude-safety.ts +2 -2
  402. package/src/snapshot/snapshot-mutation-queues.ts +2 -2
  403. package/src/snapshot/snapshot-paths.ts +2 -2
  404. package/src/snapshot/snapshot-root-transition.ts +2 -2
  405. package/src/snapshot/snapshot-transaction-directory.ts +2 -2
  406. package/src/snapshot/snapshot-transaction-plan.ts +2 -2
  407. package/src/snapshot/snapshot-transaction.ts +2 -2
  408. package/src/snapshot/snapshot-types.ts +1 -1
  409. package/src/snapshot/snapshot.ts +2 -2
  410. package/src/state/json-file.ts +2 -2
  411. package/src/state/lock-policy.ts +2 -2
  412. package/src/state/lock.ts +2 -2
  413. package/src/state/lockfile-fs.ts +2 -2
  414. package/src/state/merge-baseline-store.ts +2 -2
  415. package/src/state/mutation-directory-sync.ts +2 -2
  416. package/src/state/operation-availability.ts +2 -2
  417. package/src/state/state-directory.ts +2 -2
  418. package/src/state/state-types.ts +1 -1
  419. package/src/state/sync-state-store.ts +2 -2
  420. package/src/sync/agent-candidate.ts +2 -2
  421. package/src/sync/agent-plan.ts +2 -2
  422. package/src/sync/agent-policy.ts +2 -2
  423. package/src/sync/agent-refusal-retry.ts +2 -2
  424. package/src/sync/agent-request.ts +2 -2
  425. package/src/sync/agent-runner.ts +2 -2
  426. package/src/sync/agent-store.ts +2 -2
  427. package/src/sync/agent-sync.ts +2 -2
  428. package/src/sync/apply-review.ts +2 -2
  429. package/src/sync/automatic-sync.ts +58 -120
  430. package/src/sync/conflict-artifact-ownership.ts +2 -2
  431. package/src/sync/conflict-artifacts.ts +2 -2
  432. package/src/sync/conflict-groups.ts +2 -2
  433. package/src/sync/conflict-preview.ts +2 -2
  434. package/src/sync/conflict-resolution.ts +2 -2
  435. package/src/sync/conflict-retention.ts +2 -2
  436. package/src/sync/conflict-review.ts +5 -2
  437. package/src/sync/content-conflicts.ts +2 -2
  438. package/src/sync/continuous-errors.ts +2 -2
  439. package/src/sync/continuous-lease.ts +2 -2
  440. package/src/sync/continuous-record.ts +2 -2
  441. package/src/sync/continuous-storage.ts +2 -2
  442. package/src/sync/continuous-sync.ts +2 -2
  443. package/src/sync/continuous-watch.ts +2 -2
  444. package/src/sync/debug-tool-execution.ts +21 -22
  445. package/src/sync/debug-tool.ts +12 -15
  446. package/src/sync/exclude-policy.ts +2 -2
  447. package/src/sync/field-migration.ts +2 -2
  448. package/src/sync/file-merge-planner.ts +2 -2
  449. package/src/sync/json-document.ts +2 -2
  450. package/src/sync/local-diff-review.ts +115 -0
  451. package/src/sync/local-field-policy.ts +2 -2
  452. package/src/sync/local-fields.ts +2 -2
  453. package/src/sync/local-recovery.ts +53 -0
  454. package/src/sync/merge-apply.ts +2 -2
  455. package/src/sync/merge-journal.ts +2 -2
  456. package/src/sync/merge-transfer-error.ts +2 -2
  457. package/src/sync/merged-sync.ts +2 -2
  458. package/src/sync/mutation-owner.ts +2 -2
  459. package/src/sync/package-merge.ts +2 -2
  460. package/src/sync/partial-progress.ts +2 -2
  461. package/src/sync/remote-snapshot.ts +2 -2
  462. package/src/sync/session-merge.ts +2 -2
  463. package/src/sync/settings-conflicts.ts +2 -2
  464. package/src/sync/settings-merge.ts +2 -2
  465. package/src/sync/signals.ts +2 -2
  466. package/src/sync/startup-timings.ts +2 -2
  467. package/src/sync/sync-decision.ts +2 -2
  468. package/src/sync/sync-error-guidance.ts +2 -2
  469. package/src/sync/sync-errors.ts +2 -2
  470. package/src/sync/sync-inspection.ts +46 -11
  471. package/src/sync/sync-local.ts +2 -2
  472. package/src/sync/sync-mutations.ts +2 -2
  473. package/src/sync/sync-operations.ts +143 -33
  474. package/src/sync/sync-policy.ts +2 -2
  475. package/src/sync/sync-queries.ts +2 -2
  476. package/src/sync/sync-state.ts +2 -2
  477. package/src/sync/text-merge.ts +2 -2
  478. package/src/sync-extension.ts +193 -278
  479. package/src/ui/cancellable-operation.ts +1 -1
  480. package/src/ui/diff-review.ts +4 -3
  481. package/src/ui/manager-ui.ts +2 -22
  482. package/dist/chunks/chunk-6YKOHBSC.ts +0 -18
  483. package/dist/chunks/chunk-6YKOHBSC.ts.map +0 -7
  484. package/dist/chunks/chunk-A43CJYG4.ts +0 -26
  485. package/dist/chunks/chunk-A43CJYG4.ts.map +0 -7
  486. package/dist/chunks/chunk-APZVJAEW.ts +0 -34
  487. package/dist/chunks/chunk-APZVJAEW.ts.map +0 -7
  488. package/dist/chunks/chunk-AXN3B5KC.ts.map +0 -7
  489. package/dist/chunks/chunk-GELYN4UC.ts +0 -14
  490. package/dist/chunks/chunk-GELYN4UC.ts.map +0 -7
  491. package/dist/chunks/chunk-IBXEM35O.ts +0 -34
  492. package/dist/chunks/chunk-IBXEM35O.ts.map +0 -7
  493. package/dist/chunks/chunk-KN4NY2VV.ts +0 -1524
  494. package/dist/chunks/chunk-KN4NY2VV.ts.map +0 -7
  495. package/dist/chunks/chunk-LNZRNXNQ.ts.map +0 -7
  496. package/dist/chunks/chunk-NXWHPVXR.ts +0 -26
  497. package/dist/chunks/chunk-NXWHPVXR.ts.map +0 -7
  498. package/dist/chunks/chunk-P4GI7LTT.ts +0 -20
  499. package/dist/chunks/chunk-P4GI7LTT.ts.map +0 -7
  500. package/dist/chunks/chunk-R3SAMXB6.ts +0 -60
  501. package/dist/chunks/chunk-R3SAMXB6.ts.map +0 -7
  502. package/dist/chunks/chunk-R7PN3KIY.ts +0 -22
  503. package/dist/chunks/chunk-R7PN3KIY.ts.map +0 -7
  504. package/dist/chunks/chunk-T3LABNHF.ts +0 -20
  505. package/dist/chunks/chunk-T3LABNHF.ts.map +0 -7
  506. package/dist/chunks/chunk-UMPA5S7X.ts +0 -11
  507. package/dist/chunks/chunk-UMPA5S7X.ts.map +0 -7
  508. package/dist/chunks/chunk-VQTYTUBU.ts.map +0 -7
  509. package/dist/chunks/chunk-ZO52JM4H.ts +0 -15
  510. package/dist/chunks/chunk-ZO52JM4H.ts.map +0 -7
  511. package/dist/chunks/chunk-ZWP6HAYV.ts.map +0 -7
  512. package/dist/chunks/client-debug-F4WFP2YJ.ts +0 -40
  513. package/dist/chunks/client-debug-F4WFP2YJ.ts.map +0 -7
  514. package/dist/chunks/command-handler-GERC7LOE.ts.map +0 -7
  515. package/dist/chunks/conflict-review-XZI7RYZX.ts +0 -18
  516. package/dist/chunks/conflict-review-XZI7RYZX.ts.map +0 -7
  517. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts +0 -67
  518. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts.map +0 -7
  519. package/dist/chunks/diff-review-FLWC5VOT.ts +0 -68
  520. package/dist/chunks/diff-review-FLWC5VOT.ts.map +0 -7
  521. package/dist/chunks/diff-review-GB4NO53B.ts.map +0 -7
  522. package/dist/chunks/manager-result-dispatcher-6MOJPLIS.ts +0 -20
  523. package/dist/chunks/manager-ui-3CQU37XY.ts.map +0 -7
  524. package/dist/chunks/ownership-recovery-5KXAMFSL.ts +0 -59
  525. package/dist/chunks/ownership-recovery-5KXAMFSL.ts.map +0 -7
  526. package/dist/chunks/remote-selection-ui-2V53UBHM.ts +0 -19
  527. package/dist/chunks/setup-switch-WSKVGW7L.ts +0 -27
  528. package/dist/chunks/snapshot-ZUJJZCFW.ts.map +0 -7
  529. package/dist/chunks/snapshot-transaction-directory-F46JWRAU.ts +0 -13
  530. package/dist/chunks/snapshot-transaction-directory-F46JWRAU.ts.map +0 -7
  531. package/dist/chunks/state-directory-CMAIF34J.ts +0 -17
  532. package/dist/chunks/sync-inspection-ECI4BY5N.ts +0 -23
  533. package/dist/chunks/sync-inspection-ECI4BY5N.ts.map +0 -7
  534. package/dist/chunks/sync-operations-KWXZZEPT.ts +0 -52
  535. package/dist/chunks/sync-operations-KWXZZEPT.ts.map +0 -7
  536. package/dist/chunks/sync-state-QIT64TKV.ts.map +0 -7
  537. package/dist/daemon/LICENSE +0 -21
  538. package/dist/daemon/dist/build-id.json +0 -1
  539. package/dist/daemon/dist/build-version.js +0 -28
  540. package/dist/daemon/dist/child-sdk.mjs +0 -17
  541. package/dist/daemon/dist/cli.js +0 -156
  542. package/dist/daemon/dist/client-transport.js +0 -77
  543. package/dist/daemon/dist/client.js +0 -950
  544. package/dist/daemon/dist/consent.js +0 -304
  545. package/dist/daemon/dist/daemon-debug.js +0 -40
  546. package/dist/daemon/dist/daemon-recovery.js +0 -160
  547. package/dist/daemon/dist/daemon-startup.js +0 -350
  548. package/dist/daemon/dist/daemon-status.js +0 -57
  549. package/dist/daemon/dist/daemon-upgrade-error.js +0 -14
  550. package/dist/daemon/dist/diff-review-binding.js +0 -11
  551. package/dist/daemon/dist/diff-review-protocol.js +0 -85
  552. package/dist/daemon/dist/diff-review-rpc.js +0 -37
  553. package/dist/daemon/dist/diff-review-store.js +0 -89
  554. package/dist/daemon/dist/document.js +0 -6
  555. package/dist/daemon/dist/endpoint.js +0 -91
  556. package/dist/daemon/dist/engine/backends/backend-factory.js +0 -16
  557. package/dist/daemon/dist/engine/backends/backend-identity.js +0 -38
  558. package/dist/daemon/dist/engine/backends/backend-types.js +0 -1
  559. package/dist/daemon/dist/engine/backends/git/git-backend.js +0 -775
  560. package/dist/daemon/dist/engine/backends/git/git-config.js +0 -118
  561. package/dist/daemon/dist/engine/backends/git/git-runner.js +0 -237
  562. package/dist/daemon/dist/engine/backends/git/git-storage.js +0 -227
  563. package/dist/daemon/dist/engine/backends/publication-encoding.js +0 -19
  564. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +0 -453
  565. package/dist/daemon/dist/engine/backends/s3/s3-client.js +0 -362
  566. package/dist/daemon/dist/engine/backends/s3/s3-conditions.js +0 -66
  567. package/dist/daemon/dist/engine/backends/snapshot-pointer.js +0 -22
  568. package/dist/daemon/dist/engine/backends/sync-backend.js +0 -39
  569. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +0 -605
  570. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +0 -349
  571. package/dist/daemon/dist/engine/backends/webdav/webdav-config.js +0 -73
  572. package/dist/daemon/dist/engine/commands/command-types.js +0 -1
  573. package/dist/daemon/dist/engine/debug-check.js +0 -59
  574. package/dist/daemon/dist/engine/debug-log.js +0 -252
  575. package/dist/daemon/dist/engine/host.js +0 -20
  576. package/dist/daemon/dist/engine/paths.js +0 -77
  577. package/dist/daemon/dist/engine/settings/config-errors.js +0 -4
  578. package/dist/daemon/dist/engine/settings/config-file.js +0 -784
  579. package/dist/daemon/dist/engine/settings/config.js +0 -246
  580. package/dist/daemon/dist/engine/settings/retired-ignore-policy.js +0 -16
  581. package/dist/daemon/dist/engine/settings/retired-ignore-recovery.js +0 -14
  582. package/dist/daemon/dist/engine/settings/settings-management.js +0 -196
  583. package/dist/daemon/dist/engine/settings/settings-store.js +0 -41
  584. package/dist/daemon/dist/engine/settings/settings-types.js +0 -1
  585. package/dist/daemon/dist/engine/settings/settings-validation.js +0 -390
  586. package/dist/daemon/dist/engine/snapshot/session-paths.js +0 -146
  587. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +0 -347
  588. package/dist/daemon/dist/engine/snapshot/snapshot-bounds.js +0 -20
  589. package/dist/daemon/dist/engine/snapshot/snapshot-capture-limit.js +0 -99
  590. package/dist/daemon/dist/engine/snapshot/snapshot-case-replacement.js +0 -82
  591. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +0 -62
  592. package/dist/daemon/dist/engine/snapshot/snapshot-difference.js +0 -13
  593. package/dist/daemon/dist/engine/snapshot/snapshot-entry-projection.js +0 -78
  594. package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +0 -205
  595. package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +0 -153
  596. package/dist/daemon/dist/engine/snapshot/snapshot-paths.js +0 -11
  597. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +0 -42
  598. package/dist/daemon/dist/engine/snapshot/snapshot-reviewed-preimages.js +0 -60
  599. package/dist/daemon/dist/engine/snapshot/snapshot-root-transition.js +0 -138
  600. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-directory.js +0 -16
  601. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +0 -415
  602. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-plan.js +0 -68
  603. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +0 -202
  604. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-stage.js +0 -303
  605. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-verification.js +0 -78
  606. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +0 -830
  607. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +0 -3
  608. package/dist/daemon/dist/engine/snapshot/snapshot.js +0 -695
  609. package/dist/daemon/dist/engine/state/json-file.js +0 -49
  610. package/dist/daemon/dist/engine/state/lock.js +0 -399
  611. package/dist/daemon/dist/engine/state/lockfile-fs.js +0 -13
  612. package/dist/daemon/dist/engine/state/merge-baseline-store.js +0 -198
  613. package/dist/daemon/dist/engine/state/mutation-directory-sync.js +0 -34
  614. package/dist/daemon/dist/engine/state/operation-availability.js +0 -40
  615. package/dist/daemon/dist/engine/state/state-directory.js +0 -227
  616. package/dist/daemon/dist/engine/state/state-types.js +0 -1
  617. package/dist/daemon/dist/engine/state/sync-state-store.js +0 -58
  618. package/dist/daemon/dist/engine/sync/agent-candidate.js +0 -207
  619. package/dist/daemon/dist/engine/sync/agent-plan.js +0 -84
  620. package/dist/daemon/dist/engine/sync/agent-refusal-retry.js +0 -39
  621. package/dist/daemon/dist/engine/sync/agent-request.js +0 -13
  622. package/dist/daemon/dist/engine/sync/agent-runner.js +0 -183
  623. package/dist/daemon/dist/engine/sync/agent-store.js +0 -177
  624. package/dist/daemon/dist/engine/sync/agent-sync.js +0 -139
  625. package/dist/daemon/dist/engine/sync/apply-review.js +0 -52
  626. package/dist/daemon/dist/engine/sync/conflict-artifact-ownership.js +0 -53
  627. package/dist/daemon/dist/engine/sync/conflict-artifacts.js +0 -158
  628. package/dist/daemon/dist/engine/sync/conflict-groups.js +0 -76
  629. package/dist/daemon/dist/engine/sync/conflict-preview.js +0 -53
  630. package/dist/daemon/dist/engine/sync/conflict-resolution.js +0 -53
  631. package/dist/daemon/dist/engine/sync/conflict-retention.js +0 -61
  632. package/dist/daemon/dist/engine/sync/conflict-review.js +0 -73
  633. package/dist/daemon/dist/engine/sync/content-conflicts.js +0 -70
  634. package/dist/daemon/dist/engine/sync/continuous-errors.js +0 -72
  635. package/dist/daemon/dist/engine/sync/continuous-lease.js +0 -206
  636. package/dist/daemon/dist/engine/sync/continuous-record.js +0 -199
  637. package/dist/daemon/dist/engine/sync/continuous-storage.js +0 -59
  638. package/dist/daemon/dist/engine/sync/continuous-sync.js +0 -549
  639. package/dist/daemon/dist/engine/sync/continuous-watch.js +0 -137
  640. package/dist/daemon/dist/engine/sync/diff-review-capture.js +0 -210
  641. package/dist/daemon/dist/engine/sync/diff-review-preview.js +0 -114
  642. package/dist/daemon/dist/engine/sync/directional-action.js +0 -101
  643. package/dist/daemon/dist/engine/sync/directional-conflict.js +0 -29
  644. package/dist/daemon/dist/engine/sync/exclude-policy.js +0 -86
  645. package/dist/daemon/dist/engine/sync/field-migration.js +0 -20
  646. package/dist/daemon/dist/engine/sync/file-merge-planner.js +0 -123
  647. package/dist/daemon/dist/engine/sync/initialization.js +0 -81
  648. package/dist/daemon/dist/engine/sync/json-document.js +0 -172
  649. package/dist/daemon/dist/engine/sync/local-field-policy.js +0 -26
  650. package/dist/daemon/dist/engine/sync/local-fields.js +0 -161
  651. package/dist/daemon/dist/engine/sync/merge-acceptance.js +0 -29
  652. package/dist/daemon/dist/engine/sync/merge-apply.js +0 -530
  653. package/dist/daemon/dist/engine/sync/merge-journal.js +0 -204
  654. package/dist/daemon/dist/engine/sync/merge-transfer-error.js +0 -64
  655. package/dist/daemon/dist/engine/sync/merged-sync.js +0 -655
  656. package/dist/daemon/dist/engine/sync/mutation-owner.js +0 -18
  657. package/dist/daemon/dist/engine/sync/package-merge.js +0 -82
  658. package/dist/daemon/dist/engine/sync/partial-progress.js +0 -41
  659. package/dist/daemon/dist/engine/sync/push-review.js +0 -18
  660. package/dist/daemon/dist/engine/sync/remote-snapshot.js +0 -119
  661. package/dist/daemon/dist/engine/sync/resolver-stream.js +0 -34
  662. package/dist/daemon/dist/engine/sync/session-merge.js +0 -178
  663. package/dist/daemon/dist/engine/sync/session-push.js +0 -56
  664. package/dist/daemon/dist/engine/sync/settings-conflicts.js +0 -56
  665. package/dist/daemon/dist/engine/sync/settings-merge.js +0 -93
  666. package/dist/daemon/dist/engine/sync/signals.js +0 -8
  667. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +0 -105
  668. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +0 -37
  669. package/dist/daemon/dist/engine/sync/startup-timings.js +0 -116
  670. package/dist/daemon/dist/engine/sync/sync-decision.js +0 -81
  671. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +0 -74
  672. package/dist/daemon/dist/engine/sync/sync-errors.js +0 -38
  673. package/dist/daemon/dist/engine/sync/sync-inspection.js +0 -42
  674. package/dist/daemon/dist/engine/sync/sync-loaders.js +0 -8
  675. package/dist/daemon/dist/engine/sync/sync-local.js +0 -96
  676. package/dist/daemon/dist/engine/sync/sync-mutations.js +0 -723
  677. package/dist/daemon/dist/engine/sync/sync-operations.js +0 -3
  678. package/dist/daemon/dist/engine/sync/sync-policy.js +0 -530
  679. package/dist/daemon/dist/engine/sync/sync-queries.js +0 -316
  680. package/dist/daemon/dist/engine/sync/sync-rollback.js +0 -180
  681. package/dist/daemon/dist/engine/sync/sync-state.js +0 -119
  682. package/dist/daemon/dist/engine/sync/text-merge.js +0 -124
  683. package/dist/daemon/dist/engine/sync/transfer-freshness.js +0 -79
  684. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +0 -88
  685. package/dist/daemon/dist/engine/types.js +0 -2
  686. package/dist/daemon/dist/engine/ui/merge-review.js +0 -7
  687. package/dist/daemon/dist/engine/ui/merged-sync-summary.js +0 -86
  688. package/dist/daemon/dist/engine/ui/sync-format.js +0 -123
  689. package/dist/daemon/dist/engine/ui/sync-status.js +0 -30
  690. package/dist/daemon/dist/engine/ui/terminal-text.js +0 -9
  691. package/dist/daemon/dist/engine/ui/transfer-changes.js +0 -24
  692. package/dist/daemon/dist/engine/ui/transfer-review.js +0 -18
  693. package/dist/daemon/dist/engine-service.js +0 -506
  694. package/dist/daemon/dist/foreground-queue-outcome.js +0 -9
  695. package/dist/daemon/dist/foreground-transfer.js +0 -10
  696. package/dist/daemon/dist/identity.js +0 -275
  697. package/dist/daemon/dist/idle-exit.js +0 -77
  698. package/dist/daemon/dist/index.js +0 -27
  699. package/dist/daemon/dist/legacy-consent-guard.js +0 -34
  700. package/dist/daemon/dist/lifecycle-log.js +0 -54
  701. package/dist/daemon/dist/lifecycle.js +0 -21
  702. package/dist/daemon/dist/model-signature.js +0 -7
  703. package/dist/daemon/dist/paged-review.js +0 -177
  704. package/dist/daemon/dist/participant-admission.js +0 -30
  705. package/dist/daemon/dist/participant-ledger.js +0 -149
  706. package/dist/daemon/dist/protocol.js +0 -108
  707. package/dist/daemon/dist/resolver-host.js +0 -78
  708. package/dist/daemon/dist/server.js +0 -1374
  709. package/dist/daemon/dist/service-host.js +0 -260
  710. package/dist/daemon/dist/session-presence.js +0 -207
  711. package/dist/daemon/dist/state-wait-jobs.js +0 -23
  712. package/dist/daemon/dist/state-wait.js +0 -34
  713. package/dist/daemon/dist/upgrade-repair.js +0 -55
  714. package/dist/daemon/package.json +0 -3
  715. package/dist/package.json +0 -6
  716. package/src/daemon/apply-gate.ts +0 -146
  717. package/src/daemon/client-debug.ts +0 -50
  718. package/src/daemon/daemon-status-ui.ts +0 -64
  719. package/src/daemon/diff-review.ts +0 -68
  720. package/src/daemon/directional-recovery.ts +0 -106
  721. package/src/daemon/ownership-recovery.ts +0 -50
  722. package/src/daemon/pi-client.ts +0 -1300
  723. package/src/daemon/queue-release-ui.ts +0 -88
  724. package/src/daemon/recovery.ts +0 -103
  725. package/src/daemon/startup-bootstrap-client.ts +0 -26
  726. /package/dist/chunks/{manager-result-dispatcher-6MOJPLIS.ts.map → chunk-3GL7LBNB.ts.map} +0 -0
  727. /package/dist/chunks/{remote-selection-ui-2V53UBHM.ts.map → chunk-3PFWVSV3.ts.map} +0 -0
  728. /package/dist/chunks/{setup-switch-WSKVGW7L.ts.map → chunk-53IKSWLZ.ts.map} +0 -0
  729. /package/dist/chunks/{state-directory-CMAIF34J.ts.map → chunk-A3NEEVNA.ts.map} +0 -0
  730. /package/dist/chunks/{sync-state-store-TZE7XDV5.ts.map → chunk-AITZUACB.ts.map} +0 -0
  731. /package/dist/chunks/{chunk-WE3KJ7JS.ts.map → chunk-IFJXUHHC.ts.map} +0 -0
  732. /package/dist/chunks/{chunk-HFMGK6A6.ts.map → chunk-YLVRV6NM.ts.map} +0 -0
  733. /package/dist/chunks/{merge-review-DXSERTCK.ts.map → merge-review-RMDYVNBK.ts.map} +0 -0
  734. /package/{dist/daemon/dist/engine/state/lock-policy.js → src/engine/state/lock-policy.ts} +0 -0
@@ -0,0 +1,2499 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ backupSnapshot,
5
+ protectedSessionPaths
6
+ } from "./chunk-JPLT2DG6.ts";
7
+ import {
8
+ conflictArtifactFingerprint,
9
+ conflictDirectory,
10
+ conflictGroups,
11
+ readConflictArtifact,
12
+ saveConflictArtifact
13
+ } from "./chunk-2BMTS5OW.ts";
14
+ import {
15
+ clearMergeJournal,
16
+ mergeJournalIdentity,
17
+ readMergeJournal,
18
+ sameMergeRecoveryHead,
19
+ writeMergeJournal
20
+ } from "./chunk-2G6GTIWW.ts";
21
+ import {
22
+ mergeAcceptedSettingsPackages,
23
+ mergeSettingsJson,
24
+ resolveContentConflicts
25
+ } from "./chunk-3M3KQFSQ.ts";
26
+ import {
27
+ createSyncBackend
28
+ } from "./chunk-ZWOKNJDT.ts";
29
+ import {
30
+ formatRemoteSelectionStatus,
31
+ readSnapshotForHead,
32
+ requireCompatibleRemoteSelection,
33
+ safeTerminalText,
34
+ snapshotPathLabel
35
+ } from "./chunk-MHERAG42.ts";
36
+ import {
37
+ acceptedSelection,
38
+ fileHashMap,
39
+ hasLocalChanges,
40
+ hasRemoteChanges,
41
+ sameHashes,
42
+ syncPolicyChanged
43
+ } from "./chunk-D34Y5JSL.ts";
44
+ import {
45
+ ContinuousError,
46
+ TransferSizeError
47
+ } from "./chunk-KDTDGAOM.ts";
48
+ import {
49
+ SyncBackendConflictError,
50
+ expectedRemoteHead
51
+ } from "./chunk-DLA5RPFP.ts";
52
+ import {
53
+ startupTransferEnabled
54
+ } from "./chunk-2YHXXWUF.ts";
55
+ import {
56
+ TEXT_MERGE_WORK_LIMIT,
57
+ hasCurrentMergeBaseline,
58
+ pruneMergeBaselines,
59
+ readMergeAncestor,
60
+ readMergeAncestors,
61
+ stageMergeBaseline
62
+ } from "./chunk-YVHXQZIH.ts";
63
+ import {
64
+ applySnapshotTransaction,
65
+ assertCanonicalMutationTargets,
66
+ assertProjectedAgentDirectoryBudget,
67
+ createMutationParents,
68
+ recheckAgentDirectoryBudget,
69
+ recoverPendingSnapshotTransactions,
70
+ syncMutationParents
71
+ } from "./chunk-A7KJUFLX.ts";
72
+ import {
73
+ readStateForConfig,
74
+ statePathForConfig,
75
+ syncStateFingerprint,
76
+ writeStateForConfig
77
+ } from "./chunk-NFW5HLKA.ts";
78
+ import {
79
+ syncDirectory
80
+ } from "./chunk-ESUMO4TW.ts";
81
+ import {
82
+ captureMutationOwner
83
+ } from "./chunk-QJTU5SCJ.ts";
84
+ import {
85
+ SyncDecisionRequiredError
86
+ } from "./chunk-4S5CGN4M.ts";
87
+ import {
88
+ createStartupTimings
89
+ } from "./chunk-D3DMJSFU.ts";
90
+ import {
91
+ loadConfig,
92
+ syncCheckConfigFingerprint,
93
+ syncConfigReviewIdentity
94
+ } from "./chunk-AVLYLWA7.ts";
95
+ import {
96
+ stateDir
97
+ } from "./chunk-NFZMKZ2D.ts";
98
+ import {
99
+ overlayLocalFields,
100
+ portableSnapshot,
101
+ sameLocalFields
102
+ } from "./chunk-C2YD64T6.ts";
103
+ import {
104
+ MAX_AGENT_DIRECTORY_BYTES,
105
+ agentDirectoryConfiguredSessionDir,
106
+ agentDirectoryInventory,
107
+ assertAgentDirectorySnapshotBound,
108
+ createSnapshot,
109
+ decodeBase64Strict,
110
+ filterSnapshotForConfigPolicy,
111
+ isSessionFilePath,
112
+ isSessionPath,
113
+ mergeRemotePreservedFiles,
114
+ observeSnapshot,
115
+ regenerateSnapshotIdentity,
116
+ scanSnapshot,
117
+ snapshotBase64Size,
118
+ snapshotIncludesSessions,
119
+ snapshotTarget,
120
+ snapshotWithObservedInventory
121
+ } from "./chunk-WETDHZAD.ts";
122
+ import {
123
+ agentDir,
124
+ agentDirectoryPhysicalSessionPath,
125
+ assertUnexcludedTargets,
126
+ effectiveSessionRoot,
127
+ requireStableMergeSessionRoot,
128
+ sessionStorageRoot,
129
+ snapshotOptionsForContext
130
+ } from "./chunk-RRFW2UAD.ts";
131
+ import {
132
+ collidingPaths,
133
+ mergePathIdentity,
134
+ planFileMerge
135
+ } from "./chunk-ULNEZ53E.ts";
136
+ import {
137
+ assertSnapshotExcludesDebugLog,
138
+ compileSyncPolicyExclude,
139
+ configuredSnapshotPathMatcher,
140
+ includeFromSelectionConfig,
141
+ inspectRemoteSelection,
142
+ requireLegacyTransferPolicy,
143
+ syncSessionsSelected
144
+ } from "./chunk-OTI4XVCS.ts";
145
+ import {
146
+ engineHost,
147
+ withEngineMutationQueue,
148
+ withSessionWriteProtection
149
+ } from "./chunk-ES4FIIHZ.ts";
150
+ import {
151
+ assertWithinRoot,
152
+ isDeniedPath,
153
+ isPathInside,
154
+ parentPaths,
155
+ safeJoin,
156
+ toPosix
157
+ } from "./chunk-C66HLRRZ.ts";
158
+
159
+ // src/engine/ui/merge-review.ts
160
+ async function confirmMergeReview(ctx, title, content, signal, isCurrent, confirmationLabel = "apply changes", summaryLines) {
161
+ if (signal?.aborted || !isCurrent()) return false;
162
+ const result = await engineHost().review(ctx, { title, content, confirmationLabel, summaryLines }, signal, isCurrent);
163
+ return !signal?.aborted && isCurrent() && result;
164
+ }
165
+
166
+ // src/engine/ui/merged-sync-summary.ts
167
+ import { truncateToWidth } from "@earendil-works/pi-tui";
168
+
169
+ // src/engine/ui/transfer-changes.ts
170
+ function transferChanges(before, after, protectedPaths = /* @__PURE__ */ new Set()) {
171
+ const beforeMap = before ? fileHashMap(before) : {};
172
+ const afterMap = fileHashMap(after);
173
+ return [.../* @__PURE__ */ new Set([...Object.keys(beforeMap), ...Object.keys(afterMap)])].sort().flatMap((filePath) => {
174
+ if (protectedPaths.has(filePath)) return [];
175
+ if (!Object.hasOwn(beforeMap, filePath)) return [{ path: filePath, action: "Add" }];
176
+ if (!Object.hasOwn(afterMap, filePath)) return [{ path: filePath, action: "Delete" }];
177
+ return beforeMap[filePath] !== afterMap[filePath] ? [{ path: filePath, action: "Update" }] : [];
178
+ });
179
+ }
180
+ function transferCounts(changes) {
181
+ return {
182
+ add: changes.filter((change) => change.action === "Add").length,
183
+ update: changes.filter((change) => change.action === "Update").length,
184
+ remove: changes.filter((change) => change.action === "Delete").length
185
+ };
186
+ }
187
+
188
+ // src/engine/ui/merged-sync-summary.ts
189
+ function mergedSyncSummary(input) {
190
+ const local = transferChanges(input.localBefore, input.localAfter);
191
+ const remote = transferChanges(input.remoteBefore, input.remoteAfter);
192
+ const all = [...local, ...remote];
193
+ const updatesOnly = all.length > 0 && all.every((change) => change.action === "Update");
194
+ const verb = updatesOnly ? "Update" : "Apply changes to";
195
+ const title = local.length && remote.length ? "Apply local and remote changes?" : all.length ? `${verb} ${all.length} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}?` : input.publish ? "Publish a new remote snapshot?" : "Pi Sync is already up to date.";
196
+ const confirmationLabel = local.length && remote.length ? "apply local and remote changes" : all.length ? `${updatesOnly ? "update" : "apply changes to"} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}` : "publish remote snapshot";
197
+ const sources = new Map(
198
+ input.decisions.filter((item) => item.kind === "accepted").map((item) => [item.path, item.source])
199
+ );
200
+ const label = (change, side) => {
201
+ const source = sources.get(change.path);
202
+ const suffix = source === "merged" ? " (merged content)" : side === "local" && source === "remote" ? change.action === "Delete" ? " (deleted remotely)" : " from remote" : "";
203
+ return `${change.action} ${snapshotPathLabel(change.path)}${suffix}`;
204
+ };
205
+ const section = (items, side, compact) => {
206
+ const heading = side === "local" ? "Local changes" : "Remote file changes";
207
+ if (!items.length) return [`${heading}: none`];
208
+ const counts = ["Add", "Update", "Delete"].flatMap((action) => {
209
+ const count = items.filter((item) => item.action === action).length;
210
+ return count ? [`${count} ${action.toLowerCase()}`] : [];
211
+ });
212
+ return [
213
+ `${heading}: ${counts.join(", ")}`,
214
+ ...(compact ? items.slice(0, 3) : items).map(
215
+ (item) => ` ${compact ? truncateToWidth(label(item, side), 80) : label(item, side)}`
216
+ ),
217
+ ...compact && items.length > 3 ? [` ${items.length - 3} more files \u2014 View details`] : []
218
+ ];
219
+ };
220
+ const context = [`Setup: ${safeTerminalText(input.setupName)}`, `Remote: ${safeTerminalText(input.destination)}`];
221
+ const safety = [
222
+ `Remote snapshot publication: ${input.publish ? "yes" : "no"}`,
223
+ "Remote removals affect the active snapshot; retained history is not erased.",
224
+ `Sessions: ${input.sessions ? "included \u2014 may contain private conversations" : "not included"}`,
225
+ input.groups.length ? `Unresolved groups: ${input.groups.length} \u2014 these paths stay unchanged on each side` : "Conflicts: none",
226
+ ...input.publish && input.capability === "read-check-write-verify" ? ["Warning: simultaneous remote writes can still race; visible changes are rejected."] : [],
227
+ ...input.publish && input.capability === "conditional-required" ? ["Remote publication requires verified conditional writes; verification failure stops the transfer."] : [],
228
+ "The current session is protected. A backup and recovery journal will be saved.",
229
+ "Resources will not reload automatically."
230
+ ];
231
+ return {
232
+ title,
233
+ confirmationLabel,
234
+ lines: [
235
+ ...context.map((line) => truncateToWidth(line, 100)),
236
+ ...section(local, "local", true),
237
+ ...section(remote, "remote", true),
238
+ ...safety
239
+ ],
240
+ content: [
241
+ ...context,
242
+ "",
243
+ ...section(local, "local", false),
244
+ "",
245
+ ...section(remote, "remote", false),
246
+ "",
247
+ ...safety,
248
+ ...input.groups.flatMap(
249
+ (group) => group.paths.map((filePath) => `Unchanged (unresolved): ${snapshotPathLabel(filePath)}`)
250
+ )
251
+ ].join("\n")
252
+ };
253
+ }
254
+
255
+ // src/engine/sync/conflict-artifact-ownership.ts
256
+ import fs from "node:fs/promises";
257
+ import path from "node:path";
258
+ async function releaseConflictArtifacts(config, statePath, created) {
259
+ if (!created.length || statePathForConfig(config) !== statePath) return;
260
+ try {
261
+ const state = await readStateForConfig(config);
262
+ if (statePathForConfig(config) !== statePath) return;
263
+ const journal = await readMergeJournal(config);
264
+ if (statePathForConfig(config) !== statePath) return;
265
+ const referenced = /* @__PURE__ */ new Set([
266
+ ...(state.unresolved ?? []).map((group) => group.artifact),
267
+ ...(journal?.progress?.groups ?? []).map((group) => group.artifact)
268
+ ]);
269
+ for (const lease of created) {
270
+ if (referenced.has(lease.token) || lease.target !== path.join(conflictDirectory(config), `${lease.token}.json`))
271
+ continue;
272
+ try {
273
+ const stat = await fs.lstat(lease.target);
274
+ if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== lease.dev || stat.ino !== lease.ino || stat.size !== lease.size)
275
+ continue;
276
+ const artifact = JSON.parse(await fs.readFile(lease.target, "utf8"));
277
+ if (conflictArtifactFingerprint(artifact) !== lease.fingerprint || statePathForConfig(config) !== statePath)
278
+ continue;
279
+ const latest = await fs.lstat(lease.target);
280
+ if (latest.dev !== lease.dev || latest.ino !== lease.ino || latest.nlink !== 1 || statePathForConfig(config) !== statePath)
281
+ continue;
282
+ await fs.unlink(lease.target);
283
+ await syncDirectory(path.dirname(lease.target));
284
+ } catch {
285
+ }
286
+ }
287
+ } catch {
288
+ }
289
+ }
290
+
291
+ // src/engine/sync/conflict-resolution.ts
292
+ async function resolveReviewedGroup(config, backend, state, local, remote, head, plan, resolution, protectedPaths) {
293
+ const artifact = await readConflictArtifact(config, backend.identity, resolution.token);
294
+ const group = artifact.groups[resolution.group];
295
+ if (conflictArtifactFingerprint(artifact) !== resolution.artifactIdentity || !group || plan.kind !== "planned" || !state.unresolved?.some(
296
+ (item) => item.artifact === resolution.token && JSON.stringify(item.paths) === JSON.stringify(group.paths)
297
+ ) || syncStateFingerprint(state) !== resolution.stateIdentity || state.lastObservedSnapshot !== head.snapshotId || !state.lastObservedRevision || !backend.sameRevision(state.lastObservedRevision, head.revision))
298
+ throw new Error("Conflict review is stale; refresh sync and review again.");
299
+ const ours = fileHashMap(local);
300
+ const theirs = fileHashMap(remote);
301
+ const oldOurs = fileHashMap(artifact.local);
302
+ const oldTheirs = fileHashMap(artifact.remote);
303
+ if (group.paths.some(
304
+ (filePath) => ours[filePath] !== oldOurs[filePath] || theirs[filePath] !== oldTheirs[filePath] || state.lastFileHashes[filePath] !== artifact.state.lastFileHashes[filePath]
305
+ ))
306
+ throw new Error("Conflict versions changed; no resolution was applied.");
307
+ if (group.paths.some(
308
+ (filePath) => [...protectedPaths].some((value) => mergePathIdentity(value) === mergePathIdentity(filePath))
309
+ ))
310
+ throw new Error(
311
+ "Current session conflict cannot be resolved from the loaded session; preserve evidence and close Pi."
312
+ );
313
+ const selected = resolution.source === "local" ? local : remote;
314
+ const paths = new Set(group.paths);
315
+ for (const snapshot of [selected, local]) {
316
+ const layout = planFileMerge({
317
+ baseline: {},
318
+ local: snapshot.files.filter((file) => paths.has(file.path)),
319
+ remote: [],
320
+ selectionCompatible: true
321
+ });
322
+ if (layout.kind !== "planned" || layout.conflicts.length)
323
+ throw new Error(
324
+ "Selected/current local group still has path collisions; preserve evidence, repair the layout manually and refresh sync."
325
+ );
326
+ }
327
+ const selectedFiles = new Map(selected.files.map((file) => [file.path, file]));
328
+ const decisions = plan.decisions.map(
329
+ (item) => paths.has(item.path) ? {
330
+ kind: "accepted",
331
+ path: item.path,
332
+ source: resolution.source,
333
+ file: selectedFiles.get(item.path)
334
+ } : item
335
+ );
336
+ return {
337
+ kind: "planned",
338
+ decisions,
339
+ conflicts: decisions.filter((item) => item.kind === "conflict")
340
+ };
341
+ }
342
+
343
+ // src/engine/sync/conflict-retention.ts
344
+ import fs2 from "node:fs/promises";
345
+ import path2 from "node:path";
346
+ async function pruneCompletedConflicts(config, backend, state, local, remote, validate) {
347
+ validate();
348
+ const directory = conflictDirectory(config);
349
+ let names;
350
+ try {
351
+ const stat = await fs2.lstat(directory);
352
+ validate();
353
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe conflict retention directory.");
354
+ names = await fs2.readdir(directory);
355
+ validate();
356
+ } catch (error) {
357
+ if (error.code === "ENOENT") return;
358
+ throw error;
359
+ }
360
+ const pinned = new Set(state.unresolved?.map((group) => group.artifact) ?? []);
361
+ const ours = fileHashMap(local);
362
+ const theirs = fileHashMap(remote);
363
+ const completed = [];
364
+ for (const name of names) {
365
+ validate();
366
+ const token = name.replace(/\.json$/u, "");
367
+ if (!/^[a-f0-9-]{36}\.json$/u.test(name) || pinned.has(token)) continue;
368
+ try {
369
+ const artifact = await readConflictArtifact(config, backend, token);
370
+ validate();
371
+ const originalLocal = fileHashMap(artifact.local);
372
+ const originalRemote = fileHashMap(artifact.remote);
373
+ if (!artifact.groups.every(
374
+ (group) => group.paths.every(
375
+ (filePath) => state.lastFileHashes[filePath] === ours[filePath] && ours[filePath] === theirs[filePath] && (ours[filePath] === originalLocal[filePath] || ours[filePath] === originalRemote[filePath])
376
+ )
377
+ ))
378
+ continue;
379
+ const stat = await fs2.lstat(path2.join(directory, name));
380
+ validate();
381
+ if (stat.isFile()) completed.push({ token, modified: stat.mtimeMs });
382
+ } catch {
383
+ validate();
384
+ }
385
+ }
386
+ completed.sort((left, right) => right.modified - left.modified || left.token.localeCompare(right.token));
387
+ for (const entry of completed.slice(32)) {
388
+ validate();
389
+ await fs2.rm(path2.join(directory, `${entry.token}.json`));
390
+ validate();
391
+ }
392
+ if (completed.length > 32) {
393
+ await syncDirectory(directory);
394
+ validate();
395
+ }
396
+ }
397
+
398
+ // src/engine/sync/partial-progress.ts
399
+ function acceptedMergeFiles(decisions, localFiles, withheld) {
400
+ const localByPath = new Map(localFiles.map((file) => [file.path, file]));
401
+ return decisions.flatMap((decision) => {
402
+ const file = withheld.has(decision.path) ? localByPath.get(decision.path) : decision.kind === "accepted" ? decision.file : void 0;
403
+ return file ? [file] : [];
404
+ });
405
+ }
406
+ function progressState(config, head, snapshot, progress) {
407
+ const withheld = new Set(progress.groups.flatMap((group) => group.paths));
408
+ const current = fileHashMap(snapshot);
409
+ const hashes = Object.assign(/* @__PURE__ */ Object.create(null), progress.previous.lastFileHashes);
410
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(hashes), ...Object.keys(current)])) {
411
+ if (withheld.has(key)) continue;
412
+ const value = current[key];
413
+ if (value === void 0) delete hashes[key];
414
+ else hashes[key] = value;
415
+ }
416
+ return {
417
+ ...progress.previous,
418
+ version: 3,
419
+ profile: config.snapshotIdentity,
420
+ lastFileHashes: hashes,
421
+ ...acceptedSelection(config),
422
+ ...config.exclude === void 0 ? { exclude: void 0 } : {},
423
+ ...config.scope === void 0 ? { scope: void 0 } : {},
424
+ ...config.reinclude === void 0 ? { reinclude: void 0 } : {},
425
+ localFields: config.localFields,
426
+ lastObservedSnapshot: head.snapshotId,
427
+ lastObservedRevision: head.revision,
428
+ unresolved: progress.groups
429
+ };
430
+ }
431
+
432
+ // src/engine/sync/merge-acceptance.ts
433
+ function matchesAcceptedState(state, config, head, snapshot, progress) {
434
+ return [true, false].some(
435
+ (canonical) => syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical))
436
+ );
437
+ }
438
+ function acceptedState(config, head, snapshot, progress, canonical = true) {
439
+ if (progress) return progressState(config, head, snapshot, progress);
440
+ return {
441
+ version: 1,
442
+ profile: config.snapshotIdentity,
443
+ lastAppliedSnapshot: head.snapshotId,
444
+ lastRemoteRevision: head.revision,
445
+ lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
446
+ ...acceptedSelection(config),
447
+ ...config.localFields !== void 0 ? { localFields: config.localFields } : {}
448
+ };
449
+ }
450
+ async function writeAcceptedState(config, head, snapshot, validate, progress) {
451
+ const accepted = portableSnapshot(snapshot, config.localFields);
452
+ const state = acceptedState(config, head, accepted, progress);
453
+ await stageMergeBaseline(config, accepted, state, progress?.previous);
454
+ await validate();
455
+ await writeStateForConfig(config, state);
456
+ await validate();
457
+ }
458
+
459
+ // src/engine/sync/merge-apply.ts
460
+ import { createHash as createHash3, randomUUID } from "node:crypto";
461
+ import { constants } from "node:fs";
462
+ import fs4 from "node:fs/promises";
463
+ import path5 from "node:path";
464
+
465
+ // src/engine/snapshot/snapshot-apply.ts
466
+ import { createHash as createHash2 } from "node:crypto";
467
+ import fs3 from "node:fs/promises";
468
+ import path4 from "node:path";
469
+
470
+ // src/engine/snapshot/snapshot-reviewed-preimages.ts
471
+ import { createHash } from "node:crypto";
472
+ import path3 from "node:path";
473
+ function image(entry) {
474
+ if (entry === "unreviewed" || typeof entry !== "string" && entry.unreviewed)
475
+ throw new Error("Reviewed directory contains an unreviewed entry; no replacement is authorized.");
476
+ if (typeof entry === "string") return entry;
477
+ const rows = [...entry.entries.keys()].sort().map((name) => [name, image(entry.entries.get(name))]);
478
+ return `directory:${createHash("sha256").update(JSON.stringify(rows)).digest("hex")}`;
479
+ }
480
+ function reviewedSnapshotPreimages(root, sessionDir, reviewed, plan, inventory) {
481
+ const images = /* @__PURE__ */ new Map();
482
+ function insert(target, entry) {
483
+ const existing = images.get(target);
484
+ if (existing) {
485
+ if (typeof entry === "string" || typeof existing === "string")
486
+ throw new Error("Reviewed paths conflict before apply.");
487
+ return;
488
+ }
489
+ images.set(target, entry);
490
+ for (let parent = path3.dirname(target); parent !== target; parent = path3.dirname(target)) {
491
+ const existing2 = images.get(parent);
492
+ if (typeof existing2 === "string") throw new Error("Reviewed paths conflict before apply.");
493
+ const directory = existing2 ?? { entries: /* @__PURE__ */ new Map() };
494
+ directory.entries.set(path3.basename(target), entry);
495
+ if (existing2) break;
496
+ images.set(parent, directory);
497
+ target = parent;
498
+ entry = directory;
499
+ }
500
+ }
501
+ for (const file of reviewed) insert(snapshotTarget(root, file.path, sessionDir), `file:${file.sha256}`);
502
+ if (inventory) {
503
+ for (const [target, kind] of inventory.entries) {
504
+ if (kind === "directory") insert(target, { entries: /* @__PURE__ */ new Map() });
505
+ }
506
+ for (const [target, kind] of inventory.entries) {
507
+ if (kind !== "unreviewed") continue;
508
+ const entry = images.get(target);
509
+ if (entry && typeof entry !== "string") entry.unreviewed = true;
510
+ const parent = images.get(path3.dirname(target));
511
+ if (parent && typeof parent !== "string") parent.entries.set(path3.basename(target), "unreviewed");
512
+ }
513
+ }
514
+ const targets = /* @__PURE__ */ new Set([...plan.deletes, ...plan.writes.map(({ target }) => target)]);
515
+ return new Map(
516
+ [...targets].map((target) => {
517
+ const entry = inventory?.entries.get(target) === "unreviewed" ? "unreviewed" : images.get(target);
518
+ return [target, entry === void 0 ? "missing" : image(entry)];
519
+ })
520
+ );
521
+ }
522
+
523
+ // src/engine/snapshot/snapshot-apply.ts
524
+ function sha256(value) {
525
+ return createHash2("sha256").update(value).digest("hex");
526
+ }
527
+ function fileHashMap2(snapshot) {
528
+ return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
529
+ }
530
+ async function applySnapshot(snapshot, protectedRelativePaths = /* @__PURE__ */ new Set(), options = {}) {
531
+ requireLegacyTransferPolicy(snapshot);
532
+ assertSnapshotExcludesDebugLog(snapshot);
533
+ const root = agentDir();
534
+ if (snapshot.version === 5 && options.scope !== "agent-directory")
535
+ throw new Error("Agent-directory snapshot apply requires the local agent-directory policy.");
536
+ const sessionDir = options.scope === "agent-directory" ? sessionStorageRoot(root, options.sessionDir ?? await agentDirectoryConfiguredSessionDir(options.signal, root)) : options.sessionDir;
537
+ options.validateMutation?.();
538
+ options = { ...options, sessionDir };
539
+ const excluded = excludedApplyPath(root, options);
540
+ snapshot = { ...snapshot, files: snapshot.files.filter((file) => !excluded(file.path)) };
541
+ const transactionOptions = {
542
+ ...options,
543
+ protectedTargets: [...protectedRelativePaths].map((relative) => snapshotTarget(root, relative, sessionDir)),
544
+ expectedPreimages: new Map(
545
+ Object.entries(options.expectedFileHashes ?? {}).filter(([relative]) => !excluded(relative)).map(([relative, hash]) => [
546
+ snapshotTarget(root, relative, sessionDir),
547
+ hash === null ? "missing" : `file:${hash}`
548
+ ])
549
+ )
550
+ };
551
+ options.validateMutation?.();
552
+ await recoverPendingSnapshotTransactions(transactionOptions);
553
+ const current = await createSnapshot(snapshot.profile, {
554
+ ...options,
555
+ ...options.scope === void 0 && options.include === void 0 ? { syncSessions: snapshotIncludesSessions(snapshot) } : {},
556
+ sessionDir
557
+ });
558
+ const inventory = agentDirectoryInventory(current);
559
+ if (options.reviewedLocal && !sameReviewedFiles(current, options.reviewedLocal))
560
+ throw new Error("Reviewed local files changed before apply; reopen the transfer preview.");
561
+ if (options.scope === "agent-directory") {
562
+ assertAgentDirectorySnapshotBound([
563
+ ...snapshot.files.filter(({ path: path6 }) => !protectedRelativePaths.has(path6)),
564
+ ...current.files.filter(({ path: path6 }) => protectedRelativePaths.has(path6))
565
+ ]);
566
+ }
567
+ const plan = await addTopLevelCaseVariantDeletes(
568
+ root,
569
+ protectSnapshotApplyPlan(
570
+ root,
571
+ preflightSnapshotApply(root, snapshot, current, options),
572
+ protectedRelativePaths,
573
+ sessionDir
574
+ ),
575
+ snapshot,
576
+ options
577
+ );
578
+ const currentHashes = new Map(current.files.map(({ path: path6, sha256: sha2562 }) => [path6, sha2562]));
579
+ const dependencies = collidingPaths([...plan.deletes, ...plan.writes.map(({ target }) => target)].map(toPosix));
580
+ const unchangedHashes = /* @__PURE__ */ new Map();
581
+ for (const file of snapshot.files) {
582
+ if (currentHashes.get(file.path) !== file.sha256) continue;
583
+ const target = snapshotTarget(root, file.path, sessionDir);
584
+ if (!dependencies.has(toPosix(target))) unchangedHashes.set(target, file.sha256);
585
+ }
586
+ if (inventory) {
587
+ assertProjectedAgentDirectoryBudget(
588
+ inventory,
589
+ {
590
+ deletes: plan.deletes,
591
+ writes: [
592
+ ...plan.writes.map(({ target, content }) => ({ target, size: content.length })),
593
+ { target: stateDir(root) }
594
+ ]
595
+ },
596
+ options
597
+ );
598
+ }
599
+ const skipped = inventory ? await preflightSnapshotMutations(root, plan, sessionDir, options, unchangedHashes) : void 0;
600
+ if (options.reviewedLocal || inventory) {
601
+ const images = reviewedSnapshotPreimages(root, sessionDir, current.files, plan, inventory);
602
+ const reviewed = options.reviewedLocal;
603
+ if (reviewed && inventory) {
604
+ const approved = reviewedSnapshotPreimages(
605
+ root,
606
+ sessionDir,
607
+ reviewed.files,
608
+ plan,
609
+ agentDirectoryInventory(reviewed)
610
+ );
611
+ if ([...images].some(([target, image2]) => image2 !== approved.get(target)))
612
+ throw new Error("Reviewed directory preimage changed before apply; reopen the transfer preview.");
613
+ }
614
+ for (const [target, image2] of images) {
615
+ const existing = transactionOptions.expectedPreimages.get(target);
616
+ if (existing !== void 0 && existing !== image2) throw new Error("Reviewed preimage evidence is inconsistent.");
617
+ transactionOptions.expectedPreimages.set(target, image2);
618
+ }
619
+ }
620
+ await applySnapshotTransaction(
621
+ plan,
622
+ transactionOptions,
623
+ skipped ?? await preflightSnapshotMutations(root, plan, sessionDir, options, unchangedHashes)
624
+ );
625
+ return appliedFileHashMap(snapshot, current, protectedRelativePaths);
626
+ }
627
+ function sameReviewedFiles(scanned, reviewed) {
628
+ const hashes = new Map(scanned.files.map((file) => [file.path, file.sha256]));
629
+ return scanned.files.length === reviewed.files.length && reviewed.files.every((file) => hashes.get(file.path) === file.sha256);
630
+ }
631
+ function preflightSnapshotApply(root, snapshot, current, options = {}) {
632
+ requireLegacyTransferPolicy(snapshot);
633
+ assertSnapshotExcludesDebugLog(snapshot);
634
+ const seenPaths = /* @__PURE__ */ new Set();
635
+ const remotePaths = /* @__PURE__ */ new Set();
636
+ const writes = [];
637
+ const deletes = [];
638
+ const excluded = excludedApplyPath(root, options);
639
+ for (const file of snapshot.files) {
640
+ const normalized = toPosix(file.path);
641
+ if (options.scope === "agent-directory" && excluded(normalized)) continue;
642
+ if (!isSafeSnapshotPath(file.path)) {
643
+ throw new Error(`Unsafe path in snapshot: ${file.path}`);
644
+ }
645
+ if (isSessionPath(normalized) && !isSessionFilePath(normalized)) {
646
+ throw new Error(`Unsafe session path in snapshot: ${file.path}`);
647
+ }
648
+ if (excluded(normalized)) continue;
649
+ if (seenPaths.has(normalized)) throw new Error(`Duplicate path in snapshot: ${normalized}`);
650
+ seenPaths.add(normalized);
651
+ remotePaths.add(normalized);
652
+ const target = snapshotTarget(root, normalized, options.sessionDir);
653
+ const content = decodeBase64Strict(file.contentBase64, normalized);
654
+ if (sha256(content) !== file.sha256) throw new Error(`Checksum mismatch in snapshot file: ${normalized}`);
655
+ writes.push({ target, content });
656
+ }
657
+ const deletePaths = /* @__PURE__ */ new Set();
658
+ const inventory = options.scope === "agent-directory" ? agentDirectoryInventory(current) : void 0;
659
+ for (const { target } of writes) {
660
+ if (inventory?.entries.get(target) === "directory") deletePaths.add(target);
661
+ }
662
+ for (const file of current.files) {
663
+ const normalized = toPosix(file.path);
664
+ if (excluded(normalized)) continue;
665
+ if (!remotePaths.has(normalized)) {
666
+ deletePaths.add(snapshotTarget(root, normalized, options.sessionDir));
667
+ }
668
+ for (const remotePath of parentPaths(normalized)) {
669
+ if (remotePaths.has(remotePath)) {
670
+ deletePaths.add(snapshotTarget(root, remotePath, options.sessionDir));
671
+ }
672
+ }
673
+ }
674
+ deletes.push(...deletePaths);
675
+ return { writes, deletes };
676
+ }
677
+ function protectSnapshotApplyPlan(root, plan, protectedRelativePaths, sessionDir) {
678
+ if (protectedRelativePaths.size === 0) return plan;
679
+ const protectedTargets = new Set(
680
+ [...protectedRelativePaths].map((relativePath) => snapshotTarget(root, relativePath, sessionDir))
681
+ );
682
+ return {
683
+ writes: plan.writes.filter((item) => !protectedTargets.has(item.target)),
684
+ deletes: plan.deletes.filter((target) => !protectedTargets.has(target))
685
+ };
686
+ }
687
+ async function addTopLevelCaseVariantDeletes(root, plan, snapshot, options = {}) {
688
+ if (options.scope === "agent-directory" || snapshot.selection?.version === 3) return plan;
689
+ const excluded = compileSyncPolicyExclude(options);
690
+ const topLevelPaths = /* @__PURE__ */ new Map();
691
+ for (const file of snapshot.files) {
692
+ const normalized = toPosix(file.path);
693
+ if (!normalized.includes("/") && isSafeSnapshotPath(file.path) && !excluded(normalized)) {
694
+ topLevelPaths.set(normalized.toLowerCase(), normalized);
695
+ }
696
+ }
697
+ if (topLevelPaths.size === 0) return plan;
698
+ let entries;
699
+ try {
700
+ entries = await fs3.readdir(root, { withFileTypes: true });
701
+ } catch (error) {
702
+ if (error.code === "ENOENT") return plan;
703
+ throw error;
704
+ }
705
+ const deletes = new Set(plan.deletes);
706
+ for (const entry of entries) {
707
+ const canonicalPath = topLevelPaths.get(entry.name.toLowerCase());
708
+ if (canonicalPath && entry.name !== canonicalPath && !excluded(entry.name) && (entry.isFile() || entry.isSymbolicLink())) {
709
+ deletes.add(safeJoin(root, entry.name));
710
+ }
711
+ }
712
+ return { ...plan, deletes: [...deletes] };
713
+ }
714
+ function appliedFileHashMap(snapshot, current, protectedRelativePaths) {
715
+ const hashes = fileHashMap2(snapshot);
716
+ if (protectedRelativePaths.size === 0) return hashes;
717
+ const currentHashes = fileHashMap2(current);
718
+ for (const relativePath of protectedRelativePaths) {
719
+ const normalized = toPosix(relativePath);
720
+ if (currentHashes[normalized]) {
721
+ hashes[normalized] = currentHashes[normalized];
722
+ } else {
723
+ delete hashes[normalized];
724
+ }
725
+ }
726
+ return hashes;
727
+ }
728
+ function isSafeSnapshotPath(relativePath) {
729
+ if (relativePath.includes("\\")) return false;
730
+ const normalized = toPosix(relativePath);
731
+ return Boolean(normalized) && normalized !== "." && normalized !== ".." && !normalized.startsWith("../") && !path4.posix.isAbsolute(normalized) && path4.posix.normalize(normalized) === normalized && !isDeniedPath(normalized);
732
+ }
733
+ function excludedApplyPath(root, options) {
734
+ const excluded = compileSyncPolicyExclude(options);
735
+ if (options.scope !== "agent-directory") return excluded;
736
+ const physicalSessionPath = agentDirectoryPhysicalSessionPath(root, options.sessionDir);
737
+ return (relative) => excluded(relative) || (/^sessions(?:\/|$)/iu.test(relative) ? !isSessionFilePath(relative) : physicalSessionPath(relative));
738
+ }
739
+ async function preflightSnapshotMutations(root, plan, sessionDir, options = {}, unchangedHashes) {
740
+ const skipped = [];
741
+ assertMutationCurrent(options);
742
+ await assertUnexcludedTargets(root, [...plan.deletes, ...plan.writes.map((item) => item.target)], {
743
+ ...options,
744
+ sessionDir
745
+ });
746
+ assertMutationCurrent(options);
747
+ const deletePaths = new Set(plan.deletes);
748
+ for (const target of plan.deletes) {
749
+ await assertNoSymlinkParents(rootForTarget(root, target, sessionDir), target, options);
750
+ assertMutationCurrent(options);
751
+ }
752
+ for (const item of plan.writes) {
753
+ const stat = await prepareSnapshotWrite(
754
+ rootForTarget(root, item.target, sessionDir),
755
+ item.target,
756
+ deletePaths,
757
+ options
758
+ );
759
+ assertMutationCurrent(options);
760
+ const hash = unchangedHashes?.get(item.target);
761
+ if (hash !== void 0 && stat?.isFile() && stat.nlink === 1) {
762
+ const canonical = await fs3.realpath(item.target);
763
+ assertMutationCurrent(options);
764
+ if (canonical === item.target) skipped.push({ ...item, preimage: `file:${hash}` });
765
+ }
766
+ }
767
+ return skipped;
768
+ }
769
+ function assertMutationCurrent(options) {
770
+ options.validateMutation?.();
771
+ options.signal?.throwIfAborted();
772
+ }
773
+ async function guardedStat(target, options) {
774
+ assertMutationCurrent(options);
775
+ let stat;
776
+ try {
777
+ stat = await fs3.lstat(target);
778
+ } catch (error) {
779
+ assertMutationCurrent(options);
780
+ if (error.code === "ENOENT") return void 0;
781
+ throw error;
782
+ }
783
+ assertMutationCurrent(options);
784
+ return stat;
785
+ }
786
+ function rootForTarget(root, target, sessionDir) {
787
+ const sessionRoot = sessionDir ? sessionStorageRoot(root, sessionDir) : void 0;
788
+ if (sessionRoot && isPathInside(sessionRoot, target)) return sessionRoot;
789
+ return root;
790
+ }
791
+ async function prepareSnapshotWrite(root, target, deletePaths, options) {
792
+ const parentWillBeReplaced = await ensureSafeDirectory(root, path4.dirname(target), deletePaths, options);
793
+ assertMutationCurrent(options);
794
+ if (parentWillBeReplaced) return;
795
+ const stat = await guardedStat(target, options);
796
+ assertMutationCurrent(options);
797
+ if (stat?.isSymbolicLink()) throw new Error(`Refusing to overwrite symlink during snapshot apply: ${target}`);
798
+ if (stat?.isDirectory() && !deletePaths.has(target)) {
799
+ throw new Error(`Refusing to overwrite directory during snapshot apply: ${target}`);
800
+ }
801
+ return stat;
802
+ }
803
+ async function ensureSafeDirectory(root, directory, deletePaths, options) {
804
+ assertMutationCurrent(options);
805
+ assertWithinRoot(root, directory);
806
+ const rootPath = path4.resolve(root);
807
+ const relative = path4.relative(rootPath, path4.resolve(directory));
808
+ let current = rootPath;
809
+ for (const part of relative.split(path4.sep).filter(Boolean)) {
810
+ current = path4.join(current, part);
811
+ const stat = await guardedStat(current, options);
812
+ assertMutationCurrent(options);
813
+ if (stat) {
814
+ if (stat.isSymbolicLink()) throw new Error(`Refusing to follow symlink during snapshot apply: ${current}`);
815
+ if (!stat.isDirectory()) {
816
+ if (deletePaths.has(current)) return true;
817
+ throw new Error(`Snapshot path parent is not a directory: ${current}`);
818
+ }
819
+ } else return true;
820
+ }
821
+ return false;
822
+ }
823
+ async function assertNoSymlinkParents(root, target, options) {
824
+ assertMutationCurrent(options);
825
+ assertWithinRoot(root, target);
826
+ const rootPath = path4.resolve(root);
827
+ const relative = path4.relative(rootPath, path4.resolve(target));
828
+ let current = rootPath;
829
+ const parts = relative.split(path4.sep).filter(Boolean);
830
+ for (const part of parts.slice(0, -1)) {
831
+ current = path4.join(current, part);
832
+ const stat = await guardedStat(current, options);
833
+ assertMutationCurrent(options);
834
+ if (!stat) return;
835
+ if (stat.isSymbolicLink()) throw new Error(`Refusing to follow symlink during snapshot apply: ${current}`);
836
+ if (!stat.isDirectory()) throw new Error(`Snapshot path parent is not a directory: ${current}`);
837
+ }
838
+ }
839
+
840
+ // src/engine/sync/merge-apply.ts
841
+ async function preflightMergedTargets(before, after, options, protectedTarget) {
842
+ if (options.scope === "agent-directory") assertAgentDirectorySnapshotBound(after.files);
843
+ const root = agentDir();
844
+ const scan = options.scope === "agent-directory" ? agentDirectoryInventory(before) ?? agentDirectoryInventory(await createSnapshot(before.profile, options)) : void 0;
845
+ if (scan) options = { ...options, sessionDir: scan.sessionRoot };
846
+ const beforeHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(before));
847
+ const afterHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(after));
848
+ const paths = [.../* @__PURE__ */ new Set([...Object.keys(beforeHashes), ...Object.keys(afterHashes)])].sort();
849
+ const changed = new Set(paths.filter((item) => beforeHashes[item] !== afterHashes[item]));
850
+ requireManagedChanges(changed, options);
851
+ const targets = [...changed].map((item) => snapshotTarget(root, item, options.sessionDir));
852
+ if (options.scope === "agent-directory") await assertCanonicalMutationTargets(targets, options);
853
+ await assertUnexcludedTargets(root, targets, options);
854
+ await assertCanonicalMergedTargets(root, changed, options);
855
+ await assertDistinctMergedTargets(root, paths, changed, options, protectedTarget, new Set(Object.keys(afterHashes)));
856
+ const removed = replacementPaths(
857
+ new Set(paths.filter((item) => changed.has(item) && !afterHashes[item])),
858
+ afterHashes
859
+ );
860
+ const removedTargets = new Set([...removed].map((item) => snapshotTarget(root, item, options.sessionDir)));
861
+ for (const relative of paths) {
862
+ if (changed.has(relative)) await assertFilesystemTarget(root, relative, options, removedTargets, beforeHashes);
863
+ }
864
+ await assertCanonicalMutationTargets(targets, options);
865
+ if (scan) {
866
+ assertProjectedAgentDirectoryBudget(
867
+ scan,
868
+ {
869
+ deletes: [...removedTargets],
870
+ writes: after.files.filter((file) => changed.has(file.path)).map((file) => ({
871
+ target: snapshotTarget(root, file.path, options.sessionDir),
872
+ size: snapshotBase64Size(file.contentBase64, file.path)
873
+ }))
874
+ },
875
+ options
876
+ );
877
+ }
878
+ }
879
+ function requireManagedChanges(paths, options) {
880
+ if (options.scope !== "agent-directory") return;
881
+ const configured = configuredSnapshotPathMatcher(options);
882
+ for (const relative of paths)
883
+ if (!configured(relative)) throw new Error("A merged transfer targets a path outside the configured policy.");
884
+ }
885
+ function replacementPaths(removed, afterHashes) {
886
+ for (const relative of [...removed]) {
887
+ let parent = path5.posix.dirname(relative);
888
+ while (parent !== ".") {
889
+ if (afterHashes[parent]) {
890
+ for (let directory = path5.posix.dirname(relative); directory !== parent; directory = path5.posix.dirname(directory))
891
+ removed.add(directory);
892
+ removed.add(parent);
893
+ break;
894
+ }
895
+ parent = path5.posix.dirname(parent);
896
+ }
897
+ }
898
+ return removed;
899
+ }
900
+ async function assertCanonicalMergedTargets(root, changed, options) {
901
+ const topLevel = new Map(
902
+ [...changed].filter((relative) => !relative.includes("/")).map((relative) => [relative.toLowerCase(), relative])
903
+ );
904
+ if (topLevel.size === 0) return;
905
+ options.signal?.throwIfAborted();
906
+ options.validateMutation?.();
907
+ let names;
908
+ try {
909
+ names = await fs4.readdir(root);
910
+ } catch (error) {
911
+ options.signal?.throwIfAborted();
912
+ options.validateMutation?.();
913
+ if (error.code !== "ENOENT") throw error;
914
+ return;
915
+ }
916
+ options.signal?.throwIfAborted();
917
+ options.validateMutation?.();
918
+ for (const name of names) {
919
+ const canonical = topLevel.get(name.toLowerCase());
920
+ if (canonical !== void 0 && name !== canonical)
921
+ throw new Error(
922
+ "Merged target has a noncanonical case variant; normalize selected top-level file spelling before retrying. Journal retained if already committed."
923
+ );
924
+ }
925
+ }
926
+ async function assertDistinctMergedTargets(root, paths, changed, options, protectedTarget, finalPaths = new Set(paths)) {
927
+ const protectedKeys = /* @__PURE__ */ new Set();
928
+ for (const target of typeof protectedTarget === "string" ? [protectedTarget] : protectedTarget ?? [])
929
+ protectedKeys.add(mergePathIdentity(await resolvedTargetIdentity(path5.resolve(target), options)));
930
+ options.signal?.throwIfAborted();
931
+ options.validateMutation?.();
932
+ const keys = /* @__PURE__ */ new Map();
933
+ for (const relative of paths) {
934
+ options.signal?.throwIfAborted();
935
+ const target = snapshotTarget(root, relative, options.sessionDir);
936
+ const key = mergePathIdentity(await resolvedTargetIdentity(target, options));
937
+ options.signal?.throwIfAborted();
938
+ options.validateMutation?.();
939
+ const existing = keys.get(key);
940
+ if (existing && (mergePathIdentity(existing) !== mergePathIdentity(relative) || finalPaths.has(existing) && finalPaths.has(relative)))
941
+ throw new Error("Merged paths resolve to the same file; reviewed directional recovery is required.");
942
+ if (protectedKeys.has(key) && changed.has(relative))
943
+ throw new Error("A merged transfer targets the current session; review is required.");
944
+ keys.set(key, relative);
945
+ }
946
+ }
947
+ async function hashReviewedFile(target, stat, options) {
948
+ if (options.scope !== "agent-directory")
949
+ return createHash3("sha256").update(await fs4.readFile(target)).digest("hex");
950
+ const handle = await fs4.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
951
+ try {
952
+ const opened = await handle.stat();
953
+ options.signal?.throwIfAborted();
954
+ options.validateMutation?.();
955
+ if (!opened.isFile() || opened.nlink !== 1 || opened.dev !== stat.dev || opened.ino !== stat.ino)
956
+ throw new Error("Reviewed file changed at the merge boundary.");
957
+ const hash = createHash3("sha256");
958
+ let total = 0;
959
+ for await (const bytes of handle.createReadStream({ autoClose: false, signal: options.signal })) {
960
+ options.signal?.throwIfAborted();
961
+ options.validateMutation?.();
962
+ total += bytes.length;
963
+ if (total > MAX_AGENT_DIRECTORY_BYTES) throw new Error("Reviewed file exceeds the merge byte limit.");
964
+ hash.update(bytes);
965
+ }
966
+ return hash.digest("hex");
967
+ } finally {
968
+ await handle.close();
969
+ }
970
+ }
971
+ async function assertReviewedTree(directory, relative, beforeHashes, options, removedTargets) {
972
+ for (const name of await fs4.readdir(directory)) {
973
+ options.signal?.throwIfAborted();
974
+ options.validateMutation?.();
975
+ const child = path5.join(directory, name);
976
+ const childRelative = `${relative}/${name}`;
977
+ const stat = await fs4.lstat(child);
978
+ options.signal?.throwIfAborted();
979
+ options.validateMutation?.();
980
+ if (stat.isDirectory()) {
981
+ if (options.scope === "agent-directory" && (!removedTargets.has(child) || beforeHashes[childRelative]))
982
+ throw new Error("Reviewed directory contains an unreviewed directory; use a reviewed directional transfer.");
983
+ await assertReviewedTree(child, childRelative, beforeHashes, options, removedTargets);
984
+ } else if (!stat.isFile() || stat.nlink !== 1 || beforeHashes[childRelative] === void 0 || beforeHashes[childRelative] !== await hashReviewedFile(child, stat, options)) {
985
+ throw new Error("Reviewed directory contains unknown or changed files; publication refused.");
986
+ }
987
+ }
988
+ }
989
+ function hasBlockingFileAncestor(target, files) {
990
+ for (let parent = path5.dirname(target); parent !== path5.dirname(parent); parent = path5.dirname(parent))
991
+ if (files.has(parent)) return true;
992
+ return false;
993
+ }
994
+ async function resolvedTargetIdentity(target, options) {
995
+ let ancestor = target;
996
+ while (true) {
997
+ options.signal?.throwIfAborted();
998
+ try {
999
+ const resolved = await fs4.realpath(ancestor);
1000
+ return path5.resolve(resolved, path5.relative(ancestor, target));
1001
+ } catch (error) {
1002
+ const code = error.code;
1003
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
1004
+ const parent = path5.dirname(ancestor);
1005
+ if (parent === ancestor) return target;
1006
+ ancestor = parent;
1007
+ }
1008
+ }
1009
+ }
1010
+ async function assertFilesystemTarget(root, relative, options, removedTargets = /* @__PURE__ */ new Set(), beforeHashes) {
1011
+ const target = snapshotTarget(root, relative, options.sessionDir);
1012
+ const boundary = relative.startsWith("sessions/") && options.sessionDir ? path5.resolve(sessionStorageRoot(root, options.sessionDir)) : path5.resolve(root);
1013
+ const parents = [];
1014
+ for (let parent = path5.dirname(target); mergePathIdentity(parent) !== mergePathIdentity(boundary); parent = path5.dirname(parent)) {
1015
+ if (path5.dirname(parent) === parent) throw new Error("Unowned merged target.");
1016
+ parents.push(parent);
1017
+ }
1018
+ const statTarget = async (file) => {
1019
+ options.signal?.throwIfAborted();
1020
+ options.validateMutation?.();
1021
+ try {
1022
+ return await fs4.lstat(file);
1023
+ } catch (error) {
1024
+ if (error.code !== "ENOENT") throw error;
1025
+ return void 0;
1026
+ } finally {
1027
+ options.signal?.throwIfAborted();
1028
+ options.validateMutation?.();
1029
+ }
1030
+ };
1031
+ for (const parent of parents.reverse()) {
1032
+ const stat2 = await statTarget(parent);
1033
+ if (!stat2 || stat2.isDirectory()) continue;
1034
+ if (stat2.isFile() && stat2.nlink === 1 && removedTargets.has(parent)) return;
1035
+ throw new Error("Unsafe merge filesystem layout; review the selected paths before transfer.");
1036
+ }
1037
+ const stat = await statTarget(target);
1038
+ if (!stat) return;
1039
+ if (!stat.isFile() && !removedTargets.has(target) || stat.isFile() && stat.nlink > 1)
1040
+ throw new Error("Merge target is non-regular or hard-linked; review a directional operation before transfer.");
1041
+ if (stat.isDirectory() && beforeHashes)
1042
+ await assertReviewedTree(target, relative, beforeHashes, options, removedTargets);
1043
+ }
1044
+ async function applyMergedSnapshot(before, after, protectedPaths, options, validate, protectedTarget) {
1045
+ const root = agentDir();
1046
+ if (options.scope === "agent-directory" && options.sessionDir === void 0) {
1047
+ options = {
1048
+ ...options,
1049
+ sessionDir: sessionStorageRoot(root, await agentDirectoryConfiguredSessionDir(options.signal, root))
1050
+ };
1051
+ options.validateMutation?.();
1052
+ options.signal?.throwIfAborted();
1053
+ }
1054
+ const beforeHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(before));
1055
+ const afterHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(after));
1056
+ const paths = [.../* @__PURE__ */ new Set([...Object.keys(beforeHashes), ...Object.keys(afterHashes)])].sort();
1057
+ const replacements = replacementPaths(
1058
+ new Set(paths.filter((item) => beforeHashes[item] && !afterHashes[item])),
1059
+ afterHashes
1060
+ );
1061
+ const replacementTargets = new Set(
1062
+ [...replacements].map((relative) => snapshotTarget(root, relative, options.sessionDir))
1063
+ );
1064
+ const intermediateDirectories = [...replacements].filter((item) => !beforeHashes[item] && !afterHashes[item]);
1065
+ const changedFiles = paths.filter((item) => beforeHashes[item] !== afterHashes[item]);
1066
+ requireManagedChanges(changedFiles, options);
1067
+ const changed = [.../* @__PURE__ */ new Set([...changedFiles, ...intermediateDirectories])].sort();
1068
+ const protectedKeys = new Set([...protectedPaths].map(mergePathIdentity));
1069
+ if (changed.some((item) => protectedKeys.has(mergePathIdentity(item)))) {
1070
+ throw new Error("A merged transfer targets the current session; review is required.");
1071
+ }
1072
+ const targets = changed.map((item) => snapshotTarget(root, item, options.sessionDir));
1073
+ const relativeByTarget = new Map(targets.map((target, index) => [target, changed[index]]));
1074
+ const targetSet = new Set(targets);
1075
+ await assertDistinctMergedTargets(
1076
+ root,
1077
+ paths,
1078
+ new Set(changed),
1079
+ options,
1080
+ protectedTarget,
1081
+ new Set(Object.keys(afterHashes))
1082
+ );
1083
+ await assertCanonicalMutationTargets(targets, options);
1084
+ if (options.scope === "agent-directory") await assertUnexcludedTargets(root, targets, options);
1085
+ const targetsByQueue = /* @__PURE__ */ new Map();
1086
+ const queueTargets = [];
1087
+ const deferredTargets = [];
1088
+ for (const target of targets) {
1089
+ let key = path5.resolve(target);
1090
+ try {
1091
+ key = await fs4.realpath(target);
1092
+ } catch (error) {
1093
+ const code = error.code;
1094
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
1095
+ }
1096
+ options.signal?.throwIfAborted();
1097
+ options.validateMutation?.();
1098
+ const aliases = targetsByQueue.get(key) ?? [];
1099
+ aliases.push(target);
1100
+ targetsByQueue.set(key, aliases);
1101
+ }
1102
+ for (const [key, aliases] of targetsByQueue) {
1103
+ queueTargets.push(key);
1104
+ if (aliases.length > 1) deferredTargets.push(...aliases.filter((target) => path5.resolve(target) !== key));
1105
+ }
1106
+ async function acquire(index) {
1107
+ const target = queueTargets[index];
1108
+ if (target) return withEngineMutationQueue(target, () => acquire(index + 1));
1109
+ await validate();
1110
+ await assertCanonicalMergedTargets(root, changed, options);
1111
+ await validate();
1112
+ const current = await createSnapshot(before.profile, options);
1113
+ const currentHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(current));
1114
+ const blockingFiles = new Set(
1115
+ paths.filter(
1116
+ (relative) => beforeHashes[relative] && !afterHashes[relative] || afterHashes[relative] && currentHashes[relative] === afterHashes[relative]
1117
+ ).map((relative) => snapshotTarget(root, relative, options.sessionDir))
1118
+ );
1119
+ for (const item of changed) {
1120
+ if (currentHashes[item] !== beforeHashes[item] && currentHashes[item] !== afterHashes[item]) {
1121
+ throw new Error(
1122
+ "Local content changed during merged transfer; journal retained for review. No newer bytes were replaced."
1123
+ );
1124
+ }
1125
+ const target2 = snapshotTarget(root, item, options.sessionDir);
1126
+ try {
1127
+ const stat = await fs4.lstat(target2);
1128
+ if (!stat.isFile() && !stat.isDirectory() || stat.isFile() && stat.nlink > 1)
1129
+ throw new Error("Merged transfer target is no longer an independent regular file.");
1130
+ } catch (error) {
1131
+ const code = error.code;
1132
+ if (code !== "ENOENT" && !(code === "ENOTDIR" && hasBlockingFileAncestor(target2, blockingFiles))) throw error;
1133
+ }
1134
+ }
1135
+ const plan = preflightSnapshotApply(root, after, current, options);
1136
+ plan.writes = plan.writes.filter((item) => targetSet.has(item.target));
1137
+ plan.deletes = plan.deletes.filter((target2) => targetSet.has(target2));
1138
+ if (options.scope === "agent-directory") {
1139
+ const written = new Set(plan.writes.map((item) => item.target));
1140
+ const replaced = /* @__PURE__ */ new Set([...plan.deletes, ...written]);
1141
+ const targetFor = (relative) => snapshotTarget(root, relative, options.sessionDir);
1142
+ assertAgentDirectorySnapshotBound([
1143
+ ...current.files.filter((file) => !replaced.has(targetFor(file.path))),
1144
+ ...after.files.filter((file) => written.has(targetFor(file.path)))
1145
+ ]);
1146
+ }
1147
+ await preflightSnapshotMutations(root, plan, options.sessionDir, options);
1148
+ const deletedTargets = new Set(plan.deletes);
1149
+ for (const relative of intermediateDirectories) {
1150
+ for (let parent = path5.posix.dirname(relative); parent !== "."; parent = path5.posix.dirname(parent)) {
1151
+ if (afterHashes[parent] && deletedTargets.has(snapshotTarget(root, parent, options.sessionDir))) {
1152
+ plan.deletes.push(snapshotTarget(root, relative, options.sessionDir));
1153
+ break;
1154
+ }
1155
+ }
1156
+ }
1157
+ const scan = agentDirectoryInventory(current);
1158
+ if (scan) {
1159
+ for (const { target: target2 } of plan.writes) {
1160
+ if (!deletedTargets.has(target2)) continue;
1161
+ const relative = relativeByTarget.get(target2);
1162
+ if (!relative) throw new Error("Unowned merge write target.");
1163
+ await assertFilesystemTarget(root, relative, options, replacementTargets, beforeHashes);
1164
+ }
1165
+ assertProjectedAgentDirectoryBudget(
1166
+ scan,
1167
+ { deletes: plan.deletes, writes: plan.writes.map(({ target: target2, content }) => ({ target: target2, size: content.length })) },
1168
+ options
1169
+ );
1170
+ }
1171
+ plan.deletes.sort(
1172
+ (left, right) => right.split(path5.sep).length - left.split(path5.sep).length || left.localeCompare(right)
1173
+ );
1174
+ const removed = scan ? replacements : replacementPaths(
1175
+ new Set(paths.filter((relative) => deletedTargets.has(snapshotTarget(root, relative, options.sessionDir)))),
1176
+ afterHashes
1177
+ );
1178
+ const removedTargets = new Set([...removed].map((item) => snapshotTarget(root, item, options.sessionDir)));
1179
+ await assertCanonicalMergedTargets(root, changed, options);
1180
+ await validate();
1181
+ const requireReviewedHash = (relative, hash) => {
1182
+ if (hash !== beforeHashes[relative] && hash !== afterHashes[relative])
1183
+ throw new Error("Local content changed at the apply boundary; journal retained, newer bytes untouched.");
1184
+ };
1185
+ const revalidateTarget = async (target2) => {
1186
+ await validate();
1187
+ const relative = relativeByTarget.get(target2);
1188
+ if (!relative) throw new Error("Unowned merge target.");
1189
+ if (options.scope === "agent-directory") {
1190
+ await assertCanonicalMutationTargets([target2], options);
1191
+ await assertUnexcludedTargets(root, [target2], options);
1192
+ }
1193
+ await assertFilesystemTarget(root, relative, options, removedTargets, currentHashes);
1194
+ await validate();
1195
+ let kind = "missing";
1196
+ let hash;
1197
+ try {
1198
+ const stat = await fs4.lstat(target2);
1199
+ if (stat.isDirectory() && removed.has(relative)) {
1200
+ kind = "directory";
1201
+ if ((await fs4.readdir(target2)).length)
1202
+ throw new Error("Reviewed directory has remaining contents; journal retained for review.");
1203
+ } else {
1204
+ if (!stat.isFile() || stat.nlink > 1)
1205
+ throw new Error("Merged transfer target is no longer an independent regular file.");
1206
+ hash = await hashReviewedFile(target2, stat, options);
1207
+ kind = "file";
1208
+ }
1209
+ } catch (error) {
1210
+ if (error.code !== "ENOENT") throw error;
1211
+ }
1212
+ options.signal?.throwIfAborted();
1213
+ options.validateMutation?.();
1214
+ requireReviewedHash(relative, hash);
1215
+ return kind;
1216
+ };
1217
+ let checkApplyImage = options.requireReviewedApplyImage;
1218
+ const requireReviewedApplyImage = async () => {
1219
+ const latest = fileHashMap(await observeSnapshot(options));
1220
+ await validate();
1221
+ options.validateMutation?.();
1222
+ if ([.../* @__PURE__ */ new Set([...Object.keys(latest), ...paths])].some((relative) => {
1223
+ const hash = Object.hasOwn(latest, relative) ? latest[relative] : void 0;
1224
+ return hash !== beforeHashes[relative] && hash !== afterHashes[relative];
1225
+ }))
1226
+ throw new ContinuousError(
1227
+ "unsafe",
1228
+ "Cannot verify the size-limited local apply image: local files changed. Keep the merge journal and backup for review."
1229
+ );
1230
+ checkApplyImage = false;
1231
+ };
1232
+ if (options.scope === "agent-directory" && plan.deletes.length)
1233
+ await recheckAgentDirectoryBudget(root, plan, options);
1234
+ for (const target2 of plan.deletes) {
1235
+ if (checkApplyImage) await requireReviewedApplyImage();
1236
+ await withSessionWriteProtection([target2], async () => {
1237
+ const kind = await revalidateTarget(target2);
1238
+ try {
1239
+ if (kind === "directory") await fs4.rmdir(target2);
1240
+ else if (kind === "file") await fs4.rm(target2, { force: true });
1241
+ } catch (error) {
1242
+ if (error.code !== "ENOENT") throw error;
1243
+ }
1244
+ });
1245
+ await syncDirectory(path5.dirname(target2));
1246
+ }
1247
+ const requireAbsentDestinations = async () => {
1248
+ await validate();
1249
+ for (const target2 of deferredTargets) {
1250
+ try {
1251
+ await fs4.lstat(target2);
1252
+ } catch (error) {
1253
+ if (error.code !== "ENOENT") throw error;
1254
+ continue;
1255
+ }
1256
+ throw new Error("Case replacement destination changed before queue reservation; journal retained for review.");
1257
+ }
1258
+ await validate();
1259
+ };
1260
+ async function acquireDestinations(index2) {
1261
+ const target2 = deferredTargets[index2];
1262
+ if (target2) return withEngineMutationQueue(target2, () => acquireDestinations(index2 + 1));
1263
+ await requireAbsentDestinations();
1264
+ await writeTargets();
1265
+ }
1266
+ await requireAbsentDestinations();
1267
+ await acquireDestinations(0);
1268
+ async function writeTargets() {
1269
+ if (plan.writes.length && options.scope === "agent-directory") {
1270
+ await validate();
1271
+ await recheckAgentDirectoryBudget(root, { deletes: [], writes: plan.writes }, options);
1272
+ }
1273
+ for (const item of plan.writes) {
1274
+ await validate();
1275
+ const relative = relativeByTarget.get(item.target);
1276
+ if (!relative) throw new Error("Unowned merge write target.");
1277
+ await assertFilesystemTarget(root, relative, options, /* @__PURE__ */ new Set());
1278
+ if (checkApplyImage) await requireReviewedApplyImage();
1279
+ await withSessionWriteProtection([item.target], async () => {
1280
+ await validate();
1281
+ await createMutationParents(item.target, options);
1282
+ });
1283
+ const temporary = path5.join(path5.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
1284
+ let mode = 384;
1285
+ try {
1286
+ mode = (await fs4.stat(item.target)).mode & 511;
1287
+ } catch (error) {
1288
+ if (error.code !== "ENOENT") throw error;
1289
+ }
1290
+ try {
1291
+ const handle = await fs4.open(temporary, "wx", mode);
1292
+ try {
1293
+ await handle.writeFile(item.content);
1294
+ await handle.sync();
1295
+ } finally {
1296
+ await handle.close();
1297
+ }
1298
+ await withSessionWriteProtection([item.target], async () => {
1299
+ await revalidateTarget(item.target);
1300
+ await fs4.rename(temporary, item.target);
1301
+ });
1302
+ await syncDirectory(path5.dirname(item.target));
1303
+ } finally {
1304
+ await fs4.rm(temporary, { force: true });
1305
+ }
1306
+ }
1307
+ await syncMutationParents(
1308
+ targets,
1309
+ [root, ...options.sessionDir ? [sessionStorageRoot(root, options.sessionDir)] : []],
1310
+ options
1311
+ );
1312
+ await validate();
1313
+ }
1314
+ }
1315
+ await acquire(0);
1316
+ }
1317
+
1318
+ // src/engine/sync/merge-transfer-error.ts
1319
+ var MAX_CAUSES = 4;
1320
+ var MAX_DETAIL_LENGTH = 600;
1321
+ function mergeTransferError(error, backend) {
1322
+ const messages = [];
1323
+ const seen = /* @__PURE__ */ new Set();
1324
+ let current = error;
1325
+ while (current instanceof Error && !seen.has(current) && seen.size < MAX_CAUSES) {
1326
+ seen.add(current);
1327
+ const code = current.code;
1328
+ const status = current.status;
1329
+ const metadata = [
1330
+ typeof code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/u.test(code) ? code : void 0,
1331
+ typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? `HTTP ${status}` : void 0
1332
+ ].filter(Boolean);
1333
+ const message = `${current.message}${metadata.length ? ` (${metadata.join(", ")})` : ""}`;
1334
+ if (message && !messages.includes(message)) messages.push(message);
1335
+ current = current.cause;
1336
+ }
1337
+ let detail = messages.join(" \u2192 ") || "No error details available.";
1338
+ for (const secret of credentialVariants(backend)) detail = detail.replaceAll(secret, "[REDACTED]");
1339
+ detail = detail.replace(/\b(Bearer|Basic)\s+[^\s<>"']+/giu, "$1 [REDACTED]");
1340
+ detail = safeTerminalText(detail);
1341
+ if (detail.length > MAX_DETAIL_LENGTH) detail = `${detail.slice(0, MAX_DETAIL_LENGTH)}\u2026 (details truncated)`;
1342
+ return new Error(
1343
+ `Merged transfer interrupted; journal and backup retained. Run /sync sync to reconcile before further mutations. Transfer failure: ${detail}`,
1344
+ { cause: error }
1345
+ );
1346
+ }
1347
+ function credentialVariants(backend) {
1348
+ const secrets = [];
1349
+ let address;
1350
+ switch (backend.type) {
1351
+ case "s3":
1352
+ secrets.push(backend.profile.accessKeyId, backend.profile.secretAccessKey, backend.profile.sessionToken ?? "");
1353
+ address = backend.profile.endpoint;
1354
+ break;
1355
+ case "webdav":
1356
+ secrets.push(
1357
+ backend.profile.username,
1358
+ backend.profile.password,
1359
+ Buffer.from(`${backend.profile.username}:${backend.profile.password}`).toString("base64")
1360
+ );
1361
+ address = backend.profile.url;
1362
+ break;
1363
+ case "git":
1364
+ address = backend.profile.remote;
1365
+ break;
1366
+ }
1367
+ try {
1368
+ const url = new URL(address);
1369
+ secrets.push(url.username, url.password, ...url.searchParams.values());
1370
+ for (const value of [url.username, url.password]) secrets.push(decodeURIComponent(value));
1371
+ } catch {
1372
+ }
1373
+ return [
1374
+ ...new Set(
1375
+ secrets.filter(Boolean).flatMap((value) => [value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])
1376
+ )
1377
+ ].sort((left, right) => right.length - left.length);
1378
+ }
1379
+
1380
+ // src/engine/sync/settings-conflicts.ts
1381
+ import { createHash as createHash4 } from "node:crypto";
1382
+ async function resolveSettingsConflicts(config, state, local, remote, plan) {
1383
+ if (plan.kind !== "planned") return { plan, fields: [] };
1384
+ const fields = [];
1385
+ const decisions = [...plan.decisions];
1386
+ for (let index = 0; index < decisions.length; index++) {
1387
+ const decision = decisions[index];
1388
+ if (decision?.path !== "settings.json") continue;
1389
+ if (decision.kind === "conflict" ? decision.reason !== "both-changed" : !config.agentMode) continue;
1390
+ const left = local.files.find((file) => file.path === decision.path);
1391
+ const right = remote.files.find((file) => file.path === decision.path);
1392
+ if (!left || !right) continue;
1393
+ const ancestor = await readMergeAncestor(config, state, decision.path);
1394
+ if (!ancestor) continue;
1395
+ const leftBytes = Buffer.from(left.contentBase64, "base64");
1396
+ const rightBytes = Buffer.from(right.contentBase64, "base64");
1397
+ let content;
1398
+ if (decision.kind === "accepted") {
1399
+ if (!decision.file) continue;
1400
+ const patched = mergeAcceptedSettingsPackages(
1401
+ ancestor,
1402
+ leftBytes,
1403
+ rightBytes,
1404
+ Buffer.from(decision.file.contentBase64, "base64")
1405
+ );
1406
+ if (!patched) continue;
1407
+ content = patched;
1408
+ } else {
1409
+ const merged = mergeSettingsJson(ancestor, leftBytes, rightBytes, void 0, Boolean(config.agentMode));
1410
+ if (merged.kind === "review") {
1411
+ fields.push(...merged.fields);
1412
+ continue;
1413
+ }
1414
+ content = merged.content;
1415
+ }
1416
+ decisions[index] = {
1417
+ kind: "accepted",
1418
+ path: decision.path,
1419
+ source: "merged",
1420
+ file: {
1421
+ path: decision.path,
1422
+ contentBase64: content.toString("base64"),
1423
+ sha256: createHash4("sha256").update(content).digest("hex")
1424
+ }
1425
+ };
1426
+ }
1427
+ return {
1428
+ plan: { kind: "planned", decisions, conflicts: decisions.filter((decision) => decision.kind === "conflict") },
1429
+ fields
1430
+ };
1431
+ }
1432
+
1433
+ // src/engine/snapshot/snapshot-difference.ts
1434
+ function snapshotDifferences(local, remote = []) {
1435
+ const left = new Map(local.map((file) => [file.path, file]));
1436
+ const right = new Map(remote.map((file) => [file.path, file]));
1437
+ const differences = [];
1438
+ for (const path6 of [.../* @__PURE__ */ new Set([...left.keys(), ...right.keys()])].sort()) {
1439
+ const local2 = left.get(path6);
1440
+ const remote2 = right.get(path6);
1441
+ if (local2?.sha256 === remote2?.sha256) continue;
1442
+ differences.push({ path: path6, status: !local2 ? "remote-only" : !remote2 ? "local-only" : "different", local: local2, remote: remote2 });
1443
+ }
1444
+ return differences;
1445
+ }
1446
+
1447
+ // src/engine/ui/sync-format.ts
1448
+ function formatDiff(local, remote) {
1449
+ const changes = snapshotDifferences(local.files, remote.files);
1450
+ return [
1451
+ ...formatDiffCounts(local, remote),
1452
+ "",
1453
+ ...changes.length ? changes.map(formatDiffRow) : ["No file differences."]
1454
+ ].join("\n");
1455
+ }
1456
+ function formatDiffCounts(local, remote) {
1457
+ return [
1458
+ `local: ${local.files.length} files`,
1459
+ `remote: ${safeTerminalText(remote.id)} (${remote.files.length} files)`
1460
+ ];
1461
+ }
1462
+ function formatDiffRow(change) {
1463
+ const label = { "local-only": "Local only", "remote-only": "Remote only", different: "Different" };
1464
+ return `${label[change.status]}: ${snapshotPathLabel(change.path)}`;
1465
+ }
1466
+ function formatSnapshotOnlyDiff(title, snapshot) {
1467
+ return [
1468
+ `${safeTerminalText(title)}: ${safeTerminalText(snapshot.id)}`,
1469
+ ...snapshot.files.map((file) => `Add: ${snapshotPathLabel(file.path)}`)
1470
+ ].join("\n");
1471
+ }
1472
+ function formatTransferReview(...sections) {
1473
+ return {
1474
+ lines: sections.flatMap((section) => typeof section === "string" ? section.split("\n") : section.lines),
1475
+ content: sections.map((section) => typeof section === "string" ? section : section.content).join("\n")
1476
+ };
1477
+ }
1478
+ function formatPushSummary(config, destination, upload, head, preservedRemoteFileCount = 0, remote) {
1479
+ return formatTransferReview(
1480
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
1481
+ `Storage location: ${safeTerminalText(destination)}`,
1482
+ `Direction: Local \u2192 Remote. Source: ${safeTerminalText(agentDir())}.`,
1483
+ `Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`,
1484
+ `Sessions: ${upload.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
1485
+ ...excludedPolicyLines(config),
1486
+ head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty",
1487
+ "Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.",
1488
+ ...remote && inspectRemoteSelection(config.include, remote, config.exclude, config).kind === "different" ? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."] : [],
1489
+ formatPublicationPreview(remote, upload),
1490
+ config.skipSecretScan ? "Warning: possible-secret scanning is disabled for this push." : preservedRemoteFileCount > 0 ? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.` : "Possible secrets were scanned before this prompt.",
1491
+ ...config.scope === "agent-directory" ? ["Warning: synced files may contain secrets or other sensitive data that the scanner cannot identify."] : []
1492
+ );
1493
+ }
1494
+ function excludedPolicyLines(config) {
1495
+ const scoped = config.scope === "agent-directory";
1496
+ return [
1497
+ ...scoped ? [
1498
+ "Scope: eligible files in the Pi agent directory.",
1499
+ "Always local: Pi credentials (auth.json), project trust (trust.json), their lock files, and Pi Sync settings and service state."
1500
+ ] : [],
1501
+ ...config.exclude === void 0 && !scoped ? [] : [`Excluded paths: ${(config.exclude ?? []).map(safeTerminalText).join(", ") || "none"}`],
1502
+ ...scoped ? [`Re-included paths: ${(config.reinclude ?? []).map(safeTerminalText).join(", ") || "none"}`] : [],
1503
+ ...scoped || config.exclude !== void 0 ? [
1504
+ "Excluded local files remain untouched; matching paths are omitted from new publications, not erased from history."
1505
+ ] : []
1506
+ ];
1507
+ }
1508
+ function formatApplyPreview(local, remote, protectedPaths = /* @__PURE__ */ new Set(), additionalRemovals = []) {
1509
+ return formatDirectionalChanges(
1510
+ local,
1511
+ remote,
1512
+ {
1513
+ add: "Add locally",
1514
+ update: "Update locally",
1515
+ remove: "Remove locally"
1516
+ },
1517
+ protectedPaths,
1518
+ additionalRemovals
1519
+ );
1520
+ }
1521
+ function formatPullSummary(config, destination, local, remote, protectedPaths, additionalRemovals = []) {
1522
+ return formatTransferReview(
1523
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
1524
+ `Storage location: ${safeTerminalText(destination)}`,
1525
+ "Direction: Remote \u2192 Local.",
1526
+ `Snapshot: ${safeTerminalText(remote.id)}`,
1527
+ ...excludedPolicyLines(config),
1528
+ `Sessions: ${remote.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
1529
+ `Protected live sessions: ${protectedPaths.size || "none"}`,
1530
+ formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
1531
+ ...additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : [],
1532
+ "A local backup is created before these writes/deletes. The remote active snapshot is unchanged."
1533
+ );
1534
+ }
1535
+ function formatRollbackSummary(config, destination, local, remote, requestedSnapshot, protectedPaths, additionalRemovals = []) {
1536
+ return formatTransferReview(
1537
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
1538
+ `Storage location: ${safeTerminalText(destination)}`,
1539
+ "Direction: Historical snapshot \u2192 Local and remote active head.",
1540
+ `Snapshot: ${safeTerminalText(requestedSnapshot)}`,
1541
+ ...excludedPolicyLines(config),
1542
+ `Sessions: ${remote.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
1543
+ `Protected live sessions: ${protectedPaths.size || "none"}`,
1544
+ formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
1545
+ ...additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : [],
1546
+ "A local backup is created before applying; the backend's active head will change."
1547
+ );
1548
+ }
1549
+ function formatPublicationPreview(remote, upload) {
1550
+ return formatDirectionalChanges(remote, upload, {
1551
+ add: "Add remotely",
1552
+ update: "Update remotely",
1553
+ remove: "Remove remotely"
1554
+ });
1555
+ }
1556
+ function formatDirectionalChanges(before, after, labels, protectedPaths = /* @__PURE__ */ new Set(), additionalRemovals = []) {
1557
+ const changes = transferChanges(before, after, protectedPaths);
1558
+ const known = new Set(changes.map((change) => change.path));
1559
+ for (const filePath of additionalRemovals) {
1560
+ if (!known.has(filePath) && !protectedPaths.has(filePath)) {
1561
+ changes.push({ path: filePath, action: "Delete" });
1562
+ known.add(filePath);
1563
+ }
1564
+ }
1565
+ const counts = transferCounts(changes);
1566
+ const label = { Add: labels.add, Update: labels.update, Delete: labels.remove };
1567
+ const heading = `Changes: ${counts.add} add \xB7 ${counts.update} update \xB7 ${counts.remove} remove`;
1568
+ const lines = changes.length ? [heading] : [heading, "No file changes."];
1569
+ return {
1570
+ lines,
1571
+ content: [...lines, ...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`)].join(
1572
+ "\n"
1573
+ )
1574
+ };
1575
+ }
1576
+ function countPreservedRemoteFiles(local, upload) {
1577
+ const localPaths = new Set(local.files.map((file) => file.path));
1578
+ return upload.files.filter((file) => !localPaths.has(file.path)).length;
1579
+ }
1580
+ function publicationCapabilityDescription(capability) {
1581
+ switch (capability) {
1582
+ case "lease-protected":
1583
+ return "lease-protected (exact expected-ref update)";
1584
+ case "atomic-conditional":
1585
+ return "atomic-conditional (verified atomic precondition)";
1586
+ case "conditional-required":
1587
+ return "Read-only until atomic conditional writes are verified";
1588
+ case "read-check-write-verify":
1589
+ return "read-check-write-verify (visible races rejected; simultaneous unseen races remain possible)";
1590
+ }
1591
+ }
1592
+
1593
+ // src/engine/sync/sync-decision.ts
1594
+ function createSyncDecision(options) {
1595
+ const { config, state, local, remote, kind } = options;
1596
+ const policyChanged = Boolean(state.lastAppliedSnapshot) && syncPolicyChanged(state, config);
1597
+ const previousInclude = includeFromSelectionConfig(state);
1598
+ const currentInclude = [...config.include];
1599
+ const causes = {
1600
+ localChanged: options.localChanged,
1601
+ remoteChanged: options.remoteChanged,
1602
+ policyChanged
1603
+ };
1604
+ const causeLines = kind === "first-sync-settings-diverged" ? ["This machine and the remote have different Pi settings on first sync."] : kind === "first-sync-sessions-diverged" ? ["Pi settings match, but local and remote sessions differ on first sync."] : kind === "remote-empty" ? ["The remote storage location is empty."] : [
1605
+ ...causes.localChanged ? ["Local content changed since the last sync."] : [],
1606
+ ...causes.remoteChanged ? ["Remote content changed since the last sync."] : [],
1607
+ ...causes.policyChanged ? ["Included content changed since the last sync."] : []
1608
+ ];
1609
+ const comparison = remote ? formatDiff(local, remote) : formatSnapshotOnlyDiff("Remote is empty. Local push would upload", local);
1610
+ const review = [
1611
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
1612
+ "",
1613
+ "Why a decision is required:",
1614
+ ...causeLines,
1615
+ ...policyChanged ? [
1616
+ "",
1617
+ `Previously included: ${selectionLabel(state.scope, previousInclude)}`,
1618
+ `Currently included: ${selectionLabel(config.scope, currentInclude)}`,
1619
+ `Previously excluded: ${safeList(state.exclude ?? [])}`,
1620
+ `Currently excluded: ${safeList(config.exclude ?? [])}`,
1621
+ ...state.scope || config.scope ? [
1622
+ `Previously re-included: ${safeList(state.reinclude ?? [])}`,
1623
+ `Currently re-included: ${safeList(config.reinclude ?? [])}`
1624
+ ] : []
1625
+ ] : [],
1626
+ "",
1627
+ "Observed differences:",
1628
+ ...comparison.split("\n").map(safeTerminalText)
1629
+ ].join("\n");
1630
+ return new SyncDecisionRequiredError({
1631
+ kind,
1632
+ setupName: config.setupName,
1633
+ configIdentity: syncConfigReviewIdentity(config),
1634
+ causes,
1635
+ ...policyChanged ? { previousInclude: [...previousInclude] } : {},
1636
+ currentInclude,
1637
+ ...policyChanged && state.exclude !== void 0 ? { previousExclude: [...state.exclude] } : {},
1638
+ ...config.exclude === void 0 ? {} : { currentExclude: [...config.exclude] },
1639
+ ...policyChanged && state.scope !== void 0 ? { previousScope: state.scope } : {},
1640
+ ...config.scope === void 0 ? {} : { currentScope: config.scope },
1641
+ ...policyChanged && state.reinclude !== void 0 ? { previousReinclude: [...state.reinclude] } : {},
1642
+ ...config.reinclude === void 0 ? {} : { currentReinclude: [...config.reinclude] },
1643
+ review,
1644
+ directions: kind === "remote-empty" ? ["push"] : ["push", "pull"],
1645
+ directMessage: options.directMessage
1646
+ });
1647
+ }
1648
+ function selectionLabel(scope, include) {
1649
+ return scope === "agent-directory" ? `eligible files in the Pi agent directory (sessions ${include.includes("sessions") ? "opted in" : "off"})` : safeList(include);
1650
+ }
1651
+ function safeList(values) {
1652
+ return values.length > 0 ? values.map(safeTerminalText).join(", ") : "none";
1653
+ }
1654
+
1655
+ // src/engine/sync/transfer-size-limits.ts
1656
+ var MIB = 1024 ** 2;
1657
+ var MAX_FINDINGS = 8;
1658
+ function transferSizeLimitsEnabled(config) {
1659
+ return config.maxFileSizeMiB !== void 0 || config.maxDirectorySizeMiB !== void 0;
1660
+ }
1661
+ function selectedPublicationImage(snapshot, config, sessionDir) {
1662
+ return {
1663
+ side: "Remote",
1664
+ files: filterSnapshotForConfigPolicy(snapshot, config, { sessionDir }).files
1665
+ };
1666
+ }
1667
+ function selectedPullImage(incoming, local, protectedPaths) {
1668
+ return {
1669
+ side: "Local",
1670
+ files: protectedPaths.size ? [
1671
+ ...incoming.files.filter((file) => !protectedPaths.has(file.path)),
1672
+ ...local.files.filter((file) => protectedPaths.has(file.path))
1673
+ ] : incoming.files
1674
+ };
1675
+ }
1676
+ function compareFindings(a, b) {
1677
+ if (a.side !== b.side) return a.side < b.side ? -1 : 1;
1678
+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;
1679
+ return a.kind === b.kind ? 0 : a.kind < b.kind ? -1 : 1;
1680
+ }
1681
+ function transferSizeDetails(config, images) {
1682
+ if (!transferSizeLimitsEnabled(config)) return;
1683
+ const fileLimit = (config.maxFileSizeMiB ?? Infinity) * MIB;
1684
+ const directoryLimit = (config.maxDirectorySizeMiB ?? Infinity) * MIB;
1685
+ const findings = [];
1686
+ let count = 0;
1687
+ for (const { side, files } of images) {
1688
+ const directories = /* @__PURE__ */ new Map();
1689
+ const seen = /* @__PURE__ */ new Set();
1690
+ const measure = (path6, size, kind, limit) => {
1691
+ if (size <= limit) return;
1692
+ count++;
1693
+ const finding = { side, path: path6, size, kind, limit };
1694
+ if (findings.length === MAX_FINDINGS && compareFindings(finding, findings[MAX_FINDINGS - 1]) >= 0) return;
1695
+ findings.push(finding);
1696
+ findings.sort(compareFindings);
1697
+ if (findings.length > MAX_FINDINGS) findings.pop();
1698
+ };
1699
+ const measureFile = (path6, size) => {
1700
+ if (seen.has(path6)) return;
1701
+ seen.add(path6);
1702
+ measure(path6, size, "file", fileLimit);
1703
+ if (directoryLimit !== Infinity)
1704
+ for (const parent of parentPaths(path6)) directories.set(parent, (directories.get(parent) ?? 0) + size);
1705
+ };
1706
+ for (const file of files) measureFile(file.path, snapshotBase64Size(file.contentBase64, file.path));
1707
+ for (const [path6, size] of directories) measure(path6, size, "directory", directoryLimit);
1708
+ }
1709
+ if (!count) return;
1710
+ const omitted = count - findings.length;
1711
+ return [
1712
+ ...findings.map(({ path: path6, side, size, kind, limit }) => {
1713
+ const label = JSON.stringify(snapshotPathLabel(path6.slice(0, 160))).slice(1, -1);
1714
+ const shortened = path6.length > 160 || label.length > 240;
1715
+ return `${side} ${kind} "${label.slice(0, 240)}${shortened ? "\u2026" : ""}": ${size} bytes (limit ${limit} bytes).`;
1716
+ }),
1717
+ ...omitted ? [`${omitted} additional ${omitted === 1 ? "finding" : "findings"} omitted.`] : [],
1718
+ `Use /sync diff, adjust exclusions in /sync \u2192 Settings, then review a Push or Pull.`
1719
+ ].join(" ");
1720
+ }
1721
+ function requireTransferSize(config, ...images) {
1722
+ const details = transferSizeDetails(config, images);
1723
+ if (details) throw new TransferSizeError(`Transfer blocked by size limits. ${details}`);
1724
+ }
1725
+
1726
+ // src/engine/sync/merged-sync.ts
1727
+ var MAX_ATTEMPTS = 3;
1728
+ async function mergeSync(ctx, options, factory = createSyncBackend, resolution) {
1729
+ const timings = options.startupTimings ?? createStartupTimings();
1730
+ const sessionOwner = captureMutationOwner(ctx, options.signal);
1731
+ const validateOwner = (config2) => {
1732
+ sessionOwner();
1733
+ options.background?.validate(config2);
1734
+ };
1735
+ const isCurrent = () => {
1736
+ try {
1737
+ validateOwner();
1738
+ return true;
1739
+ } catch {
1740
+ return false;
1741
+ }
1742
+ };
1743
+ const validateRetryAuthorization = (config2) => {
1744
+ options.validateAgentRetryPolicy?.(config2);
1745
+ if (options.agentRetryRefusal && (!config2.agentMode || options.auto || options.background || !ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)))
1746
+ throw new Error("Refused-candidate retry requires foreground Autonomous sync in TUI or RPC.");
1747
+ };
1748
+ const config = await loadConfig(options.setup);
1749
+ validateOwner(config);
1750
+ validateRetryAuthorization(config);
1751
+ const configToken = syncCheckConfigFingerprint(config);
1752
+ const modelToken = JSON.stringify(ctx.model);
1753
+ const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config) ? await effectiveSessionRoot(ctx, config, options.signal) : void 0;
1754
+ validateOwner();
1755
+ const snapshotOptions = {
1756
+ ...snapshotOptionsForContext(ctx, config),
1757
+ sessionDir: sessionRoot,
1758
+ signal: options.signal
1759
+ };
1760
+ const validate = () => timings.measure("transfer authorization", async () => {
1761
+ validateOwner();
1762
+ const latest = await loadConfig(options.setup);
1763
+ validateOwner(latest);
1764
+ validateRetryAuthorization(latest);
1765
+ if (configToken !== syncCheckConfigFingerprint(latest))
1766
+ throw new Error("Sync setup or settings changed during transfer; reopen sync.");
1767
+ if (sessionRoot !== void 0) {
1768
+ const currentRoot = await effectiveSessionRoot(ctx, latest, options.signal);
1769
+ validateOwner();
1770
+ if (currentRoot !== sessionRoot)
1771
+ throw new Error("Session storage root changed during transfer; evidence retained for review.");
1772
+ }
1773
+ if (config.agentMode && JSON.stringify(ctx.model) !== modelToken)
1774
+ throw new Error("Autonomous sync paused: selected model changed during transfer.");
1775
+ if (options.auto && (!startupTransferEnabled(latest) || !ctx.isIdle()))
1776
+ throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
1777
+ });
1778
+ const validateFresh = validate;
1779
+ await validateFresh();
1780
+ const pending = await timings.measure("transfer journal read", () => readMergeJournal(config));
1781
+ await validate();
1782
+ if (!pending && options.recoveryOnly)
1783
+ throw new Error("The pending merge journal changed. No new transfer was attempted.");
1784
+ if (pending && options.agentRetryRefusal)
1785
+ throw new Error("A pending merge journal requires ordinary Sync now before retrying a refused candidate.");
1786
+ const backend = await timings.measure("transfer backend initialization", () => factory(config));
1787
+ await validate();
1788
+ if (pending) {
1789
+ const recovered = await timings.measure(
1790
+ "transfer journal recovery",
1791
+ () => completeJournal(
1792
+ ctx,
1793
+ config,
1794
+ backend,
1795
+ pending,
1796
+ { validate, validateFresh, validateOwner },
1797
+ timings,
1798
+ options,
1799
+ resolution ? void 0 : isCurrent
1800
+ )
1801
+ );
1802
+ if (!recovered) {
1803
+ if ((options.auto || !options.silent) && !options.signal?.aborted)
1804
+ ctx.ui.notify(
1805
+ "Interrupted candidate is not active; local content and baseline were unchanged. Evidence was reconciled without retrying publication. Run sync again for a fresh plan.",
1806
+ "warning"
1807
+ );
1808
+ return "cancelled";
1809
+ }
1810
+ if ((options.auto || !options.silent) && !options.signal?.aborted)
1811
+ ctx.ui.notify("Recovered the committed merged transfer. Run sync again to inspect newer changes.", "info");
1812
+ return "applied";
1813
+ }
1814
+ if ((options.auto || config.agentMode) && backend.capability === "read-check-write-verify") {
1815
+ throw new Error(
1816
+ "Automatic transfer requires conditional publication or a lease; this backend supports only read/check/write/verify. Use reviewed manual sync."
1817
+ );
1818
+ }
1819
+ const textBudget = { remaining: TEXT_MERGE_WORK_LIMIT };
1820
+ const createdArtifacts = [];
1821
+ const ownedStatePath = statePathForConfig(config);
1822
+ try {
1823
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
1824
+ await validate();
1825
+ const state = await timings.measure("transfer state read", () => readStateForConfig(config));
1826
+ if (state.unresolved?.length && !config.partialSync)
1827
+ throw new Error(
1828
+ "Partial progress remains unresolved; re-enable partial sync or review an explicit force direction."
1829
+ );
1830
+ const localRaw = await timings.measure(
1831
+ "transfer local snapshot",
1832
+ () => createSnapshot(config.snapshotIdentity, snapshotOptions)
1833
+ );
1834
+ const local = portableSnapshot(localRaw, config.localFields);
1835
+ if (!sameLocalFields(state.localFields, config.localFields))
1836
+ throw new Error("Local-field rules changed; review and confirm a directional migration first.");
1837
+ const head = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
1838
+ await validate();
1839
+ if (options.auto && !resolution && !config.partialSync && head && state.lastAppliedSnapshot && state.lastRemoteRevision && !state.unresolved?.length && head.snapshotId === state.lastAppliedSnapshot && backend.sameRevision(head.revision, state.lastRemoteRevision) && inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config).kind === "same" && matchesAcceptedState(state, config, head, local)) {
1840
+ const unchanged = await timings.measure("transfer unchanged verification", async () => {
1841
+ if (!await hasCurrentMergeBaseline(config, local, state)) return false;
1842
+ await validate();
1843
+ const currentLocal = await timings.measure("transfer local snapshot", () => observeSnapshot(snapshotOptions));
1844
+ await validate();
1845
+ const currentState = await timings.measure("transfer state read", () => readStateForConfig(config));
1846
+ await validate();
1847
+ return sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) && syncStateFingerprint(currentState) === syncStateFingerprint(state);
1848
+ });
1849
+ await validate();
1850
+ if (unchanged) {
1851
+ timings.markUnchanged();
1852
+ return "applied";
1853
+ }
1854
+ }
1855
+ const rawRemote = head ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal)) : void 0;
1856
+ await validate();
1857
+ if (rawRemote) {
1858
+ requireCompatibleRemoteSelection(config, rawRemote);
1859
+ const files = [...local.files, ...rawRemote.files];
1860
+ if (files.length > 16384 || files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024) {
1861
+ const message = "Merged transfer exceeds the 64 MiB / 16,384 input-file bound; review an explicit push or pull instead.";
1862
+ if (!transferSizeLimitsEnabled(config)) throw new Error(message);
1863
+ let details;
1864
+ try {
1865
+ const projected = portableSnapshot(
1866
+ filterSnapshotForConfigPolicy(rawRemote, config, { sessionDir: sessionRoot }),
1867
+ rawRemote.localFields
1868
+ );
1869
+ details = transferSizeDetails(config, [
1870
+ { side: "Local input", files: local.files },
1871
+ { side: "Remote input", files: projected.files }
1872
+ ]);
1873
+ } catch {
1874
+ throw new ContinuousError("unsafe", message);
1875
+ }
1876
+ if (details) throw new TransferSizeError(`${message} ${details}`);
1877
+ throw new ContinuousError("unsafe", message);
1878
+ }
1879
+ }
1880
+ const remote = rawRemote ? portableSnapshot(
1881
+ filterSnapshotForConfigPolicy(rawRemote, config, { sessionDir: sessionRoot }),
1882
+ rawRemote.localFields
1883
+ ) : void 0;
1884
+ if (rawRemote) {
1885
+ const validation = await timings.measure(
1886
+ "transfer merge planning",
1887
+ () => planFileMerge({
1888
+ baseline: state.lastFileHashes,
1889
+ local: local.files,
1890
+ remote: rawRemote.files,
1891
+ selectionCompatible: true
1892
+ })
1893
+ );
1894
+ await validate();
1895
+ const managedPaths = /* @__PURE__ */ new Set([
1896
+ ...Object.keys(state.lastFileHashes),
1897
+ ...[...local.files, ...remote?.files ?? []].map((file) => file.path)
1898
+ ]);
1899
+ if (validation.kind === "planned" && validation.conflicts.some(
1900
+ (item) => item.reason === "path-collision" && (!config.partialSync || !managedPaths.has(item.path))
1901
+ ))
1902
+ throw new Error("Remote snapshot contains path collisions; review a directional recovery before merging.");
1903
+ }
1904
+ const review = (message, kind = "both-changed") => createSyncDecision({
1905
+ kind,
1906
+ config,
1907
+ state,
1908
+ local,
1909
+ remote,
1910
+ localChanged: hasLocalChanges(local, state, config),
1911
+ remoteChanged: remote ? hasRemoteChanges(remote, state, config) : Boolean(state.lastAppliedSnapshot),
1912
+ directMessage: message
1913
+ });
1914
+ if (!state.lastAppliedSnapshot) throw review("Choose the initial source before enabling automatic transfer.");
1915
+ if (syncPolicyChanged(state, config))
1916
+ throw review("Included content changed; review the selection before merging.", "remote-or-policy-changed");
1917
+ if (!head || !remote || !rawRemote)
1918
+ throw review("The established remote is missing; choose an explicit recovery direction.", "remote-empty");
1919
+ const selectionState = inspectRemoteSelection(config.include, rawRemote, config.exclude, config);
1920
+ const selectionCompatible = selectionState.kind === "same";
1921
+ let plan = await timings.measure(
1922
+ "transfer merge planning",
1923
+ () => planFileMerge({
1924
+ baseline: state.lastFileHashes,
1925
+ local: local.files,
1926
+ remote: remote.files,
1927
+ selectionCompatible,
1928
+ protectedPaths: protectedSessionPaths(ctx, sessionRoot)
1929
+ })
1930
+ );
1931
+ await validate();
1932
+ let resolved = { plan, fields: [] };
1933
+ if (config.mergeSettings || config.agentMode) {
1934
+ try {
1935
+ resolved = await timings.measure(
1936
+ "transfer settings merge",
1937
+ () => resolveSettingsConflicts(config, state, local, remote, plan)
1938
+ );
1939
+ } catch (error) {
1940
+ if (!config.partialSync) throw error;
1941
+ }
1942
+ }
1943
+ await validate();
1944
+ plan = await timings.measure(
1945
+ "transfer content merge",
1946
+ () => resolveContentConflicts(config, state, local, remote, resolved.plan, protectedSessionPaths(ctx, sessionRoot), {
1947
+ textBudget,
1948
+ signal: options.signal
1949
+ })
1950
+ );
1951
+ await validate();
1952
+ if (resolution) {
1953
+ plan = await resolveReviewedGroup(
1954
+ config,
1955
+ backend,
1956
+ state,
1957
+ local,
1958
+ remote,
1959
+ head,
1960
+ plan,
1961
+ resolution,
1962
+ protectedSessionPaths(ctx, sessionRoot)
1963
+ );
1964
+ await validate();
1965
+ }
1966
+ if (config.agentMode && !resolution) {
1967
+ const { resolveAgentPlan } = await import("./agent-plan-A6CS3XXA.ts");
1968
+ await validate();
1969
+ plan = await resolveAgentPlan(
1970
+ ctx,
1971
+ options,
1972
+ config,
1973
+ backend,
1974
+ state,
1975
+ local,
1976
+ localRaw,
1977
+ remote,
1978
+ head,
1979
+ plan,
1980
+ snapshotOptions,
1981
+ validateFresh
1982
+ );
1983
+ await validate();
1984
+ if (plan.kind !== "planned" || plan.conflicts.length && !config.partialSync)
1985
+ throw new ContinuousError(
1986
+ "unsafe",
1987
+ "Autonomous sync paused: unsupported or refused conflict groups remain; no transfer was performed."
1988
+ );
1989
+ }
1990
+ if (plan.kind !== "planned" || plan.conflicts.length && (!config.partialSync || options.auto && !config.agentMode)) {
1991
+ const decision = review(
1992
+ selectionCompatible ? `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(", ")}` : ""}` : "Remote selection metadata is unavailable; review the included content and choose an explicit direction before merging.",
1993
+ selectionCompatible ? "both-changed" : "remote-or-policy-changed"
1994
+ );
1995
+ if (!selectionCompatible)
1996
+ decision.decision.review += `
1997
+
1998
+ ${formatRemoteSelectionStatus(selectionState)}
1999
+ An explicit direction adopts this setup's included-content policy; no automatic merge was performed.`;
2000
+ throw decision;
2001
+ }
2002
+ if (plan.kind !== "planned") throw new Error("Cannot partition an unverified merge plan.");
2003
+ const groups = conflictGroups(plan, config);
2004
+ const withheld = new Set(groups.flatMap((group) => group.paths));
2005
+ const persistProgress = async () => {
2006
+ if (!groups.length) return;
2007
+ let ancestors = [];
2008
+ try {
2009
+ const configured = configuredSnapshotPathMatcher(config);
2010
+ ancestors = (await readMergeAncestors(config, state) ?? []).filter(
2011
+ (file) => withheld.has(file.path) && configured(file.path)
2012
+ );
2013
+ } catch {
2014
+ }
2015
+ await validate();
2016
+ const previousArtifacts = /* @__PURE__ */ new Map();
2017
+ for (const token of new Set(state.unresolved?.map((group) => group.artifact) ?? [])) {
2018
+ try {
2019
+ const artifact2 = await readConflictArtifact(config, backend.identity, token);
2020
+ previousArtifacts.set(token, {
2021
+ artifact: artifact2,
2022
+ local: fileHashMap(artifact2.local),
2023
+ remote: fileHashMap(artifact2.remote)
2024
+ });
2025
+ } catch {
2026
+ }
2027
+ await validate();
2028
+ }
2029
+ const localHashes = fileHashMap(local);
2030
+ const remoteHashes = fileHashMap(remote);
2031
+ const previousGroups = new Map(state.unresolved?.map((item) => [JSON.stringify(item.paths), item]));
2032
+ const pending2 = groups.map((group) => {
2033
+ const previous = previousGroups.get(JSON.stringify(group.paths));
2034
+ const original = previous ? previousArtifacts.get(previous.artifact) : void 0;
2035
+ if (!original || !previous) return { group };
2036
+ return group.paths.every(
2037
+ (filePath) => localHashes[filePath] === original.local[filePath] && remoteHashes[filePath] === original.remote[filePath] && state.lastFileHashes[filePath] === original.artifact.state.lastFileHashes[filePath]
2038
+ ) ? { group, artifact: previous.artifact } : { group };
2039
+ });
2040
+ let artifact;
2041
+ const newGroups = pending2.filter((item) => !item.artifact).map((item) => item.group);
2042
+ const newPaths = new Set(newGroups.flatMap((group) => group.paths));
2043
+ if (newGroups.length)
2044
+ artifact = await saveConflictArtifact(
2045
+ config,
2046
+ backend.identity,
2047
+ {
2048
+ state,
2049
+ local: { ...local, files: local.files.filter((file) => newPaths.has(file.path)) },
2050
+ remote: { ...remote, files: remote.files.filter((file) => newPaths.has(file.path)) },
2051
+ ancestors: ancestors.filter((file) => newPaths.has(file.path)),
2052
+ groups: newGroups,
2053
+ observed: { snapshotId: head.snapshotId, revision: head.revision }
2054
+ },
2055
+ captureMutationOwner(ctx, options.signal),
2056
+ (created) => createdArtifacts.push(created)
2057
+ );
2058
+ await validate();
2059
+ return {
2060
+ previous: state,
2061
+ groups: pending2.map((item) => ({ paths: item.group.paths, artifact: item.artifact ?? artifact ?? "" }))
2062
+ };
2063
+ };
2064
+ let progress;
2065
+ const accepted = regenerateSnapshotIdentity({
2066
+ ...local,
2067
+ files: acceptedMergeFiles(plan.decisions, local.files, withheld)
2068
+ });
2069
+ const after = overlayLocalFields(accepted, localRaw, config.localFields);
2070
+ if (sessionRoot !== void 0) requireStableMergeSessionRoot(localRaw, after, config.scope);
2071
+ const publication = regenerateSnapshotIdentity({
2072
+ ...accepted,
2073
+ version: config.partialSync && accepted.version < 3 ? 3 : accepted.version,
2074
+ files: [
2075
+ ...accepted.files.filter((file) => !withheld.has(file.path)),
2076
+ ...remote.files.filter((file) => withheld.has(file.path))
2077
+ ]
2078
+ });
2079
+ const publish = !sameHashes(fileHashMap(publication), fileHashMap(remote)) || Boolean(config.partialSync && rawRemote.version < 3);
2080
+ const candidate = mergeRemotePreservedFiles(publication, rawRemote, config, { sessionDir: sessionRoot });
2081
+ const upload = candidate;
2082
+ const apply = !sameHashes(fileHashMap(localRaw), fileHashMap(after));
2083
+ if (!publish && !apply) {
2084
+ const beforeEvidence = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
2085
+ await validate();
2086
+ if (!beforeEvidence || !backend.sameRevision(beforeEvidence.revision, head.revision))
2087
+ throw new ContinuousError(
2088
+ "stale",
2089
+ "Remote changed before baseline acceptance; retry from a fresh observation."
2090
+ );
2091
+ progress = await persistProgress();
2092
+ await validate();
2093
+ const currentLocal = await timings.measure("transfer local snapshot", () => observeSnapshot(snapshotOptions));
2094
+ await validate();
2095
+ if (!sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) || syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !== syncStateFingerprint(state))
2096
+ throw new ContinuousError(
2097
+ "stale",
2098
+ "Local content or baseline changed before baseline acceptance; retry from a fresh observation."
2099
+ );
2100
+ await validate();
2101
+ const currentHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
2102
+ await validate();
2103
+ if (!currentHead || !backend.sameRevision(currentHead.revision, head.revision))
2104
+ throw new ContinuousError(
2105
+ "stale",
2106
+ "Remote changed before baseline acceptance; retry from a fresh observation."
2107
+ );
2108
+ await options.agentAcceptance?.commitCandidate?.();
2109
+ await validate();
2110
+ await timings.measure(
2111
+ "transfer baseline write",
2112
+ () => writeAcceptedState(config, head, accepted, validateFresh, progress)
2113
+ );
2114
+ await timings.measure(
2115
+ "transfer cleanup",
2116
+ () => pruneMergeBaselines(
2117
+ config,
2118
+ acceptedState(config, head, accepted, progress),
2119
+ captureMutationOwner(ctx, options.signal)
2120
+ )
2121
+ );
2122
+ await validate();
2123
+ await timings.measure(
2124
+ "transfer cleanup",
2125
+ () => pruneCompletedConflicts(
2126
+ config,
2127
+ backend.identity,
2128
+ acceptedState(config, head, accepted, progress),
2129
+ accepted,
2130
+ remote,
2131
+ captureMutationOwner(ctx, options.signal)
2132
+ )
2133
+ );
2134
+ await validate();
2135
+ if (!options.silent)
2136
+ ctx.ui.notify(
2137
+ progress ? `No independent transfer required; ${groups.length} conflict groups remain withheld. Review /sync conflicts.` : "Pi Sync is already up to date.",
2138
+ progress ? "warning" : "info"
2139
+ );
2140
+ return "applied";
2141
+ }
2142
+ if (transferSizeLimitsEnabled(config))
2143
+ requireTransferSize(
2144
+ config,
2145
+ ...apply ? [{ side: "Local", files: accepted.files }] : [],
2146
+ ...publish ? [selectedPublicationImage(upload, config, sessionRoot)] : []
2147
+ );
2148
+ await timings.measure(
2149
+ "transfer preflight",
2150
+ () => preflightMergedTargets(localRaw, after, snapshotOptions, [
2151
+ ...ctx.protectedSessionFiles ?? [],
2152
+ ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file))
2153
+ ])
2154
+ );
2155
+ await validate();
2156
+ if (!config.skipSecretScan && scanSnapshot(upload).length)
2157
+ throw new ContinuousError(
2158
+ "unsafe",
2159
+ "Refusing to merge possible secrets. Review managed content before syncing."
2160
+ );
2161
+ if (!options.yes && !config.agentMode) {
2162
+ const summary = mergedSyncSummary({
2163
+ setupName: config.setupName,
2164
+ destination: backend.destination,
2165
+ localBefore: localRaw,
2166
+ localAfter: after,
2167
+ remoteBefore: rawRemote,
2168
+ remoteAfter: upload,
2169
+ publish,
2170
+ sessions: syncSessionsSelected(config),
2171
+ groups,
2172
+ decisions: plan.decisions,
2173
+ capability: backend.capability
2174
+ });
2175
+ if (!await confirmMergeReview(
2176
+ ctx,
2177
+ summary.title,
2178
+ summary.content,
2179
+ options.signal,
2180
+ isCurrent,
2181
+ summary.confirmationLabel,
2182
+ summary.lines
2183
+ ))
2184
+ return "cancelled";
2185
+ }
2186
+ await validate();
2187
+ const refreshObservation = await timings.measure(
2188
+ "transfer local snapshot",
2189
+ () => observeSnapshot(snapshotOptions)
2190
+ );
2191
+ validateOwner();
2192
+ const refreshed = snapshotWithObservedInventory(localRaw, refreshObservation);
2193
+ if (!refreshed)
2194
+ throw new ContinuousError("stale", "Local content changed during review; no merged transfer was performed.");
2195
+ if (syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !== syncStateFingerprint(state))
2196
+ throw new ContinuousError("stale", "Sync baseline changed during review; retry from a fresh observation.");
2197
+ await validate();
2198
+ const refreshedHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
2199
+ await validate();
2200
+ if (!sameMergeRecoveryHead(backend, refreshedHead, head))
2201
+ throw new ContinuousError("stale", "Remote changed during review; no merged transfer was performed.");
2202
+ await options.agentAcceptance?.commitCandidate?.();
2203
+ await validate();
2204
+ progress = await persistProgress();
2205
+ await validate();
2206
+ const backup = await timings.measure(
2207
+ "transfer backup",
2208
+ () => backupSnapshot(regenerateSnapshotIdentity(refreshed), options.signal)
2209
+ );
2210
+ await validateFresh();
2211
+ const journal = {
2212
+ version: 1,
2213
+ identity: mergeJournalIdentity(config, backend.identity),
2214
+ before: localRaw,
2215
+ after,
2216
+ accepted,
2217
+ ...progress ? { progress } : {},
2218
+ upload: publish ? upload : rawRemote,
2219
+ expectedHead: head,
2220
+ backup,
2221
+ stateIdentity: syncStateFingerprint(state),
2222
+ ...sessionRoot !== void 0 ? { sessionRoot } : {},
2223
+ ...!publish ? { committedHead: head, applyOnly: true } : {}
2224
+ };
2225
+ await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
2226
+ const atCommitState = syncStateFingerprint(
2227
+ await timings.measure("transfer state read", () => readStateForConfig(config))
2228
+ );
2229
+ await validate();
2230
+ const commitObservation = await timings.measure(
2231
+ "transfer local snapshot",
2232
+ () => observeSnapshot(snapshotOptions)
2233
+ );
2234
+ await validate();
2235
+ const atCommit = snapshotWithObservedInventory(refreshed, commitObservation);
2236
+ if (!atCommit || atCommitState !== journal.stateIdentity) {
2237
+ await validateFresh();
2238
+ await clearMergeJournal(config);
2239
+ throw new ContinuousError(
2240
+ "stale",
2241
+ "Local content or baseline changed before publication; candidate retired without transfer. Review a fresh sync."
2242
+ );
2243
+ }
2244
+ try {
2245
+ await timings.measure(
2246
+ "transfer preflight",
2247
+ () => preflightMergedTargets(atCommit, after, snapshotOptions, [
2248
+ ...ctx.protectedSessionFiles ?? [],
2249
+ ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file))
2250
+ ])
2251
+ );
2252
+ } catch (error) {
2253
+ await validateFresh();
2254
+ await clearMergeJournal(config);
2255
+ throw error;
2256
+ }
2257
+ await validateFresh();
2258
+ try {
2259
+ if (publish) {
2260
+ const result = await timings.measure(
2261
+ "transfer remote publication",
2262
+ () => backend.publishSnapshot(upload, expectedRemoteHead(head), {
2263
+ signal: options.signal,
2264
+ onCommit: options.onCommit,
2265
+ validatePublication: validateFresh
2266
+ })
2267
+ );
2268
+ journal.committedHead = result.head;
2269
+ journal.warnings = result.warnings;
2270
+ await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
2271
+ } else options.onCommit?.();
2272
+ } catch (error) {
2273
+ if (error instanceof SyncBackendConflictError && error.phase === "before-commit" && !error.candidateMayHaveBeenActive) {
2274
+ await validateFresh();
2275
+ await clearMergeJournal(config);
2276
+ if (attempt + 1 < MAX_ATTEMPTS) continue;
2277
+ throw new Error("Remote changed before commit in all three attempts; retry later.", { cause: error });
2278
+ }
2279
+ throw mergeTransferError(error, config.backend);
2280
+ }
2281
+ const completed = await timings.measure(
2282
+ "transfer journal recovery",
2283
+ () => completeJournal(ctx, config, backend, journal, { validate, validateFresh, validateOwner }, timings, options)
2284
+ );
2285
+ if (!completed) {
2286
+ if (!options.signal?.aborted && (options.auto || !options.silent))
2287
+ ctx.ui.notify(
2288
+ "Remote changed before local apply; candidate retired without transfer. Run sync again.",
2289
+ "warning"
2290
+ );
2291
+ return "cancelled";
2292
+ }
2293
+ if (!options.signal?.aborted && (options.auto || !options.silent))
2294
+ ctx.ui.notify(
2295
+ [
2296
+ `Synced independent changes for \u201C${safeTerminalText(config.setupName)}\u201D. ${apply ? "Local files changed; reload or restart Pi when ready to use changed resources." : "Remote updated."} No automatic reload.`,
2297
+ ...progress ? [
2298
+ `Partial progress: ${groups.length} dependency groups remain unresolved; neither side's withheld versions or baseline hashes were replaced. Review /sync conflicts.`
2299
+ ] : [],
2300
+ ...(journal.warnings ?? []).map(safeTerminalText)
2301
+ ].join("\n"),
2302
+ progress || journal.warnings?.length ? "warning" : "info"
2303
+ );
2304
+ return "applied";
2305
+ }
2306
+ } finally {
2307
+ await timings.measure("transfer cleanup", () => releaseConflictArtifacts(config, ownedStatePath, createdArtifacts));
2308
+ }
2309
+ }
2310
+ async function completeJournal(ctx, config, backend, journal, {
2311
+ validate,
2312
+ validateFresh,
2313
+ validateOwner
2314
+ }, timings, options, _isCurrent) {
2315
+ const { auto, signal } = options;
2316
+ const validateMutation = () => {
2317
+ validateOwner();
2318
+ if (auto && !ctx.isIdle()) throw new Error("Automatic file apply is no longer idle; evidence retained.");
2319
+ };
2320
+ if (journal.identity !== mergeJournalIdentity(config, backend.identity) || !sameLocalFields(journal.upload.localFields, config.localFields))
2321
+ throw new Error(
2322
+ "Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery."
2323
+ );
2324
+ await validateFresh();
2325
+ const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config) ? await effectiveSessionRoot(ctx, config, signal) : void 0;
2326
+ await validate();
2327
+ if (sessionRoot !== void 0 && journal.sessionRoot !== sessionRoot) {
2328
+ throw new Error(
2329
+ "Merge journal session root is missing or differs from this context; preserve its journal and backup for review."
2330
+ );
2331
+ }
2332
+ const snapshotOptions = { ...snapshotOptionsForContext(ctx, config), sessionDir: sessionRoot, signal };
2333
+ const head = await timings.measure("transfer remote head", () => backend.readHead(signal));
2334
+ await validate();
2335
+ const readRetirementEvidence = async () => {
2336
+ const state2 = await timings.measure("transfer state read", () => readStateForConfig(config));
2337
+ await validateFresh();
2338
+ const local = await timings.measure("transfer local snapshot", () => observeSnapshot(snapshotOptions));
2339
+ validateMutation();
2340
+ const latest = await timings.measure("transfer remote head", () => backend.readHead(signal));
2341
+ validateMutation();
2342
+ if (!sameMergeRecoveryHead(backend, head, latest))
2343
+ throw new Error("Remote head changed during merge recovery; journal and backup retained.");
2344
+ await validateFresh();
2345
+ return {
2346
+ sameBaseline: syncStateFingerprint(state2) === journal.stateIdentity,
2347
+ sameLocal: sameHashes(fileHashMap(local), fileHashMap(journal.before))
2348
+ };
2349
+ };
2350
+ if (journal.committedHead?.snapshotId === journal.upload.id && typeof journal.committedHead.revision === "string" && journal.committedHead.revision && (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
2351
+ const state2 = await timings.measure("transfer state read", () => readStateForConfig(config));
2352
+ await validate();
2353
+ if (matchesAcceptedState(state2, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)) {
2354
+ await clearMergeJournal(config);
2355
+ await validate();
2356
+ await pruneMergeBaselines(config, state2, captureMutationOwner(ctx, signal));
2357
+ await validate();
2358
+ return true;
2359
+ }
2360
+ }
2361
+ if (!journal.committedHead && head && (backend.sameRevision(head.revision, journal.expectedHead.revision) || backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
2362
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
2363
+ validateMutation();
2364
+ if (!sameBaseline || !sameLocal) {
2365
+ throw new Error(
2366
+ "Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery."
2367
+ );
2368
+ }
2369
+ await clearMergeJournal(config);
2370
+ return false;
2371
+ }
2372
+ if (journal.applyOnly && (!head || !backend.sameRevision(head.revision, journal.expectedHead.revision))) {
2373
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
2374
+ validateMutation();
2375
+ if (sameBaseline && sameLocal) {
2376
+ await clearMergeJournal(config);
2377
+ return false;
2378
+ }
2379
+ throw new Error("Apply-only remote head advanced after local changes; preserve the journal for reviewed recovery.");
2380
+ }
2381
+ if (!head || head.snapshotId !== journal.upload.id || journal.committedHead && !backend.sameRevision(head.revision, journal.committedHead.revision)) {
2382
+ throw new Error(
2383
+ "Publication outcome cannot be reconciled with the current remote head. Journal and backup retained; do not retry publication or restore old bytes blindly."
2384
+ );
2385
+ }
2386
+ const observed = await timings.measure(
2387
+ "transfer snapshot download",
2388
+ () => readSnapshotForHead(backend, head, signal)
2389
+ );
2390
+ requireCompatibleRemoteSelection(config, observed);
2391
+ if (!sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) || JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection) || observed.version !== journal.upload.version)
2392
+ throw new Error("Remote snapshot does not match the recorded merge publication.");
2393
+ const state = await timings.measure("transfer state read", () => readStateForConfig(config));
2394
+ if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
2395
+ await validateFresh();
2396
+ await clearMergeJournal(config);
2397
+ await validate();
2398
+ await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
2399
+ await validate();
2400
+ return true;
2401
+ }
2402
+ if (syncStateFingerprint(state) !== journal.stateIdentity) {
2403
+ throw new Error("Sync baseline changed after the interrupted merge; preserve its journal and review recovery.");
2404
+ }
2405
+ if (inspectRemoteSelection(config.include, observed, config.exclude, config).kind !== "same")
2406
+ throw new Error(
2407
+ "Pending merge has unavailable remote selection metadata; preserve its journal and backup for review."
2408
+ );
2409
+ const requireReviewedApplyImage = journal.applyOnly && transferSizeLimitsEnabled(config);
2410
+ if (requireReviewedApplyImage) {
2411
+ const selected = journal.accepted ?? portableSnapshot(journal.after, config.localFields);
2412
+ const details = transferSizeDetails(config, [{ side: "Local", files: selected.files }]);
2413
+ if (details) {
2414
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
2415
+ if (sameBaseline && sameLocal) {
2416
+ await clearMergeJournal(config);
2417
+ throw new TransferSizeError(`Transfer blocked by size limits. ${details}`);
2418
+ }
2419
+ throw new TransferSizeError(
2420
+ `Transfer blocked by size limits. The local apply is not verified. Keep the journal and backup. Review the limits before retrying /sync sync. ${details}`
2421
+ );
2422
+ }
2423
+ }
2424
+ if (sessionRoot !== void 0) requireStableMergeSessionRoot(journal.before, journal.after, config.scope);
2425
+ await validateFresh();
2426
+ const protectedPaths = protectedSessionPaths(ctx, sessionRoot);
2427
+ const validateApply = () => {
2428
+ validateMutation();
2429
+ };
2430
+ await timings.measure(
2431
+ "transfer local apply",
2432
+ () => applyMergedSnapshot(
2433
+ journal.before,
2434
+ journal.after,
2435
+ protectedPaths,
2436
+ { ...snapshotOptions, validateMutation: validateApply, requireReviewedApplyImage },
2437
+ validate,
2438
+ ctx.sessionManager.getSessionFile?.()
2439
+ )
2440
+ );
2441
+ await validate();
2442
+ const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
2443
+ await validate();
2444
+ if (!sameMergeRecoveryHead(backend, headAtAcceptance, head))
2445
+ throw new Error("Remote changed during merged apply; journal and backup retained for review.");
2446
+ await timings.measure(
2447
+ "transfer baseline write",
2448
+ () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validateFresh, journal.progress)
2449
+ );
2450
+ await validateFresh();
2451
+ await clearMergeJournal(config);
2452
+ await validate();
2453
+ await timings.measure(
2454
+ "transfer cleanup",
2455
+ () => pruneMergeBaselines(
2456
+ config,
2457
+ acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
2458
+ captureMutationOwner(ctx, signal)
2459
+ )
2460
+ );
2461
+ await validate();
2462
+ await timings.measure(
2463
+ "transfer cleanup",
2464
+ () => pruneCompletedConflicts(
2465
+ config,
2466
+ backend.identity,
2467
+ acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
2468
+ journal.accepted ?? journal.after,
2469
+ journal.upload,
2470
+ captureMutationOwner(ctx, signal)
2471
+ )
2472
+ );
2473
+ await validate();
2474
+ return true;
2475
+ }
2476
+
2477
+ export {
2478
+ applySnapshot,
2479
+ addTopLevelCaseVariantDeletes,
2480
+ snapshotDifferences,
2481
+ formatDiff,
2482
+ formatDiffCounts,
2483
+ formatDiffRow,
2484
+ formatSnapshotOnlyDiff,
2485
+ formatTransferReview,
2486
+ formatPushSummary,
2487
+ formatPullSummary,
2488
+ formatRollbackSummary,
2489
+ countPreservedRemoteFiles,
2490
+ publicationCapabilityDescription,
2491
+ confirmMergeReview,
2492
+ createSyncDecision,
2493
+ transferSizeLimitsEnabled,
2494
+ selectedPublicationImage,
2495
+ selectedPullImage,
2496
+ requireTransferSize,
2497
+ mergeSync
2498
+ };
2499
+ //# sourceMappingURL=chunk-DH52CVRD.ts.map