@narumitw/pi-sync 0.59.0 → 0.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +25 -17
  3. package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
  4. package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
  5. package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
  6. package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
  7. package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-6LHIRS5R.ts} +30 -47
  8. package/dist/chunks/chunk-6LHIRS5R.ts.map +7 -0
  9. package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
  10. package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
  11. package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
  12. package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
  13. package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
  14. package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
  15. package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
  16. package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
  17. package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
  18. package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
  19. package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
  20. package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
  21. package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
  22. package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
  23. package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
  24. package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
  25. package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
  26. package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
  27. package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
  28. package/dist/chunks/chunk-JZKCOM62.ts +26 -0
  29. package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
  30. package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
  31. package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
  32. package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
  33. package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
  34. package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
  35. package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
  36. package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
  37. package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
  38. package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
  39. package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
  40. package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
  41. package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
  42. package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
  43. package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
  44. package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
  45. package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-FO4XBBHF.ts} +80 -86
  46. package/dist/chunks/command-handler-FO4XBBHF.ts.map +7 -0
  47. package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
  48. package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
  49. package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
  50. package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
  51. package/dist/chunks/continuous-storage-SQBAXACF.ts +27 -0
  52. package/dist/chunks/continuous-storage-SQBAXACF.ts.map +7 -0
  53. package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
  54. package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
  55. package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
  56. package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-AY5ZU6B4.ts} +180 -164
  57. package/dist/chunks/manager-ui-AY5ZU6B4.ts.map +7 -0
  58. package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
  59. package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
  60. package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
  61. package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
  62. package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
  63. package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
  64. package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
  65. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
  66. package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
  67. package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
  68. package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
  69. package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
  70. package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
  71. package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
  72. package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
  73. package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
  74. package/dist/index.ts +269 -313
  75. package/dist/index.ts.map +4 -4
  76. package/docs/daemon-migration.md +93 -0
  77. package/docs/tui-contract.md +12 -0
  78. package/package.json +3 -6
  79. package/skills/configure-pi-sync/SKILL.md +1 -1
  80. package/skills/configure-pi-sync/references/configuration.md +19 -6
  81. package/src/backends/backend-factory.ts +2 -23
  82. package/src/backends/backend-identity.ts +5 -40
  83. package/src/backends/backend-types.ts +1 -81
  84. package/src/backends/git/git-backend.ts +6 -784
  85. package/src/backends/git/git-config.ts +8 -130
  86. package/src/backends/git/git-runner.ts +7 -255
  87. package/src/backends/git/git-storage.ts +14 -293
  88. package/src/backends/s3/s3-backend.ts +11 -523
  89. package/src/backends/s3/s3-client.ts +2 -399
  90. package/src/backends/s3/s3-conditions.ts +2 -67
  91. package/src/backends/snapshot-pointer.ts +2 -27
  92. package/src/backends/sync-backend.ts +6 -101
  93. package/src/backends/webdav/webdav-backend.ts +10 -622
  94. package/src/backends/webdav/webdav-client.ts +6 -370
  95. package/src/backends/webdav/webdav-config.ts +8 -82
  96. package/src/commands/command-execution.ts +40 -36
  97. package/src/commands/command.ts +23 -1
  98. package/src/daemon/apply-gate.ts +146 -0
  99. package/src/daemon/pi-client.ts +591 -0
  100. package/src/daemon/recovery.ts +103 -0
  101. package/src/paths.ts +12 -83
  102. package/src/settings/config-errors.ts +2 -6
  103. package/src/settings/config-file.ts +19 -693
  104. package/src/settings/config.ts +16 -263
  105. package/src/settings/settings-management.ts +11 -254
  106. package/src/settings/settings-store.ts +10 -48
  107. package/src/settings/settings-types.ts +1 -157
  108. package/src/settings/settings-validation.ts +17 -435
  109. package/src/snapshot/session-paths.ts +11 -111
  110. package/src/snapshot/snapshot-apply.ts +9 -322
  111. package/src/snapshot/snapshot-case-replacement.ts +6 -80
  112. package/src/snapshot/snapshot-codec.ts +2 -59
  113. package/src/snapshot/snapshot-exclude-safety.ts +2 -44
  114. package/src/snapshot/snapshot-mutation-queues.ts +6 -142
  115. package/src/snapshot/snapshot-paths.ts +2 -11
  116. package/src/snapshot/snapshot-root-transition.ts +6 -154
  117. package/src/snapshot/snapshot-transaction-directory.ts +5 -16
  118. package/src/snapshot/snapshot-transaction-plan.ts +2 -72
  119. package/src/snapshot/snapshot-transaction.ts +6 -946
  120. package/src/snapshot/snapshot-types.ts +1 -43
  121. package/src/snapshot/snapshot.ts +19 -447
  122. package/src/state/json-file.ts +2 -47
  123. package/src/state/lock-policy.ts +2 -2
  124. package/src/state/lock.ts +10 -292
  125. package/src/state/lockfile-fs.ts +2 -25
  126. package/src/state/merge-baseline-store.ts +8 -208
  127. package/src/state/mutation-directory-sync.ts +2 -34
  128. package/src/state/operation-availability.ts +7 -59
  129. package/src/state/state-directory.ts +8 -243
  130. package/src/state/state-types.ts +1 -25
  131. package/src/state/sync-state-store.ts +11 -75
  132. package/src/sync/agent-candidate.ts +7 -256
  133. package/src/sync/agent-plan.ts +2 -107
  134. package/src/sync/agent-policy.ts +10 -13
  135. package/src/sync/agent-refusal-retry.ts +2 -54
  136. package/src/sync/agent-request.ts +2 -19
  137. package/src/sync/agent-runner.ts +2 -191
  138. package/src/sync/agent-store.ts +7 -182
  139. package/src/sync/agent-sync.ts +2 -141
  140. package/src/sync/apply-review.ts +2 -63
  141. package/src/sync/automatic-sync.ts +55 -111
  142. package/src/sync/conflict-artifact-ownership.ts +2 -63
  143. package/src/sync/conflict-artifacts.ts +8 -195
  144. package/src/sync/conflict-groups.ts +2 -68
  145. package/src/sync/conflict-preview.ts +2 -56
  146. package/src/sync/conflict-resolution.ts +2 -93
  147. package/src/sync/conflict-retention.ts +2 -72
  148. package/src/sync/conflict-review.ts +3 -92
  149. package/src/sync/content-conflicts.ts +2 -73
  150. package/src/sync/continuous-errors.ts +7 -85
  151. package/src/sync/continuous-lease.ts +2 -216
  152. package/src/sync/continuous-record.ts +10 -261
  153. package/src/sync/continuous-storage.ts +12 -64
  154. package/src/sync/continuous-sync.ts +2 -563
  155. package/src/sync/continuous-watch.ts +2 -61
  156. package/src/sync/exclude-policy.ts +6 -84
  157. package/src/sync/field-migration.ts +2 -39
  158. package/src/sync/file-merge-planner.ts +2 -143
  159. package/src/sync/json-document.ts +7 -184
  160. package/src/sync/local-field-policy.ts +2 -29
  161. package/src/sync/local-fields.ts +9 -119
  162. package/src/sync/merge-apply.ts +2 -439
  163. package/src/sync/merge-journal.ts +10 -228
  164. package/src/sync/merge-transfer-error.ts +2 -72
  165. package/src/sync/merged-sync.ts +2 -919
  166. package/src/sync/mutation-owner.ts +2 -22
  167. package/src/sync/package-merge.ts +2 -87
  168. package/src/sync/partial-progress.ts +2 -55
  169. package/src/sync/remote-snapshot.ts +7 -79
  170. package/src/sync/session-merge.ts +2 -194
  171. package/src/sync/settings-conflicts.ts +2 -64
  172. package/src/sync/settings-merge.ts +6 -121
  173. package/src/sync/signals.ts +2 -8
  174. package/src/sync/startup-check.ts +15 -31
  175. package/src/sync/startup-timings.ts +2 -94
  176. package/src/sync/sync-decision.ts +3 -111
  177. package/src/sync/sync-error-guidance.ts +2 -46
  178. package/src/sync/sync-errors.ts +7 -23
  179. package/src/sync/sync-inspection.ts +10 -59
  180. package/src/sync/sync-local.ts +2 -44
  181. package/src/sync/sync-mutations.ts +10 -788
  182. package/src/sync/sync-operations.ts +32 -11
  183. package/src/sync/sync-policy.ts +34 -474
  184. package/src/sync/sync-queries.ts +2 -247
  185. package/src/sync/sync-state.ts +18 -157
  186. package/src/sync/text-merge.ts +10 -133
  187. package/src/sync-extension.ts +192 -142
  188. package/src/ui/manager-state.ts +35 -23
  189. package/src/ui/manager-ui.ts +80 -36
  190. package/src/ui/sync-attention.ts +7 -49
  191. package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
  192. package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
  193. package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
  194. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
  195. package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
  196. package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
  197. package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
  198. package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
  199. package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
  200. package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
  201. package/dist/chunks/chunk-25QCU3LY.ts +0 -220
  202. package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
  203. package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
  204. package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
  205. package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
  206. package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
  207. package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
  208. package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
  209. package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
  210. package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
  211. package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
  212. package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
  213. package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
  214. package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
  215. package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
  216. package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
  217. package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
  218. package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
  219. package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
  220. package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
  221. package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
  222. package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
  223. package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
  224. package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
  225. package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
  226. package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
  227. package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
  228. package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
  229. package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
  230. package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
  231. package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
  232. package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
  233. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  234. package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
  235. package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
  236. package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
  237. package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
  238. package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
  239. package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
  240. package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
  241. package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
  242. package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
  243. package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
  244. package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
  245. package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
  246. package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
  247. package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
  248. package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
  249. package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
  250. package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
  251. package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
  252. package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
  253. package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
  254. package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
  255. package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
  256. package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
  257. package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
  258. package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
  259. package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
  260. package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
  261. package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
  262. package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
  263. package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
  264. package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
  265. package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
  266. package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
  267. package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
  268. package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
  269. package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
  270. package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
  271. package/dist/chunks/chunk-VPODHKOX.ts +0 -229
  272. package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
  273. package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
  274. package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
  275. package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
  276. package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
  277. package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
  278. package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
  279. package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
  280. package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
  281. package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
  282. package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
  283. package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
  284. package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
  285. package/dist/chunks/chunk-YEULK7MK.ts +0 -415
  286. package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
  287. package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
  288. package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
  289. package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
  290. package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
  291. package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
  292. package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
  293. package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
  294. package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
  295. package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
  296. package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
  297. package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
  298. package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
  299. package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
  300. package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
  301. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
  302. package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
  303. package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
  304. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
  305. package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
  306. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
  307. package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
  308. package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
  309. package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
  310. package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
  311. package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
  312. package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
  313. package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
  314. package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
  315. package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
  316. package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
  317. package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
  318. package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
  319. package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
  320. package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
  321. /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
  322. /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
  323. /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
  324. /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
  325. /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
  326. /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
  327. /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
@@ -1,784 +1,6 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import fs from "node:fs/promises";
3
- import path from "node:path";
4
- import { posixJoin } from "../../paths.js";
5
- import type { Snapshot, SnapshotFile } from "../../snapshot/snapshot-types.js";
6
- import { stateDir } from "../../state/state-directory.js";
7
- import { throwIfAborted } from "../../sync/signals.js";
8
- import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
9
- import type { ResolvedGitBackend } from "../backend-types.js";
10
- import {
11
- type BackendDiagnostic,
12
- type ExpectedRemoteHead,
13
- type PublishSnapshotOptions,
14
- type PublishSnapshotResult,
15
- type RemoteHead,
16
- type RemoteHistoryEntry,
17
- type SyncBackend,
18
- SyncBackendConflictError,
19
- SyncBackendPublicationOutcomeUnknownError,
20
- } from "../sync-backend.js";
21
- import {
22
- normalizeGitBranch,
23
- normalizeGitDirectory,
24
- normalizeGitRemote,
25
- normalizeGitRemoteIdentity,
26
- validateGitNamespace,
27
- } from "./git-config.js";
28
- import { GitCommandError, readGitBlobs, runGit } from "./git-runner.js";
29
- import {
30
- GIT_MANIFEST_VERSION,
31
- type GitManifest,
32
- MAX_GIT_MANIFEST_BYTES,
33
- MAX_GIT_TREE_OUTPUT_BYTES,
34
- type PreparedGitFile,
35
- parseGitTree,
36
- prepareGitSnapshot,
37
- requireGitManifest,
38
- validateGitPublicationTree,
39
- validateGitSnapshot,
40
- } from "./git-storage.js";
41
-
42
- const COMMAND_TIMEOUT_MS = 30_000;
43
- const POST_COMMIT_TIMEOUT_MS = 45_000;
44
- const gitCacheMutationQueues = new Map<string, Promise<void>>();
45
-
46
- export interface GitBackendOptions {
47
- cacheRoot?: string;
48
- allowLocalRemotes?: boolean;
49
- commandTimeoutMs?: number;
50
- postCommitTimeoutMs?: number;
51
- /** Deterministic fault injection used only by the local backend test suite. */
52
- afterPushForTest?: () => void | Promise<void>;
53
- afterLsRemoteForTest?: () => void | Promise<void>;
54
- afterPayloadWriteForTest?: () => void | Promise<void>;
55
- }
56
-
57
- export class GitSyncBackend implements SyncBackend {
58
- readonly identity: string;
59
- readonly destination: string;
60
- readonly capability = "lease-protected" as const;
61
- private readonly cacheRoot: string;
62
- private readonly cacheDir: string;
63
- private readonly allowLocalRemotes: boolean;
64
- private readonly commandTimeoutMs: number;
65
- private readonly postCommitTimeoutMs: number;
66
- private readonly afterPushForTest?: () => void | Promise<void>;
67
- private readonly afterLsRemoteForTest?: () => void | Promise<void>;
68
- private readonly afterPayloadWriteForTest?: () => void | Promise<void>;
69
- private cacheReady?: Promise<void>;
70
-
71
- constructor(
72
- private readonly config: ResolvedGitBackend,
73
- options: GitBackendOptions = {},
74
- ) {
75
- assertGitDestination(config);
76
- this.allowLocalRemotes = options.allowLocalRemotes === true;
77
- if (!this.allowLocalRemotes) assertProductionRemote(config.profile.remote);
78
- this.identity = gitBackendIdentity(config);
79
- this.destination = gitDestination(config);
80
- this.cacheRoot = path.resolve(options.cacheRoot ?? path.join(stateDir(), "git"));
81
- this.cacheDir = path.join(this.cacheRoot, this.identity.slice("git:".length), "repository.git");
82
- this.commandTimeoutMs = options.commandTimeoutMs ?? COMMAND_TIMEOUT_MS;
83
- this.postCommitTimeoutMs = options.postCommitTimeoutMs ?? POST_COMMIT_TIMEOUT_MS;
84
- this.afterPushForTest = options.afterPushForTest;
85
- this.afterLsRemoteForTest = options.afterLsRemoteForTest;
86
- this.afterPayloadWriteForTest = options.afterPayloadWriteForTest;
87
- }
88
-
89
- sameRevision(left: string, right: string) {
90
- return decodeRevision(left, this.identity) === decodeRevision(right, this.identity);
91
- }
92
-
93
- async readHead(signal?: AbortSignal): Promise<RemoteHead | undefined> {
94
- const sha = await this.fetchRemoteHead(signal);
95
- if (!sha) return undefined;
96
- const { manifest } = await this.readPublication(sha, signal);
97
- return remoteHead(sha, manifest, this.identity);
98
- }
99
-
100
- async readSnapshot(reference: string, signal?: AbortSignal): Promise<Snapshot> {
101
- const head = await this.fetchRemoteHead(signal);
102
- if (!head) throw new Error(`Git snapshot publication was not found: ${reference}`);
103
- const commit = await this.resolveSnapshotReference(reference, head, signal);
104
- try {
105
- await this.git(["cat-file", "-e", `${commit}^{commit}`], { signal });
106
- await this.git(["merge-base", "--is-ancestor", commit, head], { signal });
107
- } catch (error) {
108
- throw new Error(`Git snapshot publication was not found: ${reference}`, { cause: error });
109
- }
110
- const { manifest, payloadEntries } = await this.readPublication(commit, signal);
111
- let blobs: Buffer[];
112
- try {
113
- blobs = await readGitBlobs(
114
- payloadEntries.map((entry) => entry.object),
115
- {
116
- gitDir: this.cacheDir,
117
- signal,
118
- timeoutMs: this.commandTimeoutMs,
119
- allowFileProtocol: this.allowLocalRemotes,
120
- maxOutputBytes: manifest.files.reduce((total, file) => total + file.size, 0),
121
- },
122
- );
123
- } catch (error) {
124
- if (error instanceof Error && /exceeds/u.test(error.message)) {
125
- throw new Error("Git snapshot file content exceeds its manifest size.", { cause: error });
126
- }
127
- throw this.redactedError(error);
128
- }
129
- throwIfAborted(signal);
130
- const files: SnapshotFile[] = manifest.files.map((file, index) => {
131
- const content = blobs[index];
132
- if (!content || content.byteLength !== file.size || sha256(content) !== file.sha256) {
133
- throw new Error(`Git snapshot file checksum or size mismatch: ${file.path}`);
134
- }
135
- return { path: file.path, contentBase64: content.toString("base64"), sha256: file.sha256 };
136
- });
137
- const snapshot: Snapshot = {
138
- version: manifest.snapshotVersion,
139
- id: manifest.snapshotId,
140
- createdAt: manifest.createdAt,
141
- machine: manifest.machine,
142
- profile: manifest.profile,
143
- ...(manifest.snapshotSyncSessions === undefined ? {} : { syncSessions: manifest.snapshotSyncSessions }),
144
- ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
145
- ...(manifest.localFields === undefined ? {} : { localFields: manifest.localFields }),
146
- files,
147
- };
148
- validateGitSnapshot(snapshot, manifest, this.config.destination.namespace);
149
- return snapshot;
150
- }
151
-
152
- async publishSnapshot(
153
- snapshot: Snapshot,
154
- expected: ExpectedRemoteHead,
155
- options: PublishSnapshotOptions = {},
156
- ): Promise<PublishSnapshotResult> {
157
- throwIfAborted(options.signal);
158
- const files = prepareGitSnapshot(snapshot, this.config.destination.namespace);
159
- const observed = await this.fetchRemoteHead(options.signal);
160
- if (!matchesExpected(observed, expected, this.identity)) {
161
- throw new SyncBackendConflictError(
162
- "Git remote changed while preparing publication. Run /sync status and retry.",
163
- { currentHead: observed ? await this.headForSha(observed, options.signal) : undefined },
164
- );
165
- }
166
- throwIfAborted(options.signal);
167
- const manifest: GitManifest = {
168
- version: GIT_MANIFEST_VERSION,
169
- snapshotVersion: snapshot.version,
170
- snapshotId: snapshot.id,
171
- createdAt: snapshot.createdAt,
172
- machine: snapshot.machine,
173
- profile: snapshot.profile,
174
- syncSessions: snapshot.syncSessions === true || snapshot.files.some((file) => file.path.startsWith("sessions/")),
175
- ...(snapshot.syncSessions === undefined ? {} : { snapshotSyncSessions: snapshot.syncSessions }),
176
- ...(snapshot.selection === undefined ? {} : { selection: snapshot.selection }),
177
- ...(snapshot.localFields === undefined ? {} : { localFields: snapshot.localFields }),
178
- files: files.map(({ path: filePath, sha256: fileSha, size }) => ({
179
- path: filePath,
180
- sha256: fileSha,
181
- size,
182
- })),
183
- };
184
- let candidate: string;
185
- try {
186
- candidate = await this.createCommit(snapshot, files, manifest, observed, options.signal);
187
- } catch (error) {
188
- throw this.redactedError(error);
189
- }
190
- throwIfAborted(options.signal);
191
- options.onCommit?.();
192
-
193
- const ref = this.remoteRef();
194
- const lease = `--force-with-lease=${ref}:${observed ?? ""}`;
195
- let pushError: unknown;
196
- try {
197
- await this.git(["push", "--porcelain", "--no-verify", lease, this.config.profile.remote, `${candidate}:${ref}`], {
198
- timeoutMs: this.postCommitTimeoutMs,
199
- });
200
- await this.afterPushForTest?.();
201
- } catch (error) {
202
- pushError = error;
203
- }
204
-
205
- let current: string | undefined;
206
- try {
207
- current = await this.fetchRemoteHead(AbortSignal.timeout(this.postCommitTimeoutMs));
208
- } catch (error) {
209
- throw new SyncBackendPublicationOutcomeUnknownError(
210
- `Git publication outcome is unknown: ${this.safeError(pushError ?? error)}`,
211
- { cause: pushError ?? error },
212
- );
213
- }
214
- if (current !== candidate) {
215
- if (pushError && current === observed) {
216
- throw new Error(`Git publication failed without updating the owned branch: ${this.safeError(pushError)}`, {
217
- cause: pushError,
218
- });
219
- }
220
- throw new SyncBackendConflictError(
221
- pushError
222
- ? `Git publication lease was rejected: ${this.safeError(pushError)}`
223
- : "Git remote changed immediately after publication.",
224
- {
225
- phase: "after-commit",
226
- currentHead: current ? await this.headForSha(current) : undefined,
227
- candidateMayHaveBeenActive: true,
228
- cause: pushError instanceof Error ? pushError : undefined,
229
- },
230
- );
231
- }
232
- const head = await this.headForSha(candidate);
233
- return { head, warnings: [] };
234
- }
235
-
236
- async listHistory(signal?: AbortSignal): Promise<RemoteHistoryEntry[]> {
237
- const sha = await this.fetchRemoteHead(signal);
238
- if (!sha) return [];
239
- const result = await this.git(["rev-list", "--first-parent", "--reverse", "--max-count=100", sha], { signal });
240
- const commits = result.stdout.toString("utf8").trim().split("\n").filter(Boolean);
241
- const entries: RemoteHistoryEntry[] = [];
242
- for (const commit of commits) {
243
- const { manifest } = await this.readPublication(commit, signal);
244
- entries.push({
245
- snapshotRef: commit,
246
- snapshotId: manifest.snapshotId,
247
- createdAt: manifest.createdAt,
248
- machine: manifest.machine,
249
- syncSessions: manifest.syncSessions,
250
- });
251
- }
252
- return entries;
253
- }
254
-
255
- async diagnose(signal?: AbortSignal): Promise<BackendDiagnostic[]> {
256
- const diagnostics: BackendDiagnostic[] = [
257
- {
258
- key: "git-scope",
259
- level: "info",
260
- message: "git check scope: read remote snapshots and inspect the local cache. Write access is not tested.",
261
- },
262
- ];
263
- try {
264
- const version = await runGit(["--version"], {
265
- signal,
266
- timeoutMs: this.commandTimeoutMs,
267
- });
268
- const versionText = version.stdout.toString("utf8").trim();
269
- const supported = isSupportedGitVersion(versionText);
270
- diagnostics.push({
271
- key: "git-version",
272
- level: supported ? "info" : "error",
273
- message: supported
274
- ? versionText
275
- : `${versionText || "unknown Git version"}; pi-sync requires Git 2.30 or newer`,
276
- });
277
- } catch (error) {
278
- return [
279
- {
280
- key: "git-version",
281
- level: "error",
282
- message: syncErrorGuidance(new Error(this.safeError(error))),
283
- },
284
- ];
285
- }
286
- try {
287
- const head = await this.readHead(signal);
288
- if (head) await this.readSnapshot(head.snapshotRef, signal);
289
- diagnostics.push({
290
- key: "git-remote",
291
- level: "info",
292
- message: head
293
- ? `git remote: reachable; owned branch ${this.config.destination.branch} is valid`
294
- : `git remote: reachable; owned branch ${this.config.destination.branch} is not created yet`,
295
- });
296
- diagnostics.push({
297
- key: "git-cache",
298
- level: "info",
299
- message: "git cache: private bare repository is healthy",
300
- });
301
- } catch (error) {
302
- diagnostics.push({
303
- key: "git-remote",
304
- level: "error",
305
- message: `git remote: ${syncErrorGuidance(new Error(this.safeError(error)))}`,
306
- });
307
- }
308
- return diagnostics;
309
- }
310
-
311
- private async resolveSnapshotReference(reference: string, head: string, signal?: AbortSignal) {
312
- if (isCommitSha(reference) || /^[0-9a-f]{64}$/u.test(reference)) {
313
- requireCommitSha(reference);
314
- return reference;
315
- }
316
- if (!reference || reference.length > 512 || !/^[A-Za-z0-9._-]+$/u.test(reference)) {
317
- throw new Error("Invalid Git publication reference.");
318
- }
319
- const result = await this.git(["rev-list", "--first-parent", "--max-count=100", head], {
320
- signal,
321
- });
322
- const commits = result.stdout.toString("utf8").trim().split("\n").filter(Boolean);
323
- const matches: string[] = [];
324
- for (const commit of commits) {
325
- const { manifest } = await this.readPublication(commit, signal);
326
- if (manifest.snapshotId === reference) matches.push(commit);
327
- }
328
- if (matches.length === 0) {
329
- throw new Error(`Git snapshot publication was not found: ${reference}`);
330
- }
331
- if (matches.length > 1) {
332
- throw new Error(`Git snapshot id is ambiguous; use a commit reference from /sync history: ${reference}`);
333
- }
334
- return matches[0] as string;
335
- }
336
-
337
- private async headForSha(sha: string, signal?: AbortSignal) {
338
- const { manifest } = await this.readPublication(sha, signal);
339
- return remoteHead(sha, manifest, this.identity);
340
- }
341
-
342
- private async fetchRemoteHead(signal?: AbortSignal) {
343
- await this.ensureCache(signal);
344
- const result = await this.git(["ls-remote", "--refs", this.config.profile.remote, this.remoteRef()], { signal });
345
- const line = result.stdout.toString("utf8").trim();
346
- if (!line) return undefined;
347
- const [sha, ref, ...extra] = line.split(/\s+/u);
348
- if (extra.length > 0 || ref !== this.remoteRef() || !sha) {
349
- throw new Error("Git remote returned a malformed owned-ref response.");
350
- }
351
- requireCommitSha(sha);
352
- await this.afterLsRemoteForTest?.();
353
- return withGitCacheMutation(
354
- this.cacheDir,
355
- async () => {
356
- const localRef = `refs/pisync/fetch/${process.pid}-${randomUUID()}`;
357
- try {
358
- await this.git(
359
- ["fetch", "--no-tags", "--force", this.config.profile.remote, `${this.remoteRef()}:${localRef}`],
360
- { signal },
361
- );
362
- const fetched = (await this.git(["rev-parse", "--verify", localRef], { signal })).stdout
363
- .toString("utf8")
364
- .trim();
365
- requireCommitSha(fetched);
366
- return fetched;
367
- } finally {
368
- await this.git(["update-ref", "-d", localRef], { timeoutMs: 5_000 }).catch(() => undefined);
369
- }
370
- },
371
- signal,
372
- );
373
- }
374
-
375
- private async readManifest(commit: string, signal?: AbortSignal): Promise<GitManifest> {
376
- requireCommitSha(commit);
377
- const bytes = await this.showFile(commit, this.manifestPath(), signal, MAX_GIT_MANIFEST_BYTES);
378
- let parsed: unknown;
379
- try {
380
- parsed = JSON.parse(bytes.toString("utf8"));
381
- } catch (error) {
382
- throw new Error("Git publication manifest is malformed.", { cause: error });
383
- }
384
- return requireGitManifest(parsed);
385
- }
386
-
387
- private showFile(commit: string, filePath: string, signal?: AbortSignal, maxOutputBytes?: number) {
388
- return this.git(["show", `${commit}:${filePath}`], { signal, maxOutputBytes }).then((result) => result.stdout);
389
- }
390
-
391
- private async createCommit(
392
- snapshot: Snapshot,
393
- files: PreparedGitFile[],
394
- manifest: GitManifest,
395
- parent: string | undefined,
396
- signal?: AbortSignal,
397
- ) {
398
- const manifestBytes = Buffer.from(`${JSON.stringify(manifest)}\n`, "utf8");
399
- if (manifestBytes.byteLength > MAX_GIT_MANIFEST_BYTES) {
400
- throw new Error(`Git publication manifest exceeds the ${MAX_GIT_MANIFEST_BYTES}-byte limit.`);
401
- }
402
- await this.ensureCache(signal);
403
- const temporaryDirectory = await fs.mkdtemp(path.join(path.dirname(this.cacheDir), ".index-"));
404
- const indexPath = path.join(temporaryDirectory, "index");
405
- const payloadDirectory = path.join(temporaryDirectory, "payloads");
406
- const env = { GIT_INDEX_FILE: indexPath };
407
- try {
408
- await fs.mkdir(payloadDirectory, { mode: 0o700 });
409
- const uniqueFiles = [...new Map(files.map((file) => [file.sha256, file])).values()].sort((left, right) =>
410
- left.sha256.localeCompare(right.sha256),
411
- );
412
- for (const file of uniqueFiles) {
413
- throwIfAborted(signal);
414
- await fs.writeFile(path.join(payloadDirectory, file.sha256), file.content, {
415
- flag: "wx",
416
- mode: 0o600,
417
- });
418
- }
419
- await this.afterPayloadWriteForTest?.();
420
- throwIfAborted(signal);
421
- const hashed = await this.git(["hash-object", "-w", "--no-filters", "--stdin-paths"], {
422
- cwd: payloadDirectory,
423
- input: uniqueFiles.map((file) => file.sha256).join("\n") + (uniqueFiles.length ? "\n" : ""),
424
- signal,
425
- maxOutputBytes: Math.max(1024, uniqueFiles.length * 64),
426
- });
427
- const objectIds = hashed.stdout.toString("utf8").trim().split("\n").filter(Boolean);
428
- if (objectIds.length !== uniqueFiles.length || objectIds.some((id) => !isCommitSha(id))) {
429
- throw new Error("Git hash-object returned a malformed payload response.");
430
- }
431
- const objectsBySha256 = new Map(uniqueFiles.map((file, index) => [file.sha256, objectIds[index] as string]));
432
- const manifestBlob = (await this.git(["hash-object", "-w", "--stdin"], { input: manifestBytes, signal })).stdout
433
- .toString("utf8")
434
- .trim();
435
- if (!isCommitSha(manifestBlob)) throw new Error("Git returned an invalid manifest blob id.");
436
- await this.git(["read-tree", "--empty"], { env, signal });
437
- const indexLines = [
438
- `100644 ${manifestBlob}\t${this.manifestPath()}`,
439
- ...files.map((file) => {
440
- const object = objectsBySha256.get(file.sha256);
441
- if (!object) throw new Error("Git payload object is missing after hashing.");
442
- return `100644 ${object}\t${this.filePath(file.path)}`;
443
- }),
444
- ];
445
- await this.git(["update-index", "-z", "--index-info"], {
446
- env,
447
- signal,
448
- input: Buffer.from(`${indexLines.join("\0")}\0`, "utf8"),
449
- });
450
- const tree = (await this.git(["write-tree"], { env, signal })).stdout.toString("utf8").trim();
451
- const date = Number.isNaN(Date.parse(snapshot.createdAt)) ? new Date().toISOString() : snapshot.createdAt;
452
- const commit = await this.git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-F", "-"], {
453
- signal,
454
- input: `pi-sync snapshot ${snapshot.id}\n`,
455
- env: {
456
- GIT_AUTHOR_NAME: "pi-sync",
457
- GIT_AUTHOR_EMAIL: "pi-sync@localhost",
458
- GIT_COMMITTER_NAME: "pi-sync",
459
- GIT_COMMITTER_EMAIL: "pi-sync@localhost",
460
- GIT_AUTHOR_DATE: date,
461
- GIT_COMMITTER_DATE: date,
462
- },
463
- });
464
- const sha = commit.stdout.toString("utf8").trim();
465
- requireCommitSha(sha);
466
- return sha;
467
- } finally {
468
- await fs.rm(temporaryDirectory, { recursive: true, force: true });
469
- }
470
- }
471
-
472
- private ensureCache(signal?: AbortSignal) {
473
- if (!this.cacheReady) {
474
- const operation = withGitCacheMutation(this.cacheDir, () => this.initializeCache(signal), signal);
475
- const wrapped = operation.catch((error) => {
476
- if (this.cacheReady === wrapped) this.cacheReady = undefined;
477
- throw this.redactedError(error);
478
- });
479
- this.cacheReady = wrapped;
480
- }
481
- return this.cacheReady;
482
- }
483
-
484
- private async initializeCache(signal?: AbortSignal) {
485
- const version = await runGit(["--version"], {
486
- signal,
487
- timeoutMs: this.commandTimeoutMs,
488
- });
489
- const versionText = version.stdout.toString("utf8").trim();
490
- if (!isSupportedGitVersion(versionText)) {
491
- throw new Error(`${versionText || "Unknown Git version"}; pi-sync requires Git 2.30 or newer.`);
492
- }
493
- const parent = path.dirname(this.cacheDir);
494
- const cacheParent = path.dirname(this.cacheRoot);
495
- await assertNotSymlink(cacheParent, "Git cache parent");
496
- await assertNotSymlink(this.cacheRoot, "Git cache root");
497
- await fs.mkdir(this.cacheRoot, { recursive: true, mode: 0o700 });
498
- await assertNotSymlink(cacheParent, "Git cache parent");
499
- await assertNotSymlink(this.cacheRoot, "Git cache root");
500
- await assertNotSymlink(parent, "Git cache identity directory");
501
- await fs.mkdir(parent, { recursive: true, mode: 0o700 });
502
- await assertNotSymlink(parent, "Git cache identity directory");
503
- let recreate = false;
504
- try {
505
- const stat = await fs.lstat(this.cacheDir);
506
- if (stat.isSymbolicLink()) throw new Error("Refusing symlinked Git cache.");
507
- if (!stat.isDirectory()) recreate = true;
508
- else {
509
- try {
510
- recreate = !(await this.cacheUsesSha1(signal));
511
- } catch {
512
- throwIfAborted(signal);
513
- recreate = true;
514
- }
515
- }
516
- } catch (error) {
517
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
518
- }
519
- throwIfAborted(signal);
520
- if (recreate) await fs.rm(this.cacheDir, { recursive: true, force: true });
521
- try {
522
- await fs.access(this.cacheDir);
523
- } catch {
524
- try {
525
- await runGit(["init", "--bare", "--object-format=sha1", this.cacheDir], {
526
- signal,
527
- timeoutMs: this.commandTimeoutMs,
528
- allowFileProtocol: this.allowLocalRemotes,
529
- });
530
- } catch (initError) {
531
- const concurrent = await this.cacheUsesSha1(signal).catch(() => false);
532
- if (!concurrent) throw initError;
533
- }
534
- }
535
- if (process.platform !== "win32") await fs.chmod(parent, 0o700);
536
- }
537
-
538
- private async cacheUsesSha1(signal?: AbortSignal) {
539
- const result = await this.git(["rev-parse", "--is-bare-repository", "--show-object-format"], {
540
- signal,
541
- });
542
- return result.stdout.toString("utf8").trim() === "true\nsha1";
543
- }
544
-
545
- private git(
546
- args: string[],
547
- options: {
548
- cwd?: string;
549
- input?: Buffer | string;
550
- env?: NodeJS.ProcessEnv;
551
- signal?: AbortSignal;
552
- timeoutMs?: number;
553
- maxOutputBytes?: number;
554
- } = {},
555
- ) {
556
- return runGit(args, {
557
- gitDir: this.cacheDir,
558
- allowFileProtocol: this.allowLocalRemotes,
559
- timeoutMs: options.timeoutMs ?? this.commandTimeoutMs,
560
- ...options,
561
- }).catch((error) => {
562
- throw this.redactedError(error);
563
- });
564
- }
565
-
566
- private remoteRef() {
567
- return `refs/heads/${this.config.destination.branch}`;
568
- }
569
-
570
- private publicationPath() {
571
- return this.config.destination.directory === "./" ? "" : this.config.destination.directory;
572
- }
573
-
574
- private manifestPath() {
575
- return posixJoin(this.publicationPath(), "manifest.json");
576
- }
577
-
578
- private filePath(filePath: string) {
579
- return posixJoin(this.publicationPath(), "files", filePath);
580
- }
581
-
582
- private async readPublication(commit: string, signal?: AbortSignal) {
583
- const manifest = await this.readManifest(commit, signal);
584
- const entries = await this.readPublicationTree(commit, signal);
585
- const payloadEntries = validateGitPublicationTree(entries, manifest, this.manifestPath(), (filePath) =>
586
- this.filePath(filePath),
587
- );
588
- return { manifest, payloadEntries };
589
- }
590
-
591
- private async readPublicationTree(commit: string, signal?: AbortSignal) {
592
- const result = await this.git(["ls-tree", "-r", "-z", commit], {
593
- signal,
594
- maxOutputBytes: MAX_GIT_TREE_OUTPUT_BYTES,
595
- });
596
- return parseGitTree(result.stdout);
597
- }
598
-
599
- private redactedError(error: unknown) {
600
- if (error instanceof Error && error.name === "AbortError") return error;
601
- return new Error(this.safeError(error));
602
- }
603
-
604
- private safeError(error: unknown) {
605
- const raw =
606
- error instanceof GitCommandError
607
- ? error.stderr || error.message
608
- : error instanceof Error
609
- ? error.message
610
- : String(error);
611
- return redactGitError(raw, this.config.profile.remote, this.cacheDir);
612
- }
613
- }
614
-
615
- export function gitBackendIdentity(config: ResolvedGitBackend) {
616
- let remoteIdentity: string;
617
- try {
618
- remoteIdentity = normalizeGitRemoteIdentity(config.profile.remote);
619
- } catch {
620
- remoteIdentity = config.profile.remote;
621
- }
622
- const canonical = JSON.stringify([remoteIdentity, config.destination.branch, config.destination.directory]);
623
- return `git:${sha256(Buffer.from(canonical))}`;
624
- }
625
-
626
- function gitDestination(config: ResolvedGitBackend) {
627
- let host = "Git remote";
628
- const remote = config.profile.remote;
629
- if (remote.includes("://")) {
630
- try {
631
- host = new URL(remote).host;
632
- } catch {
633
- host = "Git remote";
634
- }
635
- } else {
636
- const match = /^(?:[^@]+@)?(?<host>\[[^\]]+\]|[^:]+):/u.exec(remote);
637
- if (match?.groups?.host) host = match.groups.host;
638
- }
639
- return `${host} · ${config.destination.branch}:${config.destination.directory}`;
640
- }
641
-
642
- function remoteHead(sha: string, manifest: GitManifest, identity: string): RemoteHead {
643
- return {
644
- snapshotRef: sha,
645
- snapshotId: manifest.snapshotId,
646
- revision: `${identity}:${sha}`,
647
- createdAt: manifest.createdAt,
648
- machine: manifest.machine,
649
- syncSessions: manifest.syncSessions,
650
- ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
651
- };
652
- }
653
-
654
- function matchesExpected(current: string | undefined, expected: ExpectedRemoteHead, identity: string) {
655
- if (expected.kind === "missing") return current === undefined;
656
- try {
657
- return current === decodeRevision(expected.revision, identity);
658
- } catch {
659
- return false;
660
- }
661
- }
662
-
663
- function decodeRevision(revision: string, identity: string) {
664
- const prefix = `${identity}:`;
665
- const sha = revision.startsWith(prefix) ? revision.slice(prefix.length) : "";
666
- if (!/^[0-9a-f]{40}$/u.test(sha)) throw new Error("Invalid Git remote revision.");
667
- return sha;
668
- }
669
-
670
- function isCommitSha(value: string) {
671
- return /^[0-9a-f]{40}$/u.test(value);
672
- }
673
-
674
- function requireCommitSha(value: string) {
675
- if (/^[0-9a-f]{64}$/u.test(value)) {
676
- throw new Error("Unsupported Git SHA-256 repository; pi-sync currently requires SHA-1 refs.");
677
- }
678
- if (!/^[0-9a-f]{40}$/u.test(value)) throw new Error("Invalid Git publication reference.");
679
- }
680
-
681
- export function isSupportedGitVersion(value: string) {
682
- const match = /git version (\d+)\.(\d+)/u.exec(value);
683
- if (!match) return false;
684
- const major = Number(match[1]);
685
- const minor = Number(match[2]);
686
- return major > 2 || (major === 2 && minor >= 30);
687
- }
688
-
689
- function assertGitDestination(config: ResolvedGitBackend) {
690
- try {
691
- if (
692
- normalizeGitBranch(config.destination.branch) !== config.destination.branch ||
693
- normalizeGitDirectory(config.destination.directory) !== config.destination.directory
694
- ) {
695
- throw new Error("Git storage location is not normalized.");
696
- }
697
- validateGitNamespace(config.destination.namespace);
698
- } catch (error) {
699
- throw new Error("Invalid Git storage location.", { cause: error });
700
- }
701
- }
702
-
703
- function assertProductionRemote(remote: string) {
704
- let normalized: string | undefined;
705
- try {
706
- normalized = normalizeGitRemote(remote);
707
- } catch (error) {
708
- throw new Error(error instanceof Error ? error.message : "Invalid Git remote.", {
709
- cause: error,
710
- });
711
- }
712
- if (!normalized || normalized !== remote) throw new Error("Invalid or non-normalized Git remote.");
713
- }
714
-
715
- async function withGitCacheMutation<T>(cacheDir: string, run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
716
- const previous = gitCacheMutationQueues.get(cacheDir) ?? Promise.resolve();
717
- let started = false;
718
- const operation = previous
719
- .catch(() => undefined)
720
- .then(() => {
721
- throwIfAborted(signal);
722
- started = true;
723
- return run();
724
- });
725
- const tail = operation.then(
726
- () => undefined,
727
- () => undefined,
728
- );
729
- gitCacheMutationQueues.set(cacheDir, tail);
730
- void tail.then(() => {
731
- if (gitCacheMutationQueues.get(cacheDir) === tail) gitCacheMutationQueues.delete(cacheDir);
732
- });
733
- if (!signal) return operation;
734
- throwIfAborted(signal);
735
- let rejectAbort: ((reason: unknown) => void) | undefined;
736
- const aborted = new Promise<never>((_resolve, reject) => {
737
- rejectAbort = reject;
738
- });
739
- const onAbort = () => rejectAbort?.(abortReason(signal));
740
- signal.addEventListener("abort", onAbort, { once: true });
741
- if (signal.aborted) onAbort();
742
- try {
743
- return await Promise.race([operation, aborted]);
744
- } catch (error) {
745
- // A queued job can cancel immediately, but a running job owns a child/cache
746
- // mutation. Drain its bounded cleanup before releasing outer sync guards.
747
- if (started) await tail;
748
- throw error;
749
- } finally {
750
- signal.removeEventListener("abort", onAbort);
751
- }
752
- }
753
-
754
- async function assertNotSymlink(target: string, label: string) {
755
- try {
756
- const stat = await fs.lstat(target);
757
- if (stat.isSymbolicLink()) throw new Error(`Refusing symlinked ${label}.`);
758
- } catch (error) {
759
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
760
- }
761
- }
762
-
763
- function redactGitError(value: string, remote: string, cacheDir: string) {
764
- return (
765
- value
766
- .replaceAll(remote, "<git-remote>")
767
- .replaceAll(cacheDir, "<git-cache>")
768
- .replace(/https:\/\/[^/@\s]+@/gu, "https://<credentials>@")
769
- .replace(/\b(password|token|authorization)=\S+/giu, "$1=<redacted>")
770
- .replace(/\bBearer\s+\S+/giu, "Bearer <redacted>")
771
- // biome-ignore lint/suspicious/noControlCharactersInRegex: sanitize untrusted process output.
772
- .replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ")
773
- .trim()
774
- .slice(0, 4096)
775
- );
776
- }
777
-
778
- function sha256(value: Buffer) {
779
- return createHash("sha256").update(value).digest("hex");
780
- }
781
-
782
- function abortReason(signal: AbortSignal) {
783
- return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
784
- }
1
+ export type * from "@narumitw/sync-daemon/engine/backends/git/git-backend";
2
+ export {
3
+ GitSyncBackend,
4
+ gitBackendIdentity,
5
+ isSupportedGitVersion,
6
+ } from "@narumitw/sync-daemon/engine/backends/git/git-backend";