@narumitw/pi-sync 0.59.0 → 0.60.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 (321) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +19 -10
  3. package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
  4. package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
  5. package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
  6. package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
  7. package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
  8. package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
  9. package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
  10. package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
  11. package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
  12. package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
  13. package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
  14. package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
  15. package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
  16. package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
  17. package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
  18. package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
  19. package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
  20. package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
  21. package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
  22. package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
  23. package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
  24. package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
  25. package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
  26. package/dist/chunks/chunk-JZKCOM62.ts +26 -0
  27. package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
  28. package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
  29. package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
  30. package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-MIXZVHFR.ts} +24 -10
  31. package/dist/chunks/chunk-MIXZVHFR.ts.map +7 -0
  32. package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
  33. package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
  34. package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
  35. package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
  36. package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
  37. package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
  38. package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
  39. package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
  40. package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
  41. package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
  42. package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
  43. package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
  44. package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
  45. package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-3O76V7Q5.ts} +80 -86
  46. package/dist/chunks/command-handler-3O76V7Q5.ts.map +7 -0
  47. package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
  48. package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
  49. package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
  50. package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
  51. package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
  52. package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
  53. package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
  54. package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-SJOBTJLY.ts} +80 -123
  55. package/dist/chunks/manager-ui-SJOBTJLY.ts.map +7 -0
  56. package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
  57. package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
  58. package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
  59. package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
  60. package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
  61. package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
  62. package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
  63. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
  64. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
  65. package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
  66. package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
  67. package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
  68. package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
  69. package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
  70. package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
  71. package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
  72. package/dist/index.ts +269 -313
  73. package/dist/index.ts.map +4 -4
  74. package/docs/daemon-migration.md +93 -0
  75. package/package.json +3 -6
  76. package/skills/configure-pi-sync/SKILL.md +1 -1
  77. package/skills/configure-pi-sync/references/configuration.md +19 -6
  78. package/src/backends/backend-factory.ts +2 -23
  79. package/src/backends/backend-identity.ts +5 -40
  80. package/src/backends/backend-types.ts +1 -81
  81. package/src/backends/git/git-backend.ts +6 -784
  82. package/src/backends/git/git-config.ts +8 -130
  83. package/src/backends/git/git-runner.ts +7 -255
  84. package/src/backends/git/git-storage.ts +14 -293
  85. package/src/backends/s3/s3-backend.ts +11 -523
  86. package/src/backends/s3/s3-client.ts +2 -399
  87. package/src/backends/s3/s3-conditions.ts +2 -67
  88. package/src/backends/snapshot-pointer.ts +2 -27
  89. package/src/backends/sync-backend.ts +6 -101
  90. package/src/backends/webdav/webdav-backend.ts +10 -622
  91. package/src/backends/webdav/webdav-client.ts +6 -370
  92. package/src/backends/webdav/webdav-config.ts +8 -82
  93. package/src/commands/command-execution.ts +40 -36
  94. package/src/commands/command.ts +23 -1
  95. package/src/daemon/apply-gate.ts +146 -0
  96. package/src/daemon/pi-client.ts +591 -0
  97. package/src/daemon/recovery.ts +103 -0
  98. package/src/paths.ts +12 -83
  99. package/src/settings/config-errors.ts +2 -6
  100. package/src/settings/config-file.ts +19 -693
  101. package/src/settings/config.ts +16 -263
  102. package/src/settings/settings-management.ts +11 -254
  103. package/src/settings/settings-store.ts +10 -48
  104. package/src/settings/settings-types.ts +1 -157
  105. package/src/settings/settings-validation.ts +17 -435
  106. package/src/snapshot/session-paths.ts +11 -111
  107. package/src/snapshot/snapshot-apply.ts +9 -322
  108. package/src/snapshot/snapshot-case-replacement.ts +6 -80
  109. package/src/snapshot/snapshot-codec.ts +2 -59
  110. package/src/snapshot/snapshot-exclude-safety.ts +2 -44
  111. package/src/snapshot/snapshot-mutation-queues.ts +6 -142
  112. package/src/snapshot/snapshot-paths.ts +2 -11
  113. package/src/snapshot/snapshot-root-transition.ts +6 -154
  114. package/src/snapshot/snapshot-transaction-directory.ts +5 -16
  115. package/src/snapshot/snapshot-transaction-plan.ts +2 -72
  116. package/src/snapshot/snapshot-transaction.ts +6 -946
  117. package/src/snapshot/snapshot-types.ts +1 -43
  118. package/src/snapshot/snapshot.ts +19 -447
  119. package/src/state/json-file.ts +2 -47
  120. package/src/state/lock-policy.ts +2 -2
  121. package/src/state/lock.ts +10 -292
  122. package/src/state/lockfile-fs.ts +2 -25
  123. package/src/state/merge-baseline-store.ts +8 -208
  124. package/src/state/mutation-directory-sync.ts +2 -34
  125. package/src/state/operation-availability.ts +7 -59
  126. package/src/state/state-directory.ts +8 -243
  127. package/src/state/state-types.ts +1 -25
  128. package/src/state/sync-state-store.ts +11 -75
  129. package/src/sync/agent-candidate.ts +7 -256
  130. package/src/sync/agent-plan.ts +2 -107
  131. package/src/sync/agent-policy.ts +10 -13
  132. package/src/sync/agent-refusal-retry.ts +2 -54
  133. package/src/sync/agent-request.ts +2 -19
  134. package/src/sync/agent-runner.ts +2 -191
  135. package/src/sync/agent-store.ts +7 -182
  136. package/src/sync/agent-sync.ts +2 -141
  137. package/src/sync/apply-review.ts +2 -63
  138. package/src/sync/automatic-sync.ts +55 -111
  139. package/src/sync/conflict-artifact-ownership.ts +2 -63
  140. package/src/sync/conflict-artifacts.ts +8 -195
  141. package/src/sync/conflict-groups.ts +2 -68
  142. package/src/sync/conflict-preview.ts +2 -56
  143. package/src/sync/conflict-resolution.ts +2 -93
  144. package/src/sync/conflict-retention.ts +2 -72
  145. package/src/sync/conflict-review.ts +3 -92
  146. package/src/sync/content-conflicts.ts +2 -73
  147. package/src/sync/continuous-errors.ts +7 -85
  148. package/src/sync/continuous-lease.ts +2 -216
  149. package/src/sync/continuous-record.ts +10 -261
  150. package/src/sync/continuous-storage.ts +12 -64
  151. package/src/sync/continuous-sync.ts +2 -563
  152. package/src/sync/continuous-watch.ts +2 -61
  153. package/src/sync/exclude-policy.ts +6 -84
  154. package/src/sync/field-migration.ts +2 -39
  155. package/src/sync/file-merge-planner.ts +2 -143
  156. package/src/sync/json-document.ts +7 -184
  157. package/src/sync/local-field-policy.ts +2 -29
  158. package/src/sync/local-fields.ts +9 -119
  159. package/src/sync/merge-apply.ts +2 -439
  160. package/src/sync/merge-journal.ts +10 -228
  161. package/src/sync/merge-transfer-error.ts +2 -72
  162. package/src/sync/merged-sync.ts +2 -919
  163. package/src/sync/mutation-owner.ts +2 -22
  164. package/src/sync/package-merge.ts +2 -87
  165. package/src/sync/partial-progress.ts +2 -55
  166. package/src/sync/remote-snapshot.ts +7 -79
  167. package/src/sync/session-merge.ts +2 -194
  168. package/src/sync/settings-conflicts.ts +2 -64
  169. package/src/sync/settings-merge.ts +6 -121
  170. package/src/sync/signals.ts +2 -8
  171. package/src/sync/startup-check.ts +15 -31
  172. package/src/sync/startup-timings.ts +2 -94
  173. package/src/sync/sync-decision.ts +3 -111
  174. package/src/sync/sync-error-guidance.ts +2 -46
  175. package/src/sync/sync-errors.ts +7 -23
  176. package/src/sync/sync-inspection.ts +10 -59
  177. package/src/sync/sync-local.ts +2 -44
  178. package/src/sync/sync-mutations.ts +10 -788
  179. package/src/sync/sync-operations.ts +32 -11
  180. package/src/sync/sync-policy.ts +34 -474
  181. package/src/sync/sync-queries.ts +2 -247
  182. package/src/sync/sync-state.ts +18 -157
  183. package/src/sync/text-merge.ts +10 -133
  184. package/src/sync-extension.ts +192 -142
  185. package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
  186. package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
  187. package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
  188. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
  189. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
  190. package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
  191. package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
  192. package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
  193. package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
  194. package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
  195. package/dist/chunks/chunk-25QCU3LY.ts +0 -220
  196. package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
  197. package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
  198. package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
  199. package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
  200. package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
  201. package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
  202. package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
  203. package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
  204. package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
  205. package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
  206. package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
  207. package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
  208. package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
  209. package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
  210. package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
  211. package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
  212. package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
  213. package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
  214. package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
  215. package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
  216. package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
  217. package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
  218. package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
  219. package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
  220. package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
  221. package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
  222. package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
  223. package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
  224. package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
  225. package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
  226. package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
  227. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  228. package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
  229. package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
  230. package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
  231. package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
  232. package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
  233. package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
  234. package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
  235. package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
  236. package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
  237. package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
  238. package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
  239. package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
  240. package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
  241. package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
  242. package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
  243. package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
  244. package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
  245. package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
  246. package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
  247. package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
  248. package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
  249. package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
  250. package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
  251. package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
  252. package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
  253. package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
  254. package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
  255. package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
  256. package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
  257. package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
  258. package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
  259. package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
  260. package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
  261. package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
  262. package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
  263. package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
  264. package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
  265. package/dist/chunks/chunk-VPODHKOX.ts +0 -229
  266. package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
  267. package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
  268. package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
  269. package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
  270. package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
  271. package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
  272. package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
  273. package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
  274. package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
  275. package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
  276. package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
  277. package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
  278. package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
  279. package/dist/chunks/chunk-YEULK7MK.ts +0 -415
  280. package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
  281. package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
  282. package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
  283. package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
  284. package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
  285. package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
  286. package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
  287. package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
  288. package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
  289. package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
  290. package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
  291. package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
  292. package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
  293. package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
  294. package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
  295. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
  296. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
  297. package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
  298. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
  299. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
  300. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
  301. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
  302. package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
  303. package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
  304. package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
  305. package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
  306. package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
  307. package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
  308. package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
  309. package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
  310. package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
  311. package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
  312. package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
  313. package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
  314. package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
  315. /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
  316. /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
  317. /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
  318. /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
  319. /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
  320. /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
  321. /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
@@ -1,946 +1,6 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import type { Stats } from "node:fs";
3
- import fs from "node:fs/promises";
4
- import path from "node:path";
5
- import { assertWithinRoot, isDeniedPath, isPathInside } from "../paths.js";
6
- import { syncDirectory, writeJson } from "../state/json-file.js";
7
- import { withLock } from "../state/lock.js";
8
- import { syncMutationParents } from "../state/mutation-directory-sync.js";
9
- import { stateDir } from "../state/state-directory.js";
10
- import { normalizeSyncExclude, sameSyncExclude } from "../sync/exclude-policy.js";
11
- import { mergePathIdentity } from "../sync/file-merge-planner.js";
12
- import { agentDir, configuredSessionDir } from "./session-paths.js";
13
- import { caseReplacementSpelling, coalesceCaseReplacements, isCaseReplacement } from "./snapshot-case-replacement.js";
14
- import { assertUnexcludedTargets } from "./snapshot-exclude-safety.js";
15
- import { withMissingTargetQueues, withTargetQueues } from "./snapshot-mutation-queues.js";
16
- import { sessionStorageRoot } from "./snapshot-paths.js";
17
- import {
18
- prepareSessionRootTransition,
19
- resolveTransitionSessionRoot,
20
- type SessionRootTransition,
21
- validateSessionRootTransition,
22
- } from "./snapshot-root-transition.js";
23
- import { pendingTransactionEntries, transactionRoot } from "./snapshot-transaction-directory.js";
24
- import { fileImage, indexTransactionPlan } from "./snapshot-transaction-plan.js";
25
- import type { SnapshotApplyPlan } from "./snapshot-types.js";
26
-
27
- const JOURNAL_VERSION = 4;
28
- interface TransactionEntry {
29
- target: string;
30
- /** Version 5: one physical file, original target spelling and intended installed spelling. */
31
- afterTarget?: string;
32
- backupName: string;
33
- kind: "missing" | "file" | "directory" | "symlink";
34
- linkTarget?: string;
35
- beforeImage?: string;
36
- afterImage?: string;
37
- postFiles?: { relative: string; image: string }[];
38
- /** Durable intent permits only a missing intermediate image, never unknown bytes. */
39
- removalPending?: boolean;
40
- /** Published before materialization: absence/partial trees can no longer prove an unstarted replacement. */
41
- replacementStarted?: boolean;
42
- /** Published before copying to a transaction-derived sibling staging path. */
43
- recoveryStaged?: boolean;
44
- }
45
- interface TransactionJournal {
46
- version: number;
47
- exclude?: string[];
48
- /** Version 6: durable files are accepted; surviving evidence permits cleanup only. */
49
- completed?: boolean;
50
- root: string;
51
- sessionRoot?: string;
52
- /** Version 7: reviewed settings images authorize recovery from either transition root. */
53
- sessionRootTransition?: SessionRootTransition;
54
- entries: TransactionEntry[];
55
- }
56
- interface TransactionOptions {
57
- sessionDir?: string;
58
- exclude?: readonly string[];
59
- signal?: AbortSignal;
60
- validateMutation?: () => void;
61
- protectedTargets?: readonly string[];
62
- /** Fresh apply authorization only; recovery remains bound to durable journal images. */
63
- expectedPreimages?: ReadonlyMap<string, string>;
64
- resolveConfiguredSessionDir?: boolean;
65
- }
66
-
67
- export async function applySnapshotTransaction(plan: SnapshotApplyPlan, options: TransactionOptions = {}) {
68
- options.validateMutation?.();
69
- await recoverPendingSnapshotTransactions(options);
70
- const coalesced = await coalesceCaseReplacements(path.resolve(agentDir()), plan);
71
- options.validateMutation?.();
72
- options.signal?.throwIfAborted();
73
- const targets = [...new Set([...coalesced.plan.deletes, ...coalesced.plan.writes.map((item) => item.target)])].sort();
74
- if (targets.length > 16_384)
75
- throw new Error("Snapshot transaction exceeds its target bound; review a smaller transfer.");
76
- return withTargetQueues(targets, options, async (heldKeys) => {
77
- await assertUnexcludedTargets(agentDir(), targets, options);
78
- options.signal?.throwIfAborted();
79
- if (
80
- targets.some((target) =>
81
- options.protectedTargets?.some(
82
- (protectedTarget) =>
83
- mergePathIdentity(target) === mergePathIdentity(protectedTarget) ||
84
- isPathInside(mergePathIdentity(target), mergePathIdentity(protectedTarget)),
85
- ),
86
- )
87
- )
88
- throw new Error("Snapshot transaction targets the current session; review is required.");
89
- for (const [before, after] of coalesced.replacements) {
90
- if ((await caseReplacementSpelling(before, after)) !== before)
91
- throw new Error("Case replacement changed before preparation; review is required.");
92
- options.validateMutation?.();
93
- options.signal?.throwIfAborted();
94
- }
95
- const originalTargets = new Map([...coalesced.replacements].map(([before, after]) => [after, before]));
96
- const expectedPreimages = new Map(
97
- [...(options.expectedPreimages ?? [])].map(([target, expected]) => [
98
- originalTargets.get(target) ?? target,
99
- expected,
100
- ]),
101
- );
102
- // A case-sensitive spelling replacement has two targets, unlike a coalesced physical alias.
103
- // Bind both the source bytes and destination absence/bytes before capturing their backups.
104
- for (const [target, expected] of options.expectedPreimages ?? []) {
105
- if (originalTargets.has(target)) continue;
106
- const variants = coalesced.plan.deletes.filter(
107
- (candidate) =>
108
- candidate !== target &&
109
- path.dirname(candidate) === path.dirname(target) &&
110
- mergePathIdentity(candidate) === mergePathIdentity(target),
111
- );
112
- if (variants.length > 1) throw new Error("Ambiguous reviewed file preimage spellings; review required.");
113
- const original = variants[0];
114
- if (!original) continue;
115
- const destination = await image(target);
116
- options.validateMutation?.();
117
- options.signal?.throwIfAborted();
118
- if (destination !== "missing" && destination !== expected)
119
- throw new Error("Reviewed destination preimage changed before apply.");
120
- expectedPreimages.set(original, expected);
121
- expectedPreimages.set(target, destination);
122
- }
123
- for (const [target, expected] of expectedPreimages) {
124
- const current = await image(target);
125
- options.validateMutation?.();
126
- options.signal?.throwIfAborted();
127
- if (current !== expected)
128
- throw new Error("Reviewed file preimage changed before apply; snapshot installation refused.");
129
- }
130
- const transaction = await prepareTransaction(
131
- coalesced.plan,
132
- targets,
133
- { ...options, expectedPreimages },
134
- coalesced.replacements,
135
- );
136
- const entriesByTarget = new Map(
137
- transaction.journal.entries.flatMap((entry) => [
138
- [entry.target, entry] as const,
139
- ...(entry.afterTarget ? [[entry.afterTarget, entry] as const] : []),
140
- ]),
141
- );
142
- // A released additional key cannot authorize rollback, even for recognized raced bytes.
143
- const changesQueueKey = transaction.journal.entries.some(
144
- (entry) => !heldKeys.has(entry.target) || (entry.afterTarget && !heldKeys.has(entry.afterTarget)),
145
- );
146
- try {
147
- for (const target of transaction.deletes.sort((a, b) => a.length - b.length)) {
148
- options.signal?.throwIfAborted();
149
- const entry = entriesByTarget.get(target);
150
- if (!entry) throw new Error("Unowned transaction target.");
151
- await removeOwnedTarget(transaction.directory, entry, transaction.journal, options);
152
- await syncDirectory(path.dirname(target));
153
- }
154
- await withMissingTargetQueues(
155
- transaction.journal.entries
156
- .filter((entry) => entry.removalPending)
157
- .flatMap((entry) => [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])]),
158
- heldKeys,
159
- options,
160
- async () => {
161
- await retireRemovalIntent(
162
- transaction.directory,
163
- transaction.journal,
164
- transaction.journal.entries.filter(
165
- (entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0),
166
- ),
167
- options,
168
- );
169
- // Only this uninterrupted call knows which deleted writes have not attempted installation yet.
170
- const uninstalledWrites = new Set(transaction.deletedWrites);
171
- for (const item of plan.writes) {
172
- options.signal?.throwIfAborted();
173
- const entry = entriesByTarget.get(item.target);
174
- if (!entry) throw new Error("Unowned transaction target.");
175
- const deletedByThisCall = uninstalledWrites.delete(entry.target);
176
- await verifyTarget(transaction.directory, entry, transaction.journal, deletedByThisCall);
177
- options.validateMutation?.();
178
- options.signal?.throwIfAborted();
179
- await fs.mkdir(path.dirname(item.target), { recursive: true });
180
- options.validateMutation?.();
181
- options.signal?.throwIfAborted();
182
- const temp = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
183
- try {
184
- let mode = 0o600;
185
- try {
186
- const stat = await fs.lstat(item.target);
187
- if (stat.isFile()) mode = stat.mode & 0o777;
188
- } catch (error) {
189
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
190
- }
191
- const handle = await fs.open(temp, "wx", mode);
192
- try {
193
- await handle.writeFile(item.content);
194
- await handle.sync();
195
- } finally {
196
- await handle.close();
197
- }
198
- await verifyTarget(transaction.directory, entry, transaction.journal, deletedByThisCall);
199
- options.signal?.throwIfAborted();
200
- options.validateMutation?.();
201
- await fs.rename(temp, item.target);
202
- await syncDirectory(path.dirname(item.target));
203
- } finally {
204
- await fs.rm(temp, { force: true });
205
- }
206
- }
207
- options.validateMutation?.();
208
- options.signal?.throwIfAborted();
209
- await syncMutationParents(
210
- targets,
211
- [transaction.journal.root, ...(transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : [])],
212
- options,
213
- );
214
- options.validateMutation?.();
215
- options.signal?.throwIfAborted();
216
- },
217
- );
218
- } catch (error) {
219
- // Aborted owners cannot roll back files after another session has replaced them.
220
- if (options.signal?.aborted)
221
- throw new Error("Snapshot apply cancelled; guarded transaction evidence retained for review.");
222
- // Additional queues have been released. Recovery must reserve missing keys afresh.
223
- if (changesQueueKey)
224
- throw new Error("Snapshot apply failed; guarded transaction evidence retained for review.", {
225
- cause: error,
226
- });
227
- try {
228
- await restoreTransaction(transaction.directory, transaction.journal, options, heldKeys);
229
- } catch (recoveryError) {
230
- throw new AggregateError(
231
- [error, recoveryError],
232
- "Snapshot apply failed and guarded recovery requires review. Transaction and backup retained; newer bytes were not restored over.",
233
- );
234
- }
235
- throw error;
236
- }
237
- // Files are durably installed. Cleanup cannot roll back once it starts deleting evidence.
238
- await completeTransaction(transaction.directory, transaction.journal);
239
- });
240
- }
241
-
242
- export async function recoverSnapshotTransactionsOnStartup(options: TransactionOptions = {}) {
243
- if (!(await pendingTransactionEntries()).some((entry) => entry.isDirectory())) return;
244
- // A pending settings.json may itself be the interrupted postimage. Read each journal
245
- // before consulting that file, and only consult it when a session target needs it.
246
- options.validateMutation?.();
247
- options.signal?.throwIfAborted();
248
- await withLock(
249
- "recovery",
250
- () => recoverPendingSnapshotTransactions({ ...options, resolveConfiguredSessionDir: true }),
251
- {
252
- reclaimStale: true,
253
- },
254
- );
255
- }
256
-
257
- export async function recoverPendingSnapshotTransactions(options: TransactionOptions = {}) {
258
- for (const entry of (await pendingTransactionEntries()).sort((a, b) => a.name.localeCompare(b.name))) {
259
- if (!entry.isDirectory()) continue;
260
- const directory = path.join(transactionRoot(), entry.name);
261
- let journal: TransactionJournal;
262
- try {
263
- const file = path.join(directory, "journal.json");
264
- const stat = await fs.lstat(file);
265
- if (!stat.isFile() || stat.size > 32 * 1024 * 1024) throw new Error("Invalid journal file.");
266
- journal = JSON.parse(await fs.readFile(file, "utf8")) as TransactionJournal;
267
- } catch (error) {
268
- // Unknown evidence is not disposable, including interrupted preparation directories.
269
- if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
270
- throw new Error("Cannot recover malformed pi-sync transaction; preserve private evidence for review.");
271
- }
272
- let sessionDir = options.sessionDir;
273
- if (
274
- sessionDir === undefined &&
275
- options.resolveConfiguredSessionDir &&
276
- !journal.completed &&
277
- transactionHasSessionTargets(journal)
278
- ) {
279
- sessionDir = await configuredSessionDir();
280
- }
281
- options.validateMutation?.();
282
- options.signal?.throwIfAborted();
283
- if (journal.sessionRootTransition && !journal.completed) {
284
- // Validate every path before consulting backup evidence under the recorded root.
285
- validateJournal(directory, journal, journal.sessionRoot);
286
- sessionDir = await resolveTransitionSessionRoot(
287
- directory,
288
- journal.root,
289
- journal.sessionRoot as string,
290
- journal.sessionRootTransition,
291
- journal.entries,
292
- path.resolve(sessionStorageRoot(journal.root, sessionDir)),
293
- options,
294
- );
295
- options.validateMutation?.();
296
- options.signal?.throwIfAborted();
297
- }
298
- validateJournal(directory, journal, sessionDir);
299
- if (!journal.completed && !sameSyncExclude(journal.exclude, options.exclude))
300
- throw new Error("Pending transaction has a different exclude policy; preserve its backup for reviewed recovery.");
301
- if (journal.completed) {
302
- await removeTransaction(directory);
303
- continue;
304
- }
305
- await withTargetQueues(journal.entries.map((entry) => entry.target).sort(), options, (heldKeys) =>
306
- restoreTransaction(directory, journal, { ...options, sessionDir }, heldKeys),
307
- );
308
- }
309
- }
310
-
311
- async function prepareTransaction(
312
- plan: SnapshotApplyPlan,
313
- targets: string[],
314
- options: TransactionOptions,
315
- replacements = new Map<string, string>(),
316
- ) {
317
- const { sessionDir } = options;
318
- const root = path.resolve(agentDir());
319
- const sessionRoot = sessionDir ? path.resolve(sessionStorageRoot(root, sessionDir)) : undefined;
320
- const indexed = indexTransactionPlan(plan, targets);
321
- const directory = path.join(transactionRoot(), randomUUID());
322
- const backupDirectory = path.join(directory, "before");
323
- await fs.mkdir(backupDirectory, { recursive: true, mode: 0o700 });
324
- const entries: TransactionEntry[] = [];
325
- for (const [index, target] of targets.entries()) {
326
- options.signal?.throwIfAborted();
327
- options.validateMutation?.();
328
- assertAllowedTarget(root, sessionRoot, target);
329
- await assertSafeParents(root, sessionRoot, target);
330
- const entry: TransactionEntry = { target, backupName: `${index}`, kind: "missing" };
331
- if (replacements.has(target)) entry.afterTarget = replacements.get(target);
332
- const backup = path.join(backupDirectory, entry.backupName);
333
- try {
334
- const stat = await fs.lstat(target);
335
- if (stat.isSymbolicLink()) {
336
- entry.kind = "symlink";
337
- entry.linkTarget = await fs.readlink(target);
338
- } else if (stat.isDirectory()) {
339
- entry.kind = "directory";
340
- await fs.cp(target, backup, {
341
- recursive: true,
342
- dereference: false,
343
- verbatimSymlinks: true,
344
- preserveTimestamps: true,
345
- filter: () => {
346
- options.signal?.throwIfAborted();
347
- options.validateMutation?.();
348
- return true;
349
- },
350
- });
351
- } else if (stat.isFile()) {
352
- entry.kind = "file";
353
- await fs.copyFile(target, backup);
354
- await fs.chmod(backup, stat.mode);
355
- } else throw new Error("Unsupported existing snapshot target.");
356
- } catch (error) {
357
- const code = (error as NodeJS.ErrnoException).code;
358
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
359
- }
360
- entry.beforeImage =
361
- entry.kind === "symlink"
362
- ? `symlink:${entry.linkTarget}`
363
- : entry.kind === "missing"
364
- ? "missing"
365
- : await image(backup, true);
366
- options.validateMutation?.();
367
- options.signal?.throwIfAborted();
368
- const expected = options.expectedPreimages?.get(target);
369
- if (expected !== undefined && entry.beforeImage !== expected)
370
- throw new Error("Reviewed file preimage changed during backup; private preparation evidence retained.");
371
- if (entry.afterTarget) {
372
- if (entry.kind !== "file" || (await caseReplacementSpelling(target, entry.afterTarget)) !== target)
373
- throw new Error("Case replacement preimage changed during backup; evidence retained for review.");
374
- options.validateMutation?.();
375
- options.signal?.throwIfAborted();
376
- }
377
- entry.afterImage = indexed.writeImages.get(target) ?? "missing";
378
- entry.postFiles = indexed.postFiles.get(target) ?? [];
379
- entries.push(entry);
380
- }
381
- // File fsync does not persist the name linking each backup into this directory.
382
- await syncDirectory(backupDirectory);
383
- const effectiveRoot = sessionRoot ?? path.join(root, "sessions");
384
- const sessionRootTransition = await prepareSessionRootTransition(
385
- directory,
386
- root,
387
- effectiveRoot,
388
- entries,
389
- plan,
390
- options,
391
- );
392
- const journal: TransactionJournal = {
393
- version: sessionRootTransition ? 7 : replacements.size ? 5 : JOURNAL_VERSION,
394
- root,
395
- ...(options.exclude === undefined ? {} : { exclude: normalizeSyncExclude(options.exclude) }),
396
- sessionRoot: sessionRootTransition ? effectiveRoot : sessionRoot,
397
- sessionRootTransition,
398
- entries,
399
- };
400
- options.signal?.throwIfAborted();
401
- options.validateMutation?.();
402
- await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
403
- await syncDirectory(transactionRoot());
404
- await syncDirectory(stateDir());
405
- await syncDirectory(path.dirname(stateDir()));
406
- return { directory, journal, deletes: indexed.deletes, deletedWrites: indexed.deletedWrites };
407
- }
408
-
409
- async function restoreTransaction(
410
- directory: string,
411
- journal: TransactionJournal,
412
- options: TransactionOptions,
413
- heldKeys: ReadonlySet<string>,
414
- ) {
415
- validateJournal(directory, journal, options.sessionDir);
416
- const missingSpellings: string[] = [];
417
- for (const entry of journal.entries) {
418
- if (!entry.afterTarget) continue;
419
- options.validateMutation?.();
420
- options.signal?.throwIfAborted();
421
- const spelling = await caseReplacementSpelling(entry.target, entry.afterTarget);
422
- options.validateMutation?.();
423
- options.signal?.throwIfAborted();
424
- if (spelling === undefined) missingSpellings.push(entry.target, entry.afterTarget);
425
- }
426
- // Reserve an interrupted removal's other spelling before staging or image checks:
427
- // recognizable bytes installed by a writer in that gap are not our postimage.
428
- return withMissingTargetQueues(missingSpellings, heldKeys, options, (reservedKeys) =>
429
- restoreQueuedTransaction(directory, journal, options, reservedKeys),
430
- );
431
- }
432
-
433
- async function restoreQueuedTransaction(
434
- directory: string,
435
- journal: TransactionJournal,
436
- options: TransactionOptions,
437
- heldKeys: ReadonlySet<string>,
438
- ) {
439
- validateJournal(directory, journal, options.sessionDir);
440
- options.validateMutation?.();
441
- options.signal?.throwIfAborted();
442
- for (const entry of journal.entries) {
443
- if (
444
- options.protectedTargets?.some(
445
- (target) =>
446
- mergePathIdentity(target) === mergePathIdentity(entry.target) ||
447
- isPathInside(mergePathIdentity(entry.target), mergePathIdentity(target)),
448
- )
449
- )
450
- throw new Error(
451
- "Pending transaction touches the current session; resume a different session before guarded recovery.",
452
- );
453
- await verifyTarget(directory, entry, journal);
454
- }
455
- // Recover copies left by a process crash even when the target is already restored.
456
- for (const entry of journal.entries) {
457
- if (!entry.recoveryStaged) continue;
458
- options.validateMutation?.();
459
- options.signal?.throwIfAborted();
460
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
461
- options.validateMutation?.();
462
- options.signal?.throwIfAborted();
463
- await fs.rm(recoveryStagePath(directory, entry), { recursive: true, force: true });
464
- options.validateMutation?.();
465
- options.signal?.throwIfAborted();
466
- }
467
- // Verify the complete group before removing any path. Recheck each destructive boundary.
468
- for (const entry of [...journal.entries].sort((a, b) => a.target.length - b.target.length)) {
469
- const current = await verifyTarget(directory, entry, journal);
470
- const before = await beforeImage(directory, entry);
471
- const spellingMatches = async () =>
472
- !entry.afterTarget || (await caseReplacementSpelling(entry.target, entry.afterTarget)) === entry.target;
473
- if (current === before && (await spellingMatches())) continue;
474
- options.signal?.throwIfAborted();
475
- options.validateMutation?.();
476
- if (entry.kind === "file") {
477
- const temporary = await prepareRecoveryStage(directory, journal, entry, options);
478
- try {
479
- await fs.mkdir(path.dirname(entry.target), { recursive: true });
480
- await fs.copyFile(path.join(directory, "before", entry.backupName), temporary);
481
- // Windows requires write access to flush an existing regular file.
482
- const handle = await fs.open(temporary, process.platform === "win32" ? "r+" : "r");
483
- try {
484
- await handle.sync();
485
- } finally {
486
- await handle.close();
487
- }
488
- const verified = await verifyTarget(directory, entry, journal);
489
- options.validateMutation?.();
490
- options.signal?.throwIfAborted();
491
- if (verified === before && (await spellingMatches())) continue;
492
- const needsCaseQueue =
493
- entry.afterTarget !== undefined &&
494
- (await caseReplacementSpelling(entry.target, entry.afterTarget)) === entry.afterTarget;
495
- if (needsCaseQueue) {
496
- // Keep the installed-spelling queue while reserving the now-missing original spelling.
497
- await removeOwnedTarget(directory, entry, journal, options);
498
- } else if (
499
- verified.startsWith("directory:") &&
500
- !(await removeOwnedTarget(directory, entry, journal, options, before))
501
- )
502
- continue;
503
- await withMissingTargetQueues(
504
- entry.afterTarget && (needsCaseQueue || verified === "missing")
505
- ? [entry.target, entry.afterTarget]
506
- : verified.startsWith("directory:")
507
- ? [entry.target]
508
- : [],
509
- heldKeys,
510
- options,
511
- async () => {
512
- const atRename = await verifyTarget(directory, entry, journal);
513
- options.validateMutation?.();
514
- options.signal?.throwIfAborted();
515
- if (atRename === before && (await spellingMatches())) return;
516
- await retireRestorationIntent(directory, journal, entry, options);
517
- const atInstall = await verifyTarget(directory, entry, journal, atRename === "missing");
518
- options.validateMutation?.();
519
- options.signal?.throwIfAborted();
520
- if (atInstall === before && (await spellingMatches())) return;
521
- await fs.rename(temporary, entry.target);
522
- await syncDirectory(path.dirname(entry.target));
523
- },
524
- );
525
- } finally {
526
- await fs.rm(temporary, { force: true });
527
- }
528
- continue;
529
- }
530
- if (entry.kind === "missing") {
531
- await removeOwnedTarget(directory, entry, journal, options, before);
532
- continue;
533
- }
534
- const temporary = await prepareRecoveryStage(directory, journal, entry, options);
535
- try {
536
- await fs.mkdir(path.dirname(entry.target), { recursive: true });
537
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
538
- if (entry.kind === "directory") {
539
- await fs.cp(path.join(directory, "before", entry.backupName), temporary, {
540
- recursive: true,
541
- dereference: false,
542
- verbatimSymlinks: true,
543
- preserveTimestamps: true,
544
- filter: () => {
545
- options.validateMutation?.();
546
- options.signal?.throwIfAborted();
547
- return true;
548
- },
549
- });
550
- } else if (entry.linkTarget !== undefined) await fs.symlink(entry.linkTarget, temporary);
551
- if ((await image(temporary, true)) !== before)
552
- throw new Error("Staged recovery image differs from the backup; evidence retained.");
553
- options.validateMutation?.();
554
- options.signal?.throwIfAborted();
555
- if (!(await removeOwnedTarget(directory, entry, journal, options, before))) continue;
556
- await withMissingTargetQueues([entry.target], heldKeys, options, async () => {
557
- const atRename = await verifyTarget(directory, entry, journal);
558
- options.validateMutation?.();
559
- options.signal?.throwIfAborted();
560
- if (atRename === before) return;
561
- await retireRestorationIntent(directory, journal, entry, options);
562
- const atInstall = await verifyTarget(directory, entry, journal, atRename === "missing");
563
- options.validateMutation?.();
564
- options.signal?.throwIfAborted();
565
- if (atInstall === before) return;
566
- await fs.rename(temporary, entry.target);
567
- await syncDirectory(path.dirname(entry.target));
568
- });
569
- } finally {
570
- await fs.rm(temporary, { recursive: true, force: true });
571
- }
572
- }
573
- await syncMutationParents(
574
- journal.entries.map((entry) => entry.target),
575
- [journal.root, ...(journal.sessionRoot ? [journal.sessionRoot] : [])],
576
- options,
577
- );
578
- options.validateMutation?.();
579
- options.signal?.throwIfAborted();
580
- await completeTransaction(directory, journal);
581
- }
582
-
583
- async function verifyTarget(
584
- directory: string,
585
- entry: TransactionEntry,
586
- journal: TransactionJournal,
587
- deletedByThisCall = false,
588
- ) {
589
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
590
- // Hash the potentially large backup before observing the live target, not after it.
591
- const before = await beforeImage(directory, entry);
592
- if (journal.version >= 2 && before !== entry.beforeImage)
593
- throw new Error("Transaction backup changed; preserve evidence for review.");
594
- if (entry.afterTarget) await caseReplacementSpelling(entry.target, entry.afterTarget);
595
- const current = await image(entry.target);
596
- if (current === before) return current;
597
- if (current === "missing") {
598
- if (deletedByThisCall || (journal.version >= 4 && entry.removalPending && !entry.replacementStarted))
599
- return current;
600
- } else if (
601
- journal.version >= 2 &&
602
- (current === entry.afterImage ||
603
- (await ownedPostTree(
604
- entry.target,
605
- entry.postFiles ?? [],
606
- journal.version < 4 || entry.replacementStarted === true || !entry.removalPending,
607
- )))
608
- )
609
- return current;
610
- throw new Error(
611
- "Transaction target has unrecognized or newer bytes; automatic rollback refused. Preserve the transaction and review its backup with Pi closed.",
612
- );
613
- }
614
-
615
- async function removeOwnedTarget(
616
- directory: string,
617
- entry: TransactionEntry,
618
- journal: TransactionJournal,
619
- options: TransactionOptions,
620
- restoringBefore?: string,
621
- ) {
622
- await assertUnexcludedTargets(journal.root, [entry.target], options);
623
- const current = await verifyTarget(directory, entry, journal);
624
- options.validateMutation?.();
625
- options.signal?.throwIfAborted();
626
- if (restoringBefore !== undefined && current === restoringBefore) return false;
627
- // Persist intent before removal, including descendants affected by a recursive delete.
628
- // Until replacement is armed, interrupted removal can recognize absence without accepting unknown bytes.
629
- upgradeRemovalEvidence(journal);
630
- for (const affected of journal.entries) {
631
- if (affected.target === entry.target || isStrictlyInside(entry.target, affected.target)) {
632
- affected.removalPending = true;
633
- affected.replacementStarted = false;
634
- }
635
- }
636
- await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
637
- const verified = await verifyTarget(directory, entry, journal);
638
- options.validateMutation?.();
639
- options.signal?.throwIfAborted();
640
- if (restoringBefore !== undefined && verified === restoringBefore) return false;
641
- await fs.rm(entry.target, { recursive: true, force: true });
642
- await syncDirectory(path.dirname(entry.target));
643
- return true;
644
- }
645
-
646
- function upgradeRemovalEvidence(journal: TransactionJournal) {
647
- if (journal.version < JOURNAL_VERSION) {
648
- // Old pending markers may already have survived a committed replacement.
649
- for (const entry of journal.entries) entry.removalPending = false;
650
- journal.version = JOURNAL_VERSION;
651
- }
652
- }
653
-
654
- async function retireRemovalIntent(
655
- directory: string,
656
- journal: TransactionJournal,
657
- entries: TransactionEntry[],
658
- options: TransactionOptions,
659
- ) {
660
- options.validateMutation?.();
661
- options.signal?.throwIfAborted();
662
- if (!entries.length) return;
663
- upgradeRemovalEvidence(journal);
664
- for (const entry of entries) {
665
- entry.removalPending = false;
666
- entry.replacementStarted = true;
667
- }
668
- await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
669
- options.validateMutation?.();
670
- options.signal?.throwIfAborted();
671
- }
672
-
673
- async function retireRestorationIntent(
674
- directory: string,
675
- journal: TransactionJournal,
676
- entry: TransactionEntry,
677
- options: TransactionOptions,
678
- ) {
679
- // Installing a complete parent preimage supersedes descendant replacement progress too.
680
- for (const child of journal.entries) {
681
- if (isStrictlyInside(entry.target, child.target)) {
682
- child.removalPending = false;
683
- child.replacementStarted = false;
684
- }
685
- }
686
- await retireRemovalIntent(directory, journal, [entry], options);
687
- }
688
-
689
- function recoveryStagePath(directory: string, entry: TransactionEntry) {
690
- const token = createHash("sha256").update(directory).update("\\0").update(entry.backupName).digest("hex");
691
- return path.join(
692
- path.dirname(entry.target),
693
- `.pi-sync.json.${token}.${entry.kind === "file" ? "restore" : "restore-tree"}`,
694
- );
695
- }
696
-
697
- async function prepareRecoveryStage(
698
- directory: string,
699
- journal: TransactionJournal,
700
- entry: TransactionEntry,
701
- options: TransactionOptions,
702
- ) {
703
- const temporary = recoveryStagePath(directory, entry);
704
- if (!entry.recoveryStaged) {
705
- try {
706
- await fs.lstat(temporary);
707
- throw new Error("Unowned recovery staging path; preserve evidence for review.");
708
- } catch (error) {
709
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
710
- }
711
- options.validateMutation?.();
712
- options.signal?.throwIfAborted();
713
- entry.recoveryStaged = true;
714
- await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
715
- options.validateMutation?.();
716
- options.signal?.throwIfAborted();
717
- }
718
- return temporary;
719
- }
720
-
721
- async function beforeImage(directory: string, entry: TransactionEntry) {
722
- if (entry.kind === "missing") return "missing";
723
- if (entry.kind === "symlink") return `symlink:${entry.linkTarget}`;
724
- const value = await image(path.join(directory, "before", entry.backupName));
725
- if (value === "missing") throw new Error("Transaction backup is missing; preserve evidence for review.");
726
- return value;
727
- }
728
- async function image(target: string, durable = false): Promise<string> {
729
- let stat: Stats;
730
- try {
731
- stat = await fs.lstat(target);
732
- } catch (error) {
733
- const code = (error as NodeJS.ErrnoException).code;
734
- if (code === "ENOENT" || code === "ENOTDIR") return "missing";
735
- throw error;
736
- }
737
- if (stat.isSymbolicLink()) return `symlink:${await fs.readlink(target)}`;
738
- if (stat.isFile()) {
739
- const content = await fs.readFile(target);
740
- if (durable) {
741
- // Keep POSIX read-only backup permissions; Windows flushing requires write access.
742
- const handle = await fs.open(target, process.platform === "win32" ? "r+" : "r");
743
- try {
744
- await handle.sync();
745
- } finally {
746
- await handle.close();
747
- }
748
- }
749
- return fileImage(content);
750
- }
751
- if (!stat.isDirectory()) throw new Error("Unsupported transaction image.");
752
- const entries = [];
753
- for (const name of (await fs.readdir(target)).sort())
754
- entries.push([name, await image(path.join(target, name), durable)]);
755
- if (durable) await syncDirectory(target);
756
- return `directory:${createHash("sha256").update(JSON.stringify(entries)).digest("hex")}`;
757
- }
758
- async function ownedPostTree(target: string, files: { relative: string; image: string }[], requireComplete: boolean) {
759
- if (!files.length) return false;
760
- const expected = new Map(files.map((file) => [mergePathIdentity(file.relative), file.image]));
761
- const prefixes = new Set<string>();
762
- for (const relative of expected.keys()) {
763
- for (
764
- let parent = path.dirname(relative);
765
- parent !== "." && parent !== path.dirname(parent);
766
- parent = path.dirname(parent)
767
- )
768
- prefixes.add(parent);
769
- }
770
- const seen = new Set<string>();
771
- async function visit(directory: string): Promise<boolean> {
772
- let stat: Stats;
773
- try {
774
- stat = await fs.lstat(directory);
775
- } catch {
776
- return false;
777
- }
778
- if (!stat.isDirectory() || stat.isSymbolicLink()) return false;
779
- for (const name of await fs.readdir(directory)) {
780
- const child = path.join(directory, name);
781
- const relative = mergePathIdentity(path.relative(target, child));
782
- const stat = await fs.lstat(child);
783
- if (stat.isDirectory() && !stat.isSymbolicLink()) {
784
- if (!prefixes.has(relative) || !(await visit(child))) return false;
785
- } else {
786
- if (expected.get(relative) !== (await image(child))) return false;
787
- seen.add(relative);
788
- }
789
- }
790
- return true;
791
- }
792
- return (await visit(target)) && (!requireComplete || [...expected.keys()].every((key) => seen.has(key)));
793
- }
794
-
795
- function validateJournal(directory: string, journal: TransactionJournal, sessionDir?: string) {
796
- if (
797
- ![1, 2, 3, 4, 5, 6, 7].includes(journal.version) ||
798
- !Array.isArray(journal.entries) ||
799
- journal.entries.length > 16_384
800
- )
801
- throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
802
- if (journal.exclude !== undefined && !Array.isArray(journal.exclude))
803
- throw new Error("Invalid transaction exclude policy; preserve evidence.");
804
- normalizeSyncExclude(journal.exclude);
805
- if (journal.completed !== undefined && (![6, 7].includes(journal.version) || journal.completed !== true))
806
- throw new Error("Invalid transaction completion evidence.");
807
- const root = path.resolve(agentDir());
808
- if (typeof journal.root !== "string" || path.resolve(journal.root) !== root)
809
- throw new Error("Transaction root no longer matches the Pi agent directory.");
810
- if (journal.sessionRootTransition !== undefined) {
811
- if (journal.version !== 7 || typeof journal.sessionRoot !== "string")
812
- throw new Error("Invalid session root-transition version.");
813
- validateSessionRootTransition(journal.sessionRootTransition);
814
- } else if (journal.version === 7) throw new Error("Missing session root-transition evidence.");
815
- const trustedSessionRoot = sessionDir
816
- ? path.resolve(sessionStorageRoot(root, sessionDir))
817
- : path.join(root, "sessions");
818
- if (
819
- journal.sessionRoot !== undefined &&
820
- (typeof journal.sessionRoot !== "string" ||
821
- !path.isAbsolute(journal.sessionRoot) ||
822
- path.resolve(journal.sessionRoot) !== journal.sessionRoot ||
823
- (!journal.completed && transactionHasSessionTargets(journal) && journal.sessionRoot !== trustedSessionRoot))
824
- )
825
- throw new Error("Transaction session root is not owned by this context; preserve evidence for review.");
826
- for (const entry of journal.entries) {
827
- if (
828
- !entry ||
829
- typeof entry.target !== "string" ||
830
- !path.isAbsolute(entry.target) ||
831
- path.resolve(entry.target) !== entry.target ||
832
- typeof entry.backupName !== "string" ||
833
- !/^\d+$/u.test(entry.backupName) ||
834
- !["missing", "file", "directory", "symlink"].includes(entry.kind)
835
- )
836
- throw new Error("Invalid pi-sync transaction entry.");
837
- assertWithinRoot(directory, path.join(directory, "before", entry.backupName));
838
- assertAllowedTarget(root, journal.sessionRoot, entry.target);
839
- if (
840
- entry.afterTarget !== undefined &&
841
- (![5, 6, 7].includes(journal.version) ||
842
- typeof entry.afterTarget !== "string" ||
843
- !isCaseReplacement(root, entry.target, entry.afterTarget) ||
844
- path.resolve(entry.afterTarget) !== entry.afterTarget ||
845
- entry.kind !== "file")
846
- )
847
- throw new Error("Invalid transaction case replacement evidence.");
848
- if (entry.afterTarget) assertAllowedTarget(root, journal.sessionRoot, entry.afterTarget);
849
- if (
850
- journal.version >= 2 &&
851
- ((entry.beforeImage === undefined ? !journal.completed : typeof entry.beforeImage !== "string") ||
852
- (entry.afterImage === undefined ? !journal.completed : typeof entry.afterImage !== "string") ||
853
- (entry.postFiles === undefined ? !journal.completed : !Array.isArray(entry.postFiles)))
854
- )
855
- throw new Error("Invalid transaction postimage evidence.");
856
- if (entry.recoveryStaged !== undefined && typeof entry.recoveryStaged !== "boolean")
857
- throw new Error("Invalid recovery staging evidence.");
858
- if (entry.removalPending !== undefined && (journal.version < 3 || typeof entry.removalPending !== "boolean"))
859
- throw new Error("Invalid transaction removal evidence.");
860
- if (
861
- entry.replacementStarted !== undefined &&
862
- (journal.version < 4 || typeof entry.replacementStarted !== "boolean")
863
- )
864
- throw new Error("Invalid transaction replacement evidence.");
865
- if (entry.removalPending && entry.replacementStarted)
866
- throw new Error("Conflicting transaction replacement evidence.");
867
- for (const file of entry.postFiles ?? []) {
868
- if (
869
- typeof file.relative !== "string" ||
870
- typeof file.image !== "string" ||
871
- !isStrictlyInside(entry.target, path.resolve(entry.target, file.relative))
872
- )
873
- throw new Error("Invalid transaction subtree evidence.");
874
- }
875
- }
876
- }
877
- function transactionHasSessionTargets(journal: TransactionJournal) {
878
- const root = path.resolve(agentDir());
879
- return (
880
- Array.isArray(journal.entries) &&
881
- journal.entries.some(
882
- (entry) =>
883
- typeof entry?.target === "string" &&
884
- (!isPathInside(root, entry.target) ||
885
- isPathInside(path.join(root, "sessions"), entry.target) ||
886
- (typeof journal.sessionRoot === "string" && isPathInside(journal.sessionRoot, entry.target))),
887
- )
888
- );
889
- }
890
- function isStrictlyInside(root: string, target: string) {
891
- return path.relative(path.resolve(root), path.resolve(target)) !== "" && isPathInside(root, target);
892
- }
893
-
894
- function assertAllowedTarget(root: string, sessionRoot: string | undefined, target: string) {
895
- const resolved = path.resolve(target);
896
- if (isStrictlyInside(root, resolved)) {
897
- if (isDeniedPath(path.relative(root, resolved))) throw new Error("Transaction targets denied private storage.");
898
- assertWithinRoot(root, resolved);
899
- return;
900
- }
901
- if (sessionRoot && isStrictlyInside(sessionRoot, resolved)) {
902
- if (isDeniedPath(`sessions/${path.relative(sessionRoot, resolved)}`))
903
- throw new Error("Transaction targets denied session storage.");
904
- assertWithinRoot(sessionRoot, resolved);
905
- return;
906
- }
907
- throw new Error("Transaction target is outside configured roots.");
908
- }
909
- async function assertSafeParents(root: string, sessionRoot: string | undefined, target: string) {
910
- assertAllowedTarget(root, sessionRoot, target);
911
- const boundary = isPathInside(root, target) ? root : sessionRoot;
912
- for (
913
- let parent = path.dirname(target);
914
- boundary && mergePathIdentity(parent) !== mergePathIdentity(boundary);
915
- parent = path.dirname(parent)
916
- ) {
917
- if (path.dirname(parent) === parent) throw new Error("Transaction parent did not reach its owned boundary.");
918
- try {
919
- const stat = await fs.lstat(parent);
920
- if ((!stat.isDirectory() && !stat.isFile()) || stat.isSymbolicLink())
921
- throw new Error("Unsafe transaction parent.");
922
- } catch (error) {
923
- const code = (error as NodeJS.ErrnoException).code;
924
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
925
- }
926
- }
927
- }
928
- async function completeTransaction(directory: string, journal: TransactionJournal) {
929
- // Publish completion before deleting any backup. A surviving journal after power loss
930
- // may only retry cleanup, never roll back already accepted files.
931
- await writeJson(
932
- path.join(directory, "journal.json"),
933
- { ...journal, version: journal.sessionRootTransition ? 7 : 6, completed: true },
934
- {
935
- maxBytes: 32 * 1024 * 1024,
936
- },
937
- );
938
- await removeTransaction(directory);
939
- }
940
- async function removeTransaction(directory: string) {
941
- await fs.rm(directory, { recursive: true, force: true });
942
- // After evidence deletion, failure cannot safely trigger rollback or withhold acceptance.
943
- // A failed cleanup fsync may leave obsolete evidence after power loss; live file durability
944
- // was established before cleanup; a surviving completed journal allows only cleanup.
945
- await syncDirectory(transactionRoot()).catch(() => {});
946
- }
1
+ export type * from "@narumitw/sync-daemon/engine/snapshot/snapshot-transaction";
2
+ export {
3
+ applySnapshotTransaction,
4
+ recoverPendingSnapshotTransactions,
5
+ recoverSnapshotTransactionsOnStartup,
6
+ } from "@narumitw/sync-daemon/engine/snapshot/snapshot-transaction";