@narumitw/pi-sync 0.58.1 → 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 (334) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +28 -15
  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-MG66XM5U.ts → chunk-4RNCZZY7.ts} +86 -36
  6. package/dist/chunks/chunk-4RNCZZY7.ts.map +7 -0
  7. package/dist/chunks/{config-HYG7G5EM.ts → chunk-7AC2RX4M.ts} +6 -12
  8. package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
  9. package/dist/chunks/{chunk-XEODG2PE.ts → chunk-BGGKHHO4.ts} +18 -14
  10. package/dist/chunks/{chunk-XEODG2PE.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-REMGB255.ts → chunk-MIXZVHFR.ts} +35 -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-JYILGR3K.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-U6GXGY5G.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-MRXE5AKK.ts → command-handler-3O76V7Q5.ts} +83 -87
  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-EPHGR2DU.ts → continuous-record-ZHUXVO4E.ts} +5 -13
  50. package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
  51. package/dist/chunks/{file-selection-IELTXSGZ.ts → file-selection-S6CNNNQI.ts} +14 -14
  52. package/dist/chunks/file-selection-S6CNNNQI.ts.map +7 -0
  53. package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
  54. package/dist/chunks/{manager-ui-AY34N4UY.ts → manager-ui-SJOBTJLY.ts} +221 -147
  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-KLGESLQX.ts → setup-switch-M3BAFGJM.ts} +9 -12
  59. package/dist/chunks/{setup-wizard-ZQAK35BP.ts → setup-wizard-NFAWP4KF.ts} +18 -20
  60. package/dist/chunks/{setup-wizard-ZQAK35BP.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
  61. package/dist/chunks/{snapshot-RGNDYT6A.ts → snapshot-D4SFDP5J.ts} +8 -12
  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-7L4NT7W2.ts → sync-state-FVCJJ7MY.ts} +5 -10
  71. package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
  72. package/dist/index.ts +269 -306
  73. package/dist/index.ts.map +4 -4
  74. package/docs/daemon-migration.md +93 -0
  75. package/docs/exclude-policy-audit.md +54 -0
  76. package/docs/exclude-review-ledger.md +36 -0
  77. package/docs/tui-contract.md +1 -1
  78. package/package.json +3 -5
  79. package/skills/configure-pi-sync/SKILL.md +5 -4
  80. package/skills/configure-pi-sync/references/configuration.md +91 -19
  81. package/src/backends/backend-factory.ts +2 -23
  82. package/src/backends/backend-identity.ts +5 -40
  83. package/src/backends/backend-types.ts +1 -81
  84. package/src/backends/git/git-backend.ts +6 -784
  85. package/src/backends/git/git-config.ts +8 -130
  86. package/src/backends/git/git-runner.ts +7 -255
  87. package/src/backends/git/git-storage.ts +14 -292
  88. package/src/backends/s3/s3-backend.ts +11 -523
  89. package/src/backends/s3/s3-client.ts +2 -399
  90. package/src/backends/s3/s3-conditions.ts +2 -67
  91. package/src/backends/snapshot-pointer.ts +2 -27
  92. package/src/backends/sync-backend.ts +6 -101
  93. package/src/backends/webdav/webdav-backend.ts +10 -622
  94. package/src/backends/webdav/webdav-client.ts +6 -370
  95. package/src/backends/webdav/webdav-config.ts +8 -82
  96. package/src/commands/command-execution.ts +42 -38
  97. package/src/commands/command.ts +23 -1
  98. package/src/daemon/apply-gate.ts +146 -0
  99. package/src/daemon/pi-client.ts +591 -0
  100. package/src/daemon/recovery.ts +103 -0
  101. package/src/paths.ts +12 -83
  102. package/src/settings/config-errors.ts +2 -6
  103. package/src/settings/config-file.ts +19 -693
  104. package/src/settings/config.ts +16 -257
  105. package/src/settings/settings-management.ts +11 -253
  106. package/src/settings/settings-store.ts +10 -48
  107. package/src/settings/settings-types.ts +1 -154
  108. package/src/settings/settings-validation.ts +17 -431
  109. package/src/snapshot/session-paths.ts +11 -110
  110. package/src/snapshot/snapshot-apply.ts +9 -306
  111. package/src/snapshot/snapshot-case-replacement.ts +6 -80
  112. package/src/snapshot/snapshot-codec.ts +2 -50
  113. package/src/snapshot/snapshot-exclude-safety.ts +2 -0
  114. package/src/snapshot/snapshot-mutation-queues.ts +6 -142
  115. package/src/snapshot/snapshot-paths.ts +2 -11
  116. package/src/snapshot/snapshot-root-transition.ts +6 -154
  117. package/src/snapshot/snapshot-transaction-directory.ts +5 -16
  118. package/src/snapshot/snapshot-transaction-plan.ts +2 -72
  119. package/src/snapshot/snapshot-transaction.ts +6 -934
  120. package/src/snapshot/snapshot-types.ts +1 -43
  121. package/src/snapshot/snapshot.ts +18 -405
  122. package/src/state/json-file.ts +2 -47
  123. package/src/state/lock-policy.ts +2 -2
  124. package/src/state/lock.ts +10 -292
  125. package/src/state/lockfile-fs.ts +2 -25
  126. package/src/state/merge-baseline-store.ts +8 -200
  127. package/src/state/mutation-directory-sync.ts +2 -34
  128. package/src/state/operation-availability.ts +7 -59
  129. package/src/state/state-directory.ts +8 -243
  130. package/src/state/state-types.ts +1 -24
  131. package/src/state/sync-state-store.ts +11 -75
  132. package/src/sync/agent-candidate.ts +7 -256
  133. package/src/sync/agent-plan.ts +2 -107
  134. package/src/sync/agent-policy.ts +10 -13
  135. package/src/sync/agent-refusal-retry.ts +2 -54
  136. package/src/sync/agent-request.ts +2 -19
  137. package/src/sync/agent-runner.ts +2 -191
  138. package/src/sync/agent-store.ts +7 -182
  139. package/src/sync/agent-sync.ts +2 -141
  140. package/src/sync/apply-review.ts +2 -63
  141. package/src/sync/automatic-sync.ts +55 -106
  142. package/src/sync/conflict-artifact-ownership.ts +2 -63
  143. package/src/sync/conflict-artifacts.ts +8 -195
  144. package/src/sync/conflict-groups.ts +2 -68
  145. package/src/sync/conflict-preview.ts +2 -56
  146. package/src/sync/conflict-resolution.ts +2 -93
  147. package/src/sync/conflict-retention.ts +2 -72
  148. package/src/sync/conflict-review.ts +3 -92
  149. package/src/sync/content-conflicts.ts +2 -73
  150. package/src/sync/continuous-errors.ts +7 -85
  151. package/src/sync/continuous-lease.ts +2 -216
  152. package/src/sync/continuous-record.ts +10 -261
  153. package/src/sync/continuous-storage.ts +12 -64
  154. package/src/sync/continuous-sync.ts +2 -563
  155. package/src/sync/continuous-watch.ts +2 -59
  156. package/src/sync/exclude-policy.ts +6 -0
  157. package/src/sync/field-migration.ts +2 -39
  158. package/src/sync/file-merge-planner.ts +2 -143
  159. package/src/sync/json-document.ts +7 -184
  160. package/src/sync/local-field-policy.ts +2 -29
  161. package/src/sync/local-fields.ts +9 -108
  162. package/src/sync/merge-apply.ts +2 -434
  163. package/src/sync/merge-journal.ts +10 -219
  164. package/src/sync/merge-transfer-error.ts +2 -72
  165. package/src/sync/merged-sync.ts +2 -914
  166. package/src/sync/mutation-owner.ts +2 -22
  167. package/src/sync/package-merge.ts +2 -87
  168. package/src/sync/partial-progress.ts +2 -54
  169. package/src/sync/remote-snapshot.ts +7 -80
  170. package/src/sync/session-merge.ts +2 -194
  171. package/src/sync/settings-conflicts.ts +2 -64
  172. package/src/sync/settings-merge.ts +6 -121
  173. package/src/sync/signals.ts +2 -8
  174. package/src/sync/startup-check.ts +15 -31
  175. package/src/sync/startup-timings.ts +2 -94
  176. package/src/sync/sync-decision.ts +3 -101
  177. package/src/sync/sync-error-guidance.ts +2 -46
  178. package/src/sync/sync-errors.ts +7 -23
  179. package/src/sync/sync-inspection.ts +10 -57
  180. package/src/sync/sync-local.ts +2 -44
  181. package/src/sync/sync-mutations.ts +10 -781
  182. package/src/sync/sync-operations.ts +32 -11
  183. package/src/sync/sync-policy.ts +34 -410
  184. package/src/sync/sync-queries.ts +2 -237
  185. package/src/sync/sync-state.ts +18 -151
  186. package/src/sync/text-merge.ts +10 -133
  187. package/src/sync-extension.ts +192 -142
  188. package/src/ui/excluded-paths-ui.ts +106 -0
  189. package/src/ui/file-selection.ts +6 -3
  190. package/src/ui/manager-state.ts +11 -5
  191. package/src/ui/remote-selection-ui.ts +73 -10
  192. package/src/ui/settings-ui.ts +20 -5
  193. package/src/ui/setup/setup-actions.ts +1 -1
  194. package/src/ui/setup/setup-switcher.ts +3 -2
  195. package/src/ui/storage-connections-ui.ts +2 -2
  196. package/src/ui/sync-attention.ts +17 -3
  197. package/src/ui/sync-format.ts +13 -1
  198. package/dist/chunks/agent-candidate-U2NU3GUX.ts +0 -29
  199. package/dist/chunks/agent-plan-3YXDIJXO.ts +0 -123
  200. package/dist/chunks/agent-plan-3YXDIJXO.ts.map +0 -7
  201. package/dist/chunks/agent-refusal-retry-476YGNU5.ts +0 -72
  202. package/dist/chunks/agent-refusal-retry-476YGNU5.ts.map +0 -7
  203. package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
  204. package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
  205. package/dist/chunks/agent-store-7GINKTS7.ts +0 -175
  206. package/dist/chunks/agent-store-7GINKTS7.ts.map +0 -7
  207. package/dist/chunks/agent-sync-2R4GG2MF.ts +0 -22
  208. package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
  209. package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
  210. package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
  211. package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
  212. package/dist/chunks/chunk-45COPAK7.ts +0 -205
  213. package/dist/chunks/chunk-45COPAK7.ts.map +0 -7
  214. package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
  215. package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
  216. package/dist/chunks/chunk-5TSCBBPP.ts +0 -229
  217. package/dist/chunks/chunk-5TSCBBPP.ts.map +0 -7
  218. package/dist/chunks/chunk-6LD5KX55.ts +0 -396
  219. package/dist/chunks/chunk-6LD5KX55.ts.map +0 -7
  220. package/dist/chunks/chunk-6O3EDBRL.ts +0 -258
  221. package/dist/chunks/chunk-6O3EDBRL.ts.map +0 -7
  222. package/dist/chunks/chunk-7A35ZAVO.ts +0 -1109
  223. package/dist/chunks/chunk-7A35ZAVO.ts.map +0 -7
  224. package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
  225. package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
  226. package/dist/chunks/chunk-7ZIYU5QS.ts +0 -64
  227. package/dist/chunks/chunk-7ZIYU5QS.ts.map +0 -7
  228. package/dist/chunks/chunk-AKMV47YC.ts +0 -215
  229. package/dist/chunks/chunk-AKMV47YC.ts.map +0 -7
  230. package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
  231. package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
  232. package/dist/chunks/chunk-BEST45H2.ts +0 -153
  233. package/dist/chunks/chunk-BEST45H2.ts.map +0 -7
  234. package/dist/chunks/chunk-CBLTWXAU.ts +0 -114
  235. package/dist/chunks/chunk-CBLTWXAU.ts.map +0 -7
  236. package/dist/chunks/chunk-CQD2TJHE.ts +0 -220
  237. package/dist/chunks/chunk-CQD2TJHE.ts.map +0 -7
  238. package/dist/chunks/chunk-DN4IA7MR.ts +0 -61
  239. package/dist/chunks/chunk-DN4IA7MR.ts.map +0 -7
  240. package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
  241. package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
  242. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  243. package/dist/chunks/chunk-ESKOPQVB.ts +0 -348
  244. package/dist/chunks/chunk-ESKOPQVB.ts.map +0 -7
  245. package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
  246. package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
  247. package/dist/chunks/chunk-FLHCOJCD.ts +0 -57
  248. package/dist/chunks/chunk-FLHCOJCD.ts.map +0 -7
  249. package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
  250. package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
  251. package/dist/chunks/chunk-GNYGNHFF.ts +0 -27
  252. package/dist/chunks/chunk-GNYGNHFF.ts.map +0 -7
  253. package/dist/chunks/chunk-KYTT7KV4.ts +0 -319
  254. package/dist/chunks/chunk-KYTT7KV4.ts.map +0 -7
  255. package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
  256. package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
  257. package/dist/chunks/chunk-MG66XM5U.ts.map +0 -7
  258. package/dist/chunks/chunk-MKSMJPVA.ts +0 -107
  259. package/dist/chunks/chunk-MKSMJPVA.ts.map +0 -7
  260. package/dist/chunks/chunk-MMQIEDZ6.ts +0 -1994
  261. package/dist/chunks/chunk-MMQIEDZ6.ts.map +0 -7
  262. package/dist/chunks/chunk-OJARL2TG.ts +0 -25
  263. package/dist/chunks/chunk-OJARL2TG.ts.map +0 -7
  264. package/dist/chunks/chunk-OVBAW7KV.ts +0 -1174
  265. package/dist/chunks/chunk-OVBAW7KV.ts.map +0 -7
  266. package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
  267. package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
  268. package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
  269. package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
  270. package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
  271. package/dist/chunks/chunk-REMGB255.ts.map +0 -7
  272. package/dist/chunks/chunk-S5OCYVPS.ts +0 -415
  273. package/dist/chunks/chunk-S5OCYVPS.ts.map +0 -7
  274. package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
  275. package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
  276. package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
  277. package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
  278. package/dist/chunks/chunk-TIMWN2RH.ts +0 -89
  279. package/dist/chunks/chunk-TIMWN2RH.ts.map +0 -7
  280. package/dist/chunks/chunk-TZC7GDJE.ts +0 -58
  281. package/dist/chunks/chunk-TZC7GDJE.ts.map +0 -7
  282. package/dist/chunks/chunk-U6GXGY5G.ts.map +0 -7
  283. package/dist/chunks/chunk-WQMYV4DW.ts +0 -140
  284. package/dist/chunks/chunk-WQMYV4DW.ts.map +0 -7
  285. package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
  286. package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
  287. package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
  288. package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
  289. package/dist/chunks/chunk-Y4UVXOLQ.ts +0 -123
  290. package/dist/chunks/chunk-Y4UVXOLQ.ts.map +0 -7
  291. package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
  292. package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
  293. package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
  294. package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
  295. package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
  296. package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
  297. package/dist/chunks/command-handler-MRXE5AKK.ts.map +0 -7
  298. package/dist/chunks/conflict-artifacts-J6WSDCWP.ts +0 -32
  299. package/dist/chunks/conflict-review-GXA6Y7KY.ts +0 -189
  300. package/dist/chunks/conflict-review-GXA6Y7KY.ts.map +0 -7
  301. package/dist/chunks/continuous-sync-FAFNLEUW.ts +0 -585
  302. package/dist/chunks/continuous-sync-FAFNLEUW.ts.map +0 -7
  303. package/dist/chunks/file-selection-IELTXSGZ.ts.map +0 -7
  304. package/dist/chunks/git-backend-KHD36W27.ts +0 -1077
  305. package/dist/chunks/git-backend-KHD36W27.ts.map +0 -7
  306. package/dist/chunks/local-fields-JEKAPZKD.ts +0 -26
  307. package/dist/chunks/local-fields-JEKAPZKD.ts.map +0 -7
  308. package/dist/chunks/manager-result-dispatcher-XCYPW7RC.ts +0 -32
  309. package/dist/chunks/manager-result-dispatcher-XCYPW7RC.ts.map +0 -7
  310. package/dist/chunks/manager-ui-AY34N4UY.ts.map +0 -7
  311. package/dist/chunks/merge-baseline-store-65GKUMXI.ts +0 -25
  312. package/dist/chunks/merge-baseline-store-65GKUMXI.ts.map +0 -7
  313. package/dist/chunks/remote-selection-ui-MYM2YCPF.ts +0 -31
  314. package/dist/chunks/remote-selection-ui-MYM2YCPF.ts.map +0 -7
  315. package/dist/chunks/s3-backend-L24UZ6IK.ts +0 -844
  316. package/dist/chunks/s3-backend-L24UZ6IK.ts.map +0 -7
  317. package/dist/chunks/setup-switch-KLGESLQX.ts.map +0 -7
  318. package/dist/chunks/snapshot-RGNDYT6A.ts.map +0 -7
  319. package/dist/chunks/snapshot-transaction-26BQO36S.ts +0 -24
  320. package/dist/chunks/snapshot-transaction-26BQO36S.ts.map +0 -7
  321. package/dist/chunks/sync-inspection-MOMLGUTD.ts +0 -25
  322. package/dist/chunks/sync-inspection-MOMLGUTD.ts.map +0 -7
  323. package/dist/chunks/sync-operations-45APGOL3.ts +0 -1021
  324. package/dist/chunks/sync-operations-45APGOL3.ts.map +0 -7
  325. package/dist/chunks/sync-state-7L4NT7W2.ts.map +0 -7
  326. package/dist/chunks/webdav-backend-3ZCACILP.ts +0 -851
  327. package/dist/chunks/webdav-backend-3ZCACILP.ts.map +0 -7
  328. /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
  329. /package/dist/chunks/{chunk-JYILGR3K.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
  330. /package/dist/chunks/{agent-candidate-U2NU3GUX.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
  331. /package/dist/chunks/{agent-sync-2R4GG2MF.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
  332. /package/dist/chunks/{config-HYG7G5EM.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
  333. /package/dist/chunks/{conflict-artifacts-J6WSDCWP.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
  334. /package/dist/chunks/{continuous-record-EPHGR2DU.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
@@ -1,1109 +0,0 @@
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
- pendingTransactionEntries,
5
- transactionRoot
6
- } from "./chunk-5SFMBY5P.ts";
7
- import {
8
- withLock
9
- } from "./chunk-6O3EDBRL.ts";
10
- import {
11
- mergePathIdentity
12
- } from "./chunk-XJHQPB3E.ts";
13
- import {
14
- syncDirectory,
15
- writeJson
16
- } from "./chunk-AR2DGDUI.ts";
17
- import {
18
- stateDir
19
- } from "./chunk-SWRVXVFD.ts";
20
- import {
21
- agentDir,
22
- configuredSessionDir,
23
- expandSessionDir,
24
- sessionStorageRoot
25
- } from "./chunk-CBLTWXAU.ts";
26
- import {
27
- assertWithinRoot,
28
- isDeniedPath,
29
- isPathInside
30
- } from "./chunk-FHE2DCA2.ts";
31
-
32
- // src/snapshot/snapshot-transaction.ts
33
- import { createHash as createHash2, randomUUID } from "node:crypto";
34
- import fs4 from "node:fs/promises";
35
- import path6 from "node:path";
36
-
37
- // src/state/mutation-directory-sync.ts
38
- import path from "node:path";
39
- async function syncMutationParents(targets, roots, options = {}) {
40
- const directories = /* @__PURE__ */ new Set();
41
- for (const target of targets) {
42
- const root = roots.map((root2) => path.resolve(root2)).find((root2) => isPathInside(root2, target));
43
- if (!root) throw new Error("Unowned mutation directory.");
44
- for (let parent = path.dirname(target); ; parent = path.dirname(parent)) {
45
- directories.add(parent);
46
- if (mergePathIdentity(parent) === mergePathIdentity(root)) break;
47
- if (path.dirname(parent) === parent) throw new Error("Mutation directory escaped its owned root.");
48
- }
49
- }
50
- for (const directory of [...directories].sort((a, b) => b.length - a.length)) {
51
- options.signal?.throwIfAborted();
52
- options.validateMutation?.();
53
- try {
54
- await syncDirectory(directory);
55
- } catch (error) {
56
- const code = error.code;
57
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
58
- }
59
- options.signal?.throwIfAborted();
60
- options.validateMutation?.();
61
- }
62
- }
63
-
64
- // src/snapshot/snapshot-case-replacement.ts
65
- import fs from "node:fs/promises";
66
- import path2 from "node:path";
67
- function isCaseReplacement(root, before, after) {
68
- return before !== after && path2.dirname(before) === root && path2.dirname(after) === root && path2.basename(before).toLowerCase() === path2.basename(after).toLowerCase();
69
- }
70
- async function caseReplacementSpelling(before, after) {
71
- const observations = await Promise.all(
72
- [before, after].map(async (target) => {
73
- try {
74
- const stat = await fs.lstat(target);
75
- if (!stat.isFile() || stat.nlink !== 1) throw new Error("Unsafe case replacement target.");
76
- return await fs.realpath(target);
77
- } catch (error) {
78
- if (error.code === "ENOENT") return void 0;
79
- throw error;
80
- }
81
- })
82
- );
83
- if (observations.every((value) => value === void 0)) return void 0;
84
- if (!observations[0] || observations[0] !== observations[1])
85
- throw new Error("Case replacement no longer identifies one physical file; preserve evidence for review.");
86
- const names = (await fs.readdir(path2.dirname(before))).filter(
87
- (name) => name.toLowerCase() === path2.basename(before).toLowerCase()
88
- );
89
- if (names.length !== 1 || names[0] !== path2.basename(before) && names[0] !== path2.basename(after))
90
- throw new Error("Case replacement spelling changed; preserve evidence for review.");
91
- return path2.join(path2.dirname(before), names[0]);
92
- }
93
- async function coalesceCaseReplacements(root, plan) {
94
- const replacements = /* @__PURE__ */ new Map();
95
- const deletesByCase = /* @__PURE__ */ new Map();
96
- const writeTargets = new Set(plan.writes.map((item) => item.target));
97
- for (const target of new Set(plan.deletes)) {
98
- if (path2.dirname(target) !== root || writeTargets.has(target)) continue;
99
- const key = path2.basename(target).toLowerCase();
100
- const group = deletesByCase.get(key) ?? [];
101
- group.push(target);
102
- deletesByCase.set(key, group);
103
- }
104
- for (const item of plan.writes) {
105
- if (path2.dirname(item.target) !== root) continue;
106
- const candidates = deletesByCase.get(path2.basename(item.target).toLowerCase()) ?? [];
107
- if (candidates.length !== 1) continue;
108
- const before = candidates[0];
109
- if (!before || !isCaseReplacement(root, before, item.target)) continue;
110
- let beforePath;
111
- let afterPath;
112
- try {
113
- [beforePath, afterPath] = await Promise.all([fs.realpath(before), fs.realpath(item.target)]);
114
- } catch (error) {
115
- if (error.code === "ENOENT") continue;
116
- throw error;
117
- }
118
- if (beforePath !== afterPath) continue;
119
- if (replacements.has(before)) throw new Error("Multiple writes alias a case replacement target.");
120
- if (await caseReplacementSpelling(before, item.target) !== before)
121
- throw new Error("Case replacement preimage spelling changed; review is required.");
122
- replacements.set(before, item.target);
123
- }
124
- const beforeByAfter = new Map([...replacements].map(([before, after]) => [after, before]));
125
- return {
126
- replacements,
127
- plan: {
128
- deletes: plan.deletes,
129
- writes: plan.writes.map((item) => ({ ...item, target: beforeByAfter.get(item.target) ?? item.target }))
130
- }
131
- };
132
- }
133
-
134
- // src/snapshot/snapshot-mutation-queues.ts
135
- import fs2 from "node:fs/promises";
136
- import path3 from "node:path";
137
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
138
- function assertCurrent(options) {
139
- options.validateMutation?.();
140
- options.signal?.throwIfAborted();
141
- }
142
- function isMissing(error) {
143
- const code = error.code;
144
- return code === "ENOENT" || code === "ENOTDIR";
145
- }
146
- async function targetMissing(target, options) {
147
- assertCurrent(options);
148
- try {
149
- await fs2.lstat(target);
150
- assertCurrent(options);
151
- return false;
152
- } catch (error) {
153
- assertCurrent(options);
154
- if (!isMissing(error)) throw error;
155
- return true;
156
- }
157
- }
158
- async function queueKey(target, options) {
159
- assertCurrent(options);
160
- try {
161
- const key = await fs2.realpath(target);
162
- assertCurrent(options);
163
- return key;
164
- } catch (error) {
165
- assertCurrent(options);
166
- if (!isMissing(error)) throw error;
167
- return path3.resolve(target);
168
- }
169
- }
170
- async function assertCanonicalParent(target, options) {
171
- const parent = path3.dirname(path3.resolve(target));
172
- const suffix = [];
173
- for (let current = parent; ; current = path3.dirname(current)) {
174
- assertCurrent(options);
175
- let canonical;
176
- try {
177
- canonical = await fs2.realpath(current);
178
- } catch (error) {
179
- assertCurrent(options);
180
- if (!isMissing(error) || path3.dirname(current) === current) throw error;
181
- suffix.unshift(path3.basename(current));
182
- continue;
183
- }
184
- assertCurrent(options);
185
- if (path3.join(canonical, ...suffix) !== parent)
186
- throw new Error(
187
- "Snapshot mutation through an aliased parent is unsafe; use the canonical agent/session path. Transaction evidence retained for review."
188
- );
189
- return;
190
- }
191
- }
192
- async function assertCanonicalMutationTargets(targets, options) {
193
- for (const target of targets) await assertCanonicalParent(target, options);
194
- }
195
- async function withTargetQueues(targets, options, action) {
196
- await assertCanonicalMutationTargets(targets, options);
197
- const keys = /* @__PURE__ */ new Set();
198
- const missing = /* @__PURE__ */ new Set();
199
- for (const target of targets) {
200
- if (await targetMissing(target, options)) missing.add(target);
201
- const key = await queueKey(target, options);
202
- if (keys.has(key)) throw new Error("Transaction targets alias the same file.");
203
- keys.add(key);
204
- }
205
- const ordered = [...keys].sort();
206
- async function acquire(index) {
207
- assertCurrent(options);
208
- const key = ordered[index];
209
- if (key) return withFileMutationQueue(key, () => acquire(index + 1));
210
- for (const target of targets) {
211
- await assertCanonicalParent(target, options);
212
- if (missing.has(target) && !await targetMissing(target, options))
213
- throw new Error("Missing transaction target appeared during queue acquisition; review is required.");
214
- if (!keys.has(await queueKey(target, options)))
215
- throw new Error("Transaction queue identity changed; review is required.");
216
- }
217
- assertCurrent(options);
218
- return action(keys);
219
- }
220
- return acquire(0);
221
- }
222
- async function withMissingTargetQueues(targets, heldKeys, options, action) {
223
- const unique = [...new Set(targets)];
224
- const requireAbsent = async () => {
225
- for (const target of unique) {
226
- await assertCanonicalParent(target, options);
227
- if (!await targetMissing(target, options))
228
- throw new Error("Snapshot target changed before destination queue reservation; evidence retained.");
229
- }
230
- };
231
- const keys = unique.map((target) => path3.resolve(target)).filter((key) => !heldKeys.has(key)).sort();
232
- await requireAbsent();
233
- const combined = /* @__PURE__ */ new Set([...heldKeys, ...keys]);
234
- async function acquire(index) {
235
- assertCurrent(options);
236
- const key = keys[index];
237
- if (key) return withFileMutationQueue(key, () => acquire(index + 1));
238
- await requireAbsent();
239
- assertCurrent(options);
240
- return action(combined);
241
- }
242
- return acquire(0);
243
- }
244
-
245
- // src/snapshot/snapshot-root-transition.ts
246
- import fs3 from "node:fs/promises";
247
- import path5 from "node:path";
248
-
249
- // src/snapshot/snapshot-transaction-plan.ts
250
- import { createHash } from "node:crypto";
251
- import path4 from "node:path";
252
- function fileImage(content) {
253
- return `file:${createHash("sha256").update(content).digest("hex")}`;
254
- }
255
- function indexTransactionPlan(plan, targets) {
256
- const targetIndex = indexTargets(targets);
257
- const writeImages = /* @__PURE__ */ new Map();
258
- const postFiles = new Map(targets.map((target) => [target, []]));
259
- for (const write of plan.writes) {
260
- const image2 = fileImage(write.content);
261
- if (!writeImages.has(write.target)) writeImages.set(write.target, image2);
262
- for (const ancestor of ancestorTargets(write.target, targetIndex, false)) {
263
- if (ancestor !== write.target && isStrictDescendant(ancestor, write.target)) {
264
- postFiles.get(ancestor)?.push({ relative: path4.relative(ancestor, write.target), image: image2 });
265
- }
266
- }
267
- }
268
- const deleteIndex = indexTargets(plan.deletes);
269
- const deletes = plan.deletes.filter((target) => {
270
- for (const ancestor of ancestorTargets(target, deleteIndex, false)) {
271
- if (ancestor !== target && isStrictDescendant(ancestor, target)) return false;
272
- }
273
- return true;
274
- });
275
- const deletedWrites = /* @__PURE__ */ new Set();
276
- const outerDeleteIndex = indexTargets(deletes);
277
- for (const write of plan.writes) {
278
- for (const ancestor of ancestorTargets(write.target, outerDeleteIndex)) {
279
- if (ancestor === write.target || isPathInside(ancestor, write.target)) {
280
- deletedWrites.add(write.target);
281
- break;
282
- }
283
- }
284
- }
285
- return { writeImages, postFiles, deletes, deletedWrites };
286
- }
287
- function isStrictDescendant(parent, target) {
288
- return path4.relative(path4.resolve(parent), path4.resolve(target)) !== "" && isPathInside(parent, target);
289
- }
290
- function pathKey(target) {
291
- const resolved = path4.resolve(target);
292
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
293
- }
294
- function indexTargets(targets) {
295
- const index = /* @__PURE__ */ new Map();
296
- for (const target of new Set(targets)) {
297
- const key = pathKey(target);
298
- const rows = index.get(key) ?? [];
299
- rows.push(target);
300
- index.set(key, rows);
301
- }
302
- return index;
303
- }
304
- function* ancestorTargets(target, index, includeSelf = true) {
305
- const resolved = path4.resolve(target);
306
- for (let ancestor = includeSelf ? resolved : path4.dirname(resolved); ; ancestor = path4.dirname(ancestor)) {
307
- yield* index.get(pathKey(ancestor)) ?? [];
308
- if (path4.dirname(ancestor) === ancestor) return;
309
- }
310
- }
311
-
312
- // src/snapshot/snapshot-root-transition.ts
313
- function validateOwner(guards) {
314
- guards.validateMutation?.();
315
- guards.signal?.throwIfAborted();
316
- }
317
- function rootFromSettings(root, bytes) {
318
- let settings;
319
- try {
320
- settings = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
321
- } catch {
322
- throw new Error("Invalid settings root-transition evidence.");
323
- }
324
- if (!settings || typeof settings !== "object" || Array.isArray(settings))
325
- throw new Error("Invalid settings root-transition evidence.");
326
- const value = settings.sessionDir;
327
- if (value !== void 0 && typeof value !== "string") throw new Error("Invalid settings root-transition evidence.");
328
- return path5.resolve(sessionStorageRoot(root, value ? expandSessionDir(value) : void 0));
329
- }
330
- async function beforeRoot(directory, root, entry, guards) {
331
- validateOwner(guards);
332
- if (entry.kind === "missing" && entry.beforeImage === "missing") return path5.join(root, "sessions");
333
- if (entry.kind !== "file") throw new Error("Root transition requires regular settings preimage evidence.");
334
- const backup = path5.join(directory, "before", entry.backupName);
335
- const stat = await fs3.lstat(backup);
336
- validateOwner(guards);
337
- if (!stat.isFile()) throw new Error("Invalid settings root-transition backup.");
338
- const bytes = await fs3.readFile(backup);
339
- validateOwner(guards);
340
- if (fileImage(bytes) !== entry.beforeImage) throw new Error("Changed settings root-transition backup.");
341
- return rootFromSettings(root, bytes);
342
- }
343
- async function prepareSessionRootTransition(directory, root, sessionRoot, entries, plan, guards = {}) {
344
- const settingsTarget = path5.join(root, "settings.json");
345
- const entry = entries.find((item) => item.target === settingsTarget || item.afterTarget === settingsTarget);
346
- const write = plan.writes.find((item) => item.target === settingsTarget || item.target === entry?.target);
347
- if (!entry || !entries.some((item) => item !== entry && isPathInside(sessionRoot, item.target))) return void 0;
348
- const deleted = !write && plan.deletes.includes(entry.target) && entry.afterImage === "missing";
349
- if (!write && !deleted) return void 0;
350
- const afterRoot = write ? rootFromSettings(root, write.content) : path5.join(root, "sessions");
351
- if (afterRoot !== sessionRoot) return void 0;
352
- const previous = await beforeRoot(directory, root, entry, guards);
353
- if (previous === sessionRoot) return void 0;
354
- if (write && fileImage(write.content) !== entry.afterImage) throw new Error("Changed settings transition postimage.");
355
- if (!write) return { beforeRoot: previous, settingsAfterBase64: null };
356
- validateOwner(guards);
357
- const handle = await fs3.open(path5.join(directory, "settings-after"), "wx", 384);
358
- try {
359
- validateOwner(guards);
360
- await handle.writeFile(write.content);
361
- validateOwner(guards);
362
- await handle.sync();
363
- validateOwner(guards);
364
- } finally {
365
- await handle.close();
366
- }
367
- await syncDirectory(directory);
368
- validateOwner(guards);
369
- return { beforeRoot: previous, settingsAfterFile: true };
370
- }
371
- function validateSessionRootTransition(value) {
372
- if (!value || typeof value.beforeRoot !== "string" || !path5.isAbsolute(value.beforeRoot) || path5.resolve(value.beforeRoot) !== value.beforeRoot || value.settingsAfterFile !== void 0 && value.settingsAfterFile !== true || (value.settingsAfterFile === true ? value.settingsAfterBase64 !== void 0 : value.settingsAfterBase64 !== null && (typeof value.settingsAfterBase64 !== "string" || value.settingsAfterBase64.length > 32 * 1024 * 1024 || Buffer.from(value.settingsAfterBase64, "base64").toString("base64") !== value.settingsAfterBase64)))
373
- throw new Error("Invalid session root-transition evidence.");
374
- }
375
- async function resolveTransitionSessionRoot(directory, root, sessionRoot, transition, entries, currentRoot, guards = {}) {
376
- const settingsTarget = path5.join(root, "settings.json");
377
- const entry = entries.find((item) => item.target === settingsTarget || item.afterTarget === settingsTarget);
378
- if (!entry) throw new Error("Missing settings root-transition evidence.");
379
- let after;
380
- if (transition.settingsAfterFile) {
381
- const file = path5.join(directory, "settings-after");
382
- const stat = await fs3.lstat(file);
383
- validateOwner(guards);
384
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0)
385
- throw new Error("Unsafe settings root-transition postimage.");
386
- after = await fs3.readFile(file);
387
- validateOwner(guards);
388
- } else if (transition.settingsAfterBase64 !== null)
389
- after = Buffer.from(transition.settingsAfterBase64, "base64");
390
- if ((after ? fileImage(after) : "missing") !== entry.afterImage || (after ? rootFromSettings(root, after) : path5.join(root, "sessions")) !== sessionRoot || await beforeRoot(directory, root, entry, guards) !== transition.beforeRoot)
391
- throw new Error("Inconsistent settings root-transition evidence.");
392
- if (currentRoot !== transition.beforeRoot && currentRoot !== sessionRoot)
393
- throw new Error("Transaction session root is not owned by this context; preserve evidence for review.");
394
- return sessionRoot;
395
- }
396
-
397
- // src/snapshot/snapshot-transaction.ts
398
- var JOURNAL_VERSION = 4;
399
- async function applySnapshotTransaction(plan, options = {}) {
400
- options.validateMutation?.();
401
- await recoverPendingSnapshotTransactions(options);
402
- const coalesced = await coalesceCaseReplacements(path6.resolve(agentDir()), plan);
403
- options.validateMutation?.();
404
- options.signal?.throwIfAborted();
405
- const targets = [.../* @__PURE__ */ new Set([...coalesced.plan.deletes, ...coalesced.plan.writes.map((item) => item.target)])].sort();
406
- if (targets.length > 16384)
407
- throw new Error("Snapshot transaction exceeds its target bound; review a smaller transfer.");
408
- return withTargetQueues(targets, options, async (heldKeys) => {
409
- options.signal?.throwIfAborted();
410
- if (targets.some(
411
- (target) => options.protectedTargets?.some(
412
- (protectedTarget) => mergePathIdentity(target) === mergePathIdentity(protectedTarget) || isPathInside(mergePathIdentity(target), mergePathIdentity(protectedTarget))
413
- )
414
- ))
415
- throw new Error("Snapshot transaction targets the current session; review is required.");
416
- for (const [before, after] of coalesced.replacements) {
417
- if (await caseReplacementSpelling(before, after) !== before)
418
- throw new Error("Case replacement changed before preparation; review is required.");
419
- options.validateMutation?.();
420
- options.signal?.throwIfAborted();
421
- }
422
- const originalTargets = new Map([...coalesced.replacements].map(([before, after]) => [after, before]));
423
- const expectedPreimages = new Map(
424
- [...options.expectedPreimages ?? []].map(([target, expected]) => [
425
- originalTargets.get(target) ?? target,
426
- expected
427
- ])
428
- );
429
- for (const [target, expected] of options.expectedPreimages ?? []) {
430
- if (originalTargets.has(target)) continue;
431
- const variants = coalesced.plan.deletes.filter(
432
- (candidate) => candidate !== target && path6.dirname(candidate) === path6.dirname(target) && mergePathIdentity(candidate) === mergePathIdentity(target)
433
- );
434
- if (variants.length > 1) throw new Error("Ambiguous reviewed file preimage spellings; review required.");
435
- const original = variants[0];
436
- if (!original) continue;
437
- const destination = await image(target);
438
- options.validateMutation?.();
439
- options.signal?.throwIfAborted();
440
- if (destination !== "missing" && destination !== expected)
441
- throw new Error("Reviewed destination preimage changed before apply.");
442
- expectedPreimages.set(original, expected);
443
- expectedPreimages.set(target, destination);
444
- }
445
- for (const [target, expected] of expectedPreimages) {
446
- const current = await image(target);
447
- options.validateMutation?.();
448
- options.signal?.throwIfAborted();
449
- if (current !== expected)
450
- throw new Error("Reviewed file preimage changed before apply; snapshot installation refused.");
451
- }
452
- const transaction = await prepareTransaction(
453
- coalesced.plan,
454
- targets,
455
- { ...options, expectedPreimages },
456
- coalesced.replacements
457
- );
458
- const entriesByTarget = new Map(
459
- transaction.journal.entries.flatMap((entry) => [
460
- [entry.target, entry],
461
- ...entry.afterTarget ? [[entry.afterTarget, entry]] : []
462
- ])
463
- );
464
- const changesQueueKey = transaction.journal.entries.some(
465
- (entry) => !heldKeys.has(entry.target) || entry.afterTarget && !heldKeys.has(entry.afterTarget)
466
- );
467
- try {
468
- for (const target of transaction.deletes.sort((a, b) => a.length - b.length)) {
469
- options.signal?.throwIfAborted();
470
- const entry = entriesByTarget.get(target);
471
- if (!entry) throw new Error("Unowned transaction target.");
472
- await removeOwnedTarget(transaction.directory, entry, transaction.journal, options);
473
- await syncDirectory(path6.dirname(target));
474
- }
475
- await withMissingTargetQueues(
476
- transaction.journal.entries.filter((entry) => entry.removalPending).flatMap((entry) => [entry.target, ...entry.afterTarget ? [entry.afterTarget] : []]),
477
- heldKeys,
478
- options,
479
- async () => {
480
- await retireRemovalIntent(
481
- transaction.directory,
482
- transaction.journal,
483
- transaction.journal.entries.filter(
484
- (entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0)
485
- ),
486
- options
487
- );
488
- const uninstalledWrites = new Set(transaction.deletedWrites);
489
- for (const item of plan.writes) {
490
- options.signal?.throwIfAborted();
491
- const entry = entriesByTarget.get(item.target);
492
- if (!entry) throw new Error("Unowned transaction target.");
493
- const deletedByThisCall = uninstalledWrites.delete(entry.target);
494
- await verifyTarget(transaction.directory, entry, transaction.journal, deletedByThisCall);
495
- options.validateMutation?.();
496
- options.signal?.throwIfAborted();
497
- await fs4.mkdir(path6.dirname(item.target), { recursive: true });
498
- options.validateMutation?.();
499
- options.signal?.throwIfAborted();
500
- const temp = path6.join(path6.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
501
- try {
502
- let mode = 384;
503
- try {
504
- const stat = await fs4.lstat(item.target);
505
- if (stat.isFile()) mode = stat.mode & 511;
506
- } catch (error) {
507
- if (error.code !== "ENOENT") throw error;
508
- }
509
- const handle = await fs4.open(temp, "wx", mode);
510
- try {
511
- await handle.writeFile(item.content);
512
- await handle.sync();
513
- } finally {
514
- await handle.close();
515
- }
516
- await verifyTarget(transaction.directory, entry, transaction.journal, deletedByThisCall);
517
- options.signal?.throwIfAborted();
518
- options.validateMutation?.();
519
- await fs4.rename(temp, item.target);
520
- await syncDirectory(path6.dirname(item.target));
521
- } finally {
522
- await fs4.rm(temp, { force: true });
523
- }
524
- }
525
- options.validateMutation?.();
526
- options.signal?.throwIfAborted();
527
- await syncMutationParents(
528
- targets,
529
- [transaction.journal.root, ...transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : []],
530
- options
531
- );
532
- options.validateMutation?.();
533
- options.signal?.throwIfAborted();
534
- }
535
- );
536
- } catch (error) {
537
- if (options.signal?.aborted)
538
- throw new Error("Snapshot apply cancelled; guarded transaction evidence retained for review.");
539
- if (changesQueueKey)
540
- throw new Error("Snapshot apply failed; guarded transaction evidence retained for review.", {
541
- cause: error
542
- });
543
- try {
544
- await restoreTransaction(transaction.directory, transaction.journal, options, heldKeys);
545
- } catch (recoveryError) {
546
- throw new AggregateError(
547
- [error, recoveryError],
548
- "Snapshot apply failed and guarded recovery requires review. Transaction and backup retained; newer bytes were not restored over."
549
- );
550
- }
551
- throw error;
552
- }
553
- await completeTransaction(transaction.directory, transaction.journal);
554
- });
555
- }
556
- async function recoverSnapshotTransactionsOnStartup(options = {}) {
557
- if (!(await pendingTransactionEntries()).some((entry) => entry.isDirectory())) return;
558
- options.validateMutation?.();
559
- options.signal?.throwIfAborted();
560
- await withLock(
561
- "recovery",
562
- () => recoverPendingSnapshotTransactions({ ...options, resolveConfiguredSessionDir: true }),
563
- {
564
- reclaimStale: true
565
- }
566
- );
567
- }
568
- async function recoverPendingSnapshotTransactions(options = {}) {
569
- for (const entry of (await pendingTransactionEntries()).sort((a, b) => a.name.localeCompare(b.name))) {
570
- if (!entry.isDirectory()) continue;
571
- const directory = path6.join(transactionRoot(), entry.name);
572
- let journal;
573
- try {
574
- const file = path6.join(directory, "journal.json");
575
- const stat = await fs4.lstat(file);
576
- if (!stat.isFile() || stat.size > 32 * 1024 * 1024) throw new Error("Invalid journal file.");
577
- journal = JSON.parse(await fs4.readFile(file, "utf8"));
578
- } catch (error) {
579
- if (error.code === "ENOENT") continue;
580
- throw new Error("Cannot recover malformed pi-sync transaction; preserve private evidence for review.");
581
- }
582
- let sessionDir = options.sessionDir;
583
- if (sessionDir === void 0 && options.resolveConfiguredSessionDir && !journal.completed && transactionHasSessionTargets(journal)) {
584
- sessionDir = await configuredSessionDir();
585
- }
586
- options.validateMutation?.();
587
- options.signal?.throwIfAborted();
588
- if (journal.sessionRootTransition && !journal.completed) {
589
- validateJournal(directory, journal, journal.sessionRoot);
590
- sessionDir = await resolveTransitionSessionRoot(
591
- directory,
592
- journal.root,
593
- journal.sessionRoot,
594
- journal.sessionRootTransition,
595
- journal.entries,
596
- path6.resolve(sessionStorageRoot(journal.root, sessionDir)),
597
- options
598
- );
599
- options.validateMutation?.();
600
- options.signal?.throwIfAborted();
601
- }
602
- validateJournal(directory, journal, sessionDir);
603
- if (journal.completed) {
604
- await removeTransaction(directory);
605
- continue;
606
- }
607
- await withTargetQueues(
608
- journal.entries.map((entry2) => entry2.target).sort(),
609
- options,
610
- (heldKeys) => restoreTransaction(directory, journal, { ...options, sessionDir }, heldKeys)
611
- );
612
- }
613
- }
614
- async function prepareTransaction(plan, targets, options, replacements = /* @__PURE__ */ new Map()) {
615
- const { sessionDir } = options;
616
- const root = path6.resolve(agentDir());
617
- const sessionRoot = sessionDir ? path6.resolve(sessionStorageRoot(root, sessionDir)) : void 0;
618
- const indexed = indexTransactionPlan(plan, targets);
619
- const directory = path6.join(transactionRoot(), randomUUID());
620
- const backupDirectory = path6.join(directory, "before");
621
- await fs4.mkdir(backupDirectory, { recursive: true, mode: 448 });
622
- const entries = [];
623
- for (const [index, target] of targets.entries()) {
624
- options.signal?.throwIfAborted();
625
- options.validateMutation?.();
626
- assertAllowedTarget(root, sessionRoot, target);
627
- await assertSafeParents(root, sessionRoot, target);
628
- const entry = { target, backupName: `${index}`, kind: "missing" };
629
- if (replacements.has(target)) entry.afterTarget = replacements.get(target);
630
- const backup = path6.join(backupDirectory, entry.backupName);
631
- try {
632
- const stat = await fs4.lstat(target);
633
- if (stat.isSymbolicLink()) {
634
- entry.kind = "symlink";
635
- entry.linkTarget = await fs4.readlink(target);
636
- } else if (stat.isDirectory()) {
637
- entry.kind = "directory";
638
- await fs4.cp(target, backup, {
639
- recursive: true,
640
- dereference: false,
641
- verbatimSymlinks: true,
642
- preserveTimestamps: true,
643
- filter: () => {
644
- options.signal?.throwIfAborted();
645
- options.validateMutation?.();
646
- return true;
647
- }
648
- });
649
- } else if (stat.isFile()) {
650
- entry.kind = "file";
651
- await fs4.copyFile(target, backup);
652
- await fs4.chmod(backup, stat.mode);
653
- } else throw new Error("Unsupported existing snapshot target.");
654
- } catch (error) {
655
- const code = error.code;
656
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
657
- }
658
- entry.beforeImage = entry.kind === "symlink" ? `symlink:${entry.linkTarget}` : entry.kind === "missing" ? "missing" : await image(backup, true);
659
- options.validateMutation?.();
660
- options.signal?.throwIfAborted();
661
- const expected = options.expectedPreimages?.get(target);
662
- if (expected !== void 0 && entry.beforeImage !== expected)
663
- throw new Error("Reviewed file preimage changed during backup; private preparation evidence retained.");
664
- if (entry.afterTarget) {
665
- if (entry.kind !== "file" || await caseReplacementSpelling(target, entry.afterTarget) !== target)
666
- throw new Error("Case replacement preimage changed during backup; evidence retained for review.");
667
- options.validateMutation?.();
668
- options.signal?.throwIfAborted();
669
- }
670
- entry.afterImage = indexed.writeImages.get(target) ?? "missing";
671
- entry.postFiles = indexed.postFiles.get(target) ?? [];
672
- entries.push(entry);
673
- }
674
- await syncDirectory(backupDirectory);
675
- const effectiveRoot = sessionRoot ?? path6.join(root, "sessions");
676
- const sessionRootTransition = await prepareSessionRootTransition(
677
- directory,
678
- root,
679
- effectiveRoot,
680
- entries,
681
- plan,
682
- options
683
- );
684
- const journal = {
685
- version: sessionRootTransition ? 7 : replacements.size ? 5 : JOURNAL_VERSION,
686
- root,
687
- sessionRoot: sessionRootTransition ? effectiveRoot : sessionRoot,
688
- sessionRootTransition,
689
- entries
690
- };
691
- options.signal?.throwIfAborted();
692
- options.validateMutation?.();
693
- await writeJson(path6.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
694
- await syncDirectory(transactionRoot());
695
- await syncDirectory(stateDir());
696
- await syncDirectory(path6.dirname(stateDir()));
697
- return { directory, journal, deletes: indexed.deletes, deletedWrites: indexed.deletedWrites };
698
- }
699
- async function restoreTransaction(directory, journal, options, heldKeys) {
700
- validateJournal(directory, journal, options.sessionDir);
701
- const missingSpellings = [];
702
- for (const entry of journal.entries) {
703
- if (!entry.afterTarget) continue;
704
- options.validateMutation?.();
705
- options.signal?.throwIfAborted();
706
- const spelling = await caseReplacementSpelling(entry.target, entry.afterTarget);
707
- options.validateMutation?.();
708
- options.signal?.throwIfAborted();
709
- if (spelling === void 0) missingSpellings.push(entry.target, entry.afterTarget);
710
- }
711
- return withMissingTargetQueues(
712
- missingSpellings,
713
- heldKeys,
714
- options,
715
- (reservedKeys) => restoreQueuedTransaction(directory, journal, options, reservedKeys)
716
- );
717
- }
718
- async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
719
- validateJournal(directory, journal, options.sessionDir);
720
- options.validateMutation?.();
721
- options.signal?.throwIfAborted();
722
- for (const entry of journal.entries) {
723
- if (options.protectedTargets?.some(
724
- (target) => mergePathIdentity(target) === mergePathIdentity(entry.target) || isPathInside(mergePathIdentity(entry.target), mergePathIdentity(target))
725
- ))
726
- throw new Error(
727
- "Pending transaction touches the current session; resume a different session before guarded recovery."
728
- );
729
- await verifyTarget(directory, entry, journal);
730
- }
731
- for (const entry of journal.entries) {
732
- if (!entry.recoveryStaged) continue;
733
- options.validateMutation?.();
734
- options.signal?.throwIfAborted();
735
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
736
- options.validateMutation?.();
737
- options.signal?.throwIfAborted();
738
- await fs4.rm(recoveryStagePath(directory, entry), { recursive: true, force: true });
739
- options.validateMutation?.();
740
- options.signal?.throwIfAborted();
741
- }
742
- for (const entry of [...journal.entries].sort((a, b) => a.target.length - b.target.length)) {
743
- const current = await verifyTarget(directory, entry, journal);
744
- const before = await beforeImage(directory, entry);
745
- const spellingMatches = async () => !entry.afterTarget || await caseReplacementSpelling(entry.target, entry.afterTarget) === entry.target;
746
- if (current === before && await spellingMatches()) continue;
747
- options.signal?.throwIfAborted();
748
- options.validateMutation?.();
749
- if (entry.kind === "file") {
750
- const temporary2 = await prepareRecoveryStage(directory, journal, entry, options);
751
- try {
752
- await fs4.mkdir(path6.dirname(entry.target), { recursive: true });
753
- await fs4.copyFile(path6.join(directory, "before", entry.backupName), temporary2);
754
- const handle = await fs4.open(temporary2, process.platform === "win32" ? "r+" : "r");
755
- try {
756
- await handle.sync();
757
- } finally {
758
- await handle.close();
759
- }
760
- const verified = await verifyTarget(directory, entry, journal);
761
- options.validateMutation?.();
762
- options.signal?.throwIfAborted();
763
- if (verified === before && await spellingMatches()) continue;
764
- const needsCaseQueue = entry.afterTarget !== void 0 && await caseReplacementSpelling(entry.target, entry.afterTarget) === entry.afterTarget;
765
- if (needsCaseQueue) {
766
- await removeOwnedTarget(directory, entry, journal, options);
767
- } else if (verified.startsWith("directory:") && !await removeOwnedTarget(directory, entry, journal, options, before))
768
- continue;
769
- await withMissingTargetQueues(
770
- entry.afterTarget && (needsCaseQueue || verified === "missing") ? [entry.target, entry.afterTarget] : verified.startsWith("directory:") ? [entry.target] : [],
771
- heldKeys,
772
- options,
773
- async () => {
774
- const atRename = await verifyTarget(directory, entry, journal);
775
- options.validateMutation?.();
776
- options.signal?.throwIfAborted();
777
- if (atRename === before && await spellingMatches()) return;
778
- await retireRestorationIntent(directory, journal, entry, options);
779
- const atInstall = await verifyTarget(directory, entry, journal, atRename === "missing");
780
- options.validateMutation?.();
781
- options.signal?.throwIfAborted();
782
- if (atInstall === before && await spellingMatches()) return;
783
- await fs4.rename(temporary2, entry.target);
784
- await syncDirectory(path6.dirname(entry.target));
785
- }
786
- );
787
- } finally {
788
- await fs4.rm(temporary2, { force: true });
789
- }
790
- continue;
791
- }
792
- if (entry.kind === "missing") {
793
- await removeOwnedTarget(directory, entry, journal, options, before);
794
- continue;
795
- }
796
- const temporary = await prepareRecoveryStage(directory, journal, entry, options);
797
- try {
798
- await fs4.mkdir(path6.dirname(entry.target), { recursive: true });
799
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
800
- if (entry.kind === "directory") {
801
- await fs4.cp(path6.join(directory, "before", entry.backupName), temporary, {
802
- recursive: true,
803
- dereference: false,
804
- verbatimSymlinks: true,
805
- preserveTimestamps: true,
806
- filter: () => {
807
- options.validateMutation?.();
808
- options.signal?.throwIfAborted();
809
- return true;
810
- }
811
- });
812
- } else if (entry.linkTarget !== void 0) await fs4.symlink(entry.linkTarget, temporary);
813
- if (await image(temporary, true) !== before)
814
- throw new Error("Staged recovery image differs from the backup; evidence retained.");
815
- options.validateMutation?.();
816
- options.signal?.throwIfAborted();
817
- if (!await removeOwnedTarget(directory, entry, journal, options, before)) continue;
818
- await withMissingTargetQueues([entry.target], heldKeys, options, async () => {
819
- const atRename = await verifyTarget(directory, entry, journal);
820
- options.validateMutation?.();
821
- options.signal?.throwIfAborted();
822
- if (atRename === before) return;
823
- await retireRestorationIntent(directory, journal, entry, options);
824
- const atInstall = await verifyTarget(directory, entry, journal, atRename === "missing");
825
- options.validateMutation?.();
826
- options.signal?.throwIfAborted();
827
- if (atInstall === before) return;
828
- await fs4.rename(temporary, entry.target);
829
- await syncDirectory(path6.dirname(entry.target));
830
- });
831
- } finally {
832
- await fs4.rm(temporary, { recursive: true, force: true });
833
- }
834
- }
835
- await syncMutationParents(
836
- journal.entries.map((entry) => entry.target),
837
- [journal.root, ...journal.sessionRoot ? [journal.sessionRoot] : []],
838
- options
839
- );
840
- options.validateMutation?.();
841
- options.signal?.throwIfAborted();
842
- await completeTransaction(directory, journal);
843
- }
844
- async function verifyTarget(directory, entry, journal, deletedByThisCall = false) {
845
- await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
846
- const before = await beforeImage(directory, entry);
847
- if (journal.version >= 2 && before !== entry.beforeImage)
848
- throw new Error("Transaction backup changed; preserve evidence for review.");
849
- if (entry.afterTarget) await caseReplacementSpelling(entry.target, entry.afterTarget);
850
- const current = await image(entry.target);
851
- if (current === before) return current;
852
- if (current === "missing") {
853
- if (deletedByThisCall || journal.version >= 4 && entry.removalPending && !entry.replacementStarted)
854
- return current;
855
- } else if (journal.version >= 2 && (current === entry.afterImage || await ownedPostTree(
856
- entry.target,
857
- entry.postFiles ?? [],
858
- journal.version < 4 || entry.replacementStarted === true || !entry.removalPending
859
- )))
860
- return current;
861
- throw new Error(
862
- "Transaction target has unrecognized or newer bytes; automatic rollback refused. Preserve the transaction and review its backup with Pi closed."
863
- );
864
- }
865
- async function removeOwnedTarget(directory, entry, journal, options, restoringBefore) {
866
- const current = await verifyTarget(directory, entry, journal);
867
- options.validateMutation?.();
868
- options.signal?.throwIfAborted();
869
- if (restoringBefore !== void 0 && current === restoringBefore) return false;
870
- upgradeRemovalEvidence(journal);
871
- for (const affected of journal.entries) {
872
- if (affected.target === entry.target || isStrictlyInside(entry.target, affected.target)) {
873
- affected.removalPending = true;
874
- affected.replacementStarted = false;
875
- }
876
- }
877
- await writeJson(path6.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
878
- const verified = await verifyTarget(directory, entry, journal);
879
- options.validateMutation?.();
880
- options.signal?.throwIfAborted();
881
- if (restoringBefore !== void 0 && verified === restoringBefore) return false;
882
- await fs4.rm(entry.target, { recursive: true, force: true });
883
- await syncDirectory(path6.dirname(entry.target));
884
- return true;
885
- }
886
- function upgradeRemovalEvidence(journal) {
887
- if (journal.version < JOURNAL_VERSION) {
888
- for (const entry of journal.entries) entry.removalPending = false;
889
- journal.version = JOURNAL_VERSION;
890
- }
891
- }
892
- async function retireRemovalIntent(directory, journal, entries, options) {
893
- options.validateMutation?.();
894
- options.signal?.throwIfAborted();
895
- if (!entries.length) return;
896
- upgradeRemovalEvidence(journal);
897
- for (const entry of entries) {
898
- entry.removalPending = false;
899
- entry.replacementStarted = true;
900
- }
901
- await writeJson(path6.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
902
- options.validateMutation?.();
903
- options.signal?.throwIfAborted();
904
- }
905
- async function retireRestorationIntent(directory, journal, entry, options) {
906
- for (const child of journal.entries) {
907
- if (isStrictlyInside(entry.target, child.target)) {
908
- child.removalPending = false;
909
- child.replacementStarted = false;
910
- }
911
- }
912
- await retireRemovalIntent(directory, journal, [entry], options);
913
- }
914
- function recoveryStagePath(directory, entry) {
915
- const token = createHash2("sha256").update(directory).update("\\0").update(entry.backupName).digest("hex");
916
- return path6.join(
917
- path6.dirname(entry.target),
918
- `.pi-sync.json.${token}.${entry.kind === "file" ? "restore" : "restore-tree"}`
919
- );
920
- }
921
- async function prepareRecoveryStage(directory, journal, entry, options) {
922
- const temporary = recoveryStagePath(directory, entry);
923
- if (!entry.recoveryStaged) {
924
- try {
925
- await fs4.lstat(temporary);
926
- throw new Error("Unowned recovery staging path; preserve evidence for review.");
927
- } catch (error) {
928
- if (error.code !== "ENOENT") throw error;
929
- }
930
- options.validateMutation?.();
931
- options.signal?.throwIfAborted();
932
- entry.recoveryStaged = true;
933
- await writeJson(path6.join(directory, "journal.json"), journal, { maxBytes: 32 * 1024 * 1024 });
934
- options.validateMutation?.();
935
- options.signal?.throwIfAborted();
936
- }
937
- return temporary;
938
- }
939
- async function beforeImage(directory, entry) {
940
- if (entry.kind === "missing") return "missing";
941
- if (entry.kind === "symlink") return `symlink:${entry.linkTarget}`;
942
- const value = await image(path6.join(directory, "before", entry.backupName));
943
- if (value === "missing") throw new Error("Transaction backup is missing; preserve evidence for review.");
944
- return value;
945
- }
946
- async function image(target, durable = false) {
947
- let stat;
948
- try {
949
- stat = await fs4.lstat(target);
950
- } catch (error) {
951
- const code = error.code;
952
- if (code === "ENOENT" || code === "ENOTDIR") return "missing";
953
- throw error;
954
- }
955
- if (stat.isSymbolicLink()) return `symlink:${await fs4.readlink(target)}`;
956
- if (stat.isFile()) {
957
- const content = await fs4.readFile(target);
958
- if (durable) {
959
- const handle = await fs4.open(target, process.platform === "win32" ? "r+" : "r");
960
- try {
961
- await handle.sync();
962
- } finally {
963
- await handle.close();
964
- }
965
- }
966
- return fileImage(content);
967
- }
968
- if (!stat.isDirectory()) throw new Error("Unsupported transaction image.");
969
- const entries = [];
970
- for (const name of (await fs4.readdir(target)).sort())
971
- entries.push([name, await image(path6.join(target, name), durable)]);
972
- if (durable) await syncDirectory(target);
973
- return `directory:${createHash2("sha256").update(JSON.stringify(entries)).digest("hex")}`;
974
- }
975
- async function ownedPostTree(target, files, requireComplete) {
976
- if (!files.length) return false;
977
- const expected = new Map(files.map((file) => [mergePathIdentity(file.relative), file.image]));
978
- const prefixes = /* @__PURE__ */ new Set();
979
- for (const relative of expected.keys()) {
980
- for (let parent = path6.dirname(relative); parent !== "." && parent !== path6.dirname(parent); parent = path6.dirname(parent))
981
- prefixes.add(parent);
982
- }
983
- const seen = /* @__PURE__ */ new Set();
984
- async function visit(directory) {
985
- let stat;
986
- try {
987
- stat = await fs4.lstat(directory);
988
- } catch {
989
- return false;
990
- }
991
- if (!stat.isDirectory() || stat.isSymbolicLink()) return false;
992
- for (const name of await fs4.readdir(directory)) {
993
- const child = path6.join(directory, name);
994
- const relative = mergePathIdentity(path6.relative(target, child));
995
- const stat2 = await fs4.lstat(child);
996
- if (stat2.isDirectory() && !stat2.isSymbolicLink()) {
997
- if (!prefixes.has(relative) || !await visit(child)) return false;
998
- } else {
999
- if (expected.get(relative) !== await image(child)) return false;
1000
- seen.add(relative);
1001
- }
1002
- }
1003
- return true;
1004
- }
1005
- return await visit(target) && (!requireComplete || [...expected.keys()].every((key) => seen.has(key)));
1006
- }
1007
- function validateJournal(directory, journal, sessionDir) {
1008
- if (![1, 2, 3, 4, 5, 6, 7].includes(journal.version) || !Array.isArray(journal.entries) || journal.entries.length > 16384)
1009
- throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
1010
- if (journal.completed !== void 0 && (![6, 7].includes(journal.version) || journal.completed !== true))
1011
- throw new Error("Invalid transaction completion evidence.");
1012
- const root = path6.resolve(agentDir());
1013
- if (typeof journal.root !== "string" || path6.resolve(journal.root) !== root)
1014
- throw new Error("Transaction root no longer matches the Pi agent directory.");
1015
- if (journal.sessionRootTransition !== void 0) {
1016
- if (journal.version !== 7 || typeof journal.sessionRoot !== "string")
1017
- throw new Error("Invalid session root-transition version.");
1018
- validateSessionRootTransition(journal.sessionRootTransition);
1019
- } else if (journal.version === 7) throw new Error("Missing session root-transition evidence.");
1020
- const trustedSessionRoot = sessionDir ? path6.resolve(sessionStorageRoot(root, sessionDir)) : path6.join(root, "sessions");
1021
- if (journal.sessionRoot !== void 0 && (typeof journal.sessionRoot !== "string" || !path6.isAbsolute(journal.sessionRoot) || path6.resolve(journal.sessionRoot) !== journal.sessionRoot || !journal.completed && transactionHasSessionTargets(journal) && journal.sessionRoot !== trustedSessionRoot))
1022
- throw new Error("Transaction session root is not owned by this context; preserve evidence for review.");
1023
- for (const entry of journal.entries) {
1024
- if (!entry || typeof entry.target !== "string" || !path6.isAbsolute(entry.target) || path6.resolve(entry.target) !== entry.target || typeof entry.backupName !== "string" || !/^\d+$/u.test(entry.backupName) || !["missing", "file", "directory", "symlink"].includes(entry.kind))
1025
- throw new Error("Invalid pi-sync transaction entry.");
1026
- assertWithinRoot(directory, path6.join(directory, "before", entry.backupName));
1027
- assertAllowedTarget(root, journal.sessionRoot, entry.target);
1028
- if (entry.afterTarget !== void 0 && (![5, 6, 7].includes(journal.version) || typeof entry.afterTarget !== "string" || !isCaseReplacement(root, entry.target, entry.afterTarget) || path6.resolve(entry.afterTarget) !== entry.afterTarget || entry.kind !== "file"))
1029
- throw new Error("Invalid transaction case replacement evidence.");
1030
- if (entry.afterTarget) assertAllowedTarget(root, journal.sessionRoot, entry.afterTarget);
1031
- if (journal.version >= 2 && ((entry.beforeImage === void 0 ? !journal.completed : typeof entry.beforeImage !== "string") || (entry.afterImage === void 0 ? !journal.completed : typeof entry.afterImage !== "string") || (entry.postFiles === void 0 ? !journal.completed : !Array.isArray(entry.postFiles))))
1032
- throw new Error("Invalid transaction postimage evidence.");
1033
- if (entry.recoveryStaged !== void 0 && typeof entry.recoveryStaged !== "boolean")
1034
- throw new Error("Invalid recovery staging evidence.");
1035
- if (entry.removalPending !== void 0 && (journal.version < 3 || typeof entry.removalPending !== "boolean"))
1036
- throw new Error("Invalid transaction removal evidence.");
1037
- if (entry.replacementStarted !== void 0 && (journal.version < 4 || typeof entry.replacementStarted !== "boolean"))
1038
- throw new Error("Invalid transaction replacement evidence.");
1039
- if (entry.removalPending && entry.replacementStarted)
1040
- throw new Error("Conflicting transaction replacement evidence.");
1041
- for (const file of entry.postFiles ?? []) {
1042
- if (typeof file.relative !== "string" || typeof file.image !== "string" || !isStrictlyInside(entry.target, path6.resolve(entry.target, file.relative)))
1043
- throw new Error("Invalid transaction subtree evidence.");
1044
- }
1045
- }
1046
- }
1047
- function transactionHasSessionTargets(journal) {
1048
- const root = path6.resolve(agentDir());
1049
- return Array.isArray(journal.entries) && journal.entries.some(
1050
- (entry) => typeof entry?.target === "string" && (!isPathInside(root, entry.target) || isPathInside(path6.join(root, "sessions"), entry.target) || typeof journal.sessionRoot === "string" && isPathInside(journal.sessionRoot, entry.target))
1051
- );
1052
- }
1053
- function isStrictlyInside(root, target) {
1054
- return path6.relative(path6.resolve(root), path6.resolve(target)) !== "" && isPathInside(root, target);
1055
- }
1056
- function assertAllowedTarget(root, sessionRoot, target) {
1057
- const resolved = path6.resolve(target);
1058
- if (isStrictlyInside(root, resolved)) {
1059
- if (isDeniedPath(path6.relative(root, resolved))) throw new Error("Transaction targets denied private storage.");
1060
- assertWithinRoot(root, resolved);
1061
- return;
1062
- }
1063
- if (sessionRoot && isStrictlyInside(sessionRoot, resolved)) {
1064
- if (isDeniedPath(`sessions/${path6.relative(sessionRoot, resolved)}`))
1065
- throw new Error("Transaction targets denied session storage.");
1066
- assertWithinRoot(sessionRoot, resolved);
1067
- return;
1068
- }
1069
- throw new Error("Transaction target is outside configured roots.");
1070
- }
1071
- async function assertSafeParents(root, sessionRoot, target) {
1072
- assertAllowedTarget(root, sessionRoot, target);
1073
- const boundary = isPathInside(root, target) ? root : sessionRoot;
1074
- for (let parent = path6.dirname(target); boundary && mergePathIdentity(parent) !== mergePathIdentity(boundary); parent = path6.dirname(parent)) {
1075
- if (path6.dirname(parent) === parent) throw new Error("Transaction parent did not reach its owned boundary.");
1076
- try {
1077
- const stat = await fs4.lstat(parent);
1078
- if (!stat.isDirectory() && !stat.isFile() || stat.isSymbolicLink())
1079
- throw new Error("Unsafe transaction parent.");
1080
- } catch (error) {
1081
- const code = error.code;
1082
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
1083
- }
1084
- }
1085
- }
1086
- async function completeTransaction(directory, journal) {
1087
- await writeJson(
1088
- path6.join(directory, "journal.json"),
1089
- { ...journal, version: journal.sessionRootTransition ? 7 : 6, completed: true },
1090
- {
1091
- maxBytes: 32 * 1024 * 1024
1092
- }
1093
- );
1094
- await removeTransaction(directory);
1095
- }
1096
- async function removeTransaction(directory) {
1097
- await fs4.rm(directory, { recursive: true, force: true });
1098
- await syncDirectory(transactionRoot()).catch(() => {
1099
- });
1100
- }
1101
-
1102
- export {
1103
- syncMutationParents,
1104
- assertCanonicalMutationTargets,
1105
- applySnapshotTransaction,
1106
- recoverSnapshotTransactionsOnStartup,
1107
- recoverPendingSnapshotTransactions
1108
- };
1109
- //# sourceMappingURL=chunk-7A35ZAVO.ts.map