@noy-db/hub 0.4.0 → 0.5.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 (325) hide show
  1. package/dist/api-M7REIE7H.js +20 -0
  2. package/dist/attestation/index.js +16 -16
  3. package/dist/{backup-X7F3TCFV.js → backup-ENTZYW37.js} +9 -9
  4. package/dist/blobs/index.js +11 -11
  5. package/dist/broker/index.js +10 -10
  6. package/dist/cargo/index.js +26 -26
  7. package/dist/{chunk-6ZNSB3H6.js → chunk-3LYMOSY7.js} +2 -2
  8. package/dist/{chunk-LXRTP3AQ.js → chunk-4DGBZEV6.js} +2 -2
  9. package/dist/{chunk-LRRX57UA.js → chunk-4MSNAB64.js} +4 -4
  10. package/dist/{chunk-MXUT7FTE.js → chunk-4SG5TOXK.js} +2 -2
  11. package/dist/{chunk-W66AM5IB.js → chunk-4TXO442D.js} +2 -2
  12. package/dist/{chunk-UADPR6F4.js → chunk-5EKL6BXI.js} +3 -3
  13. package/dist/{chunk-ZBYFMI6D.js → chunk-5UKUOMO6.js} +247 -136
  14. package/dist/chunk-5UKUOMO6.js.map +1 -0
  15. package/dist/{chunk-SU6SGWXM.js → chunk-623QEHDB.js} +6 -6
  16. package/dist/{chunk-IVYQAVWO.js → chunk-653KOQ7A.js} +7 -7
  17. package/dist/{chunk-2BET5QTS.js → chunk-6PFST3FC.js} +4 -4
  18. package/dist/{chunk-PWPYO73B.js → chunk-6RDTG6E5.js} +5 -5
  19. package/dist/{chunk-DAFBJS4Y.js → chunk-7P4LL3JH.js} +3 -3
  20. package/dist/{chunk-S7GIXBXV.js → chunk-AJAOXFCF.js} +8 -8
  21. package/dist/chunk-AJAOXFCF.js.map +1 -0
  22. package/dist/{chunk-L3YYLT4E.js → chunk-ALUVACKT.js} +2 -2
  23. package/dist/{chunk-QZWTRENR.js → chunk-AR5D76T2.js} +5 -1
  24. package/dist/chunk-AR5D76T2.js.map +1 -0
  25. package/dist/{chunk-5DRROK5W.js → chunk-BFG7LD6Z.js} +2 -2
  26. package/dist/{chunk-6UBZ6I5Z.js → chunk-DDB626I7.js} +2 -2
  27. package/dist/{chunk-W3G5REIU.js → chunk-EAN4TAPC.js} +2 -2
  28. package/dist/{chunk-4JQK3L4V.js → chunk-EBETHILL.js} +2 -2
  29. package/dist/{chunk-467SWYT5.js → chunk-ECGDJU5R.js} +3 -3
  30. package/dist/{chunk-WYUAEZSC.js → chunk-ELJOLQIG.js} +14 -13
  31. package/dist/chunk-ELJOLQIG.js.map +1 -0
  32. package/dist/{chunk-ZFG5EBI3.js → chunk-F2WWHKO7.js} +5 -5
  33. package/dist/{chunk-NJ4DYYO5.js → chunk-F5UWVF6Z.js} +2 -2
  34. package/dist/{chunk-Q36YXK77.js → chunk-FHK6WWUE.js} +2 -2
  35. package/dist/{chunk-SHEEBRZ4.js → chunk-FT5Y4VSP.js} +2 -2
  36. package/dist/{chunk-JQ2AX4T5.js → chunk-FUECZSRM.js} +2 -2
  37. package/dist/{chunk-Q5YJCVJY.js → chunk-FZAP4JNC.js} +4 -4
  38. package/dist/{chunk-SFBYQMZM.js → chunk-G3ORJ3IQ.js} +4 -4
  39. package/dist/{chunk-HLKXPJ4V.js → chunk-G7ZIMGPQ.js} +5 -5
  40. package/dist/{chunk-QJNCB5SK.js → chunk-GIGLOQL7.js} +2 -2
  41. package/dist/{chunk-ERGECZEI.js → chunk-GTQF32TP.js} +5 -5
  42. package/dist/{chunk-JYJFGD2H.js → chunk-GYJRDALN.js} +2 -2
  43. package/dist/{chunk-HZZP2ZIG.js → chunk-HGDXJVK2.js} +4 -4
  44. package/dist/{chunk-ZNWSG7XC.js → chunk-IHYSIPEK.js} +6 -6
  45. package/dist/{chunk-5GQEU4DN.js → chunk-IJV56FWY.js} +2 -2
  46. package/dist/{chunk-5UQ7Y6SQ.js → chunk-IM2KST7E.js} +3 -3
  47. package/dist/{chunk-7H3WWH6J.js → chunk-IQ423YMK.js} +3 -3
  48. package/dist/{chunk-P4JO3H6R.js → chunk-J7YVY7TW.js} +2 -2
  49. package/dist/{chunk-YGK2HMLR.js → chunk-JLBCK7XM.js} +8 -8
  50. package/dist/chunk-JLBCK7XM.js.map +1 -0
  51. package/dist/{chunk-2J6UEN2V.js → chunk-K5OFKXUG.js} +2 -2
  52. package/dist/{chunk-JEI6JJNI.js → chunk-KDWBVCIX.js} +5 -5
  53. package/dist/{chunk-T2MOJF76.js → chunk-KJNMTE2W.js} +6 -6
  54. package/dist/{chunk-NFZGZ4AK.js → chunk-L67H6FAQ.js} +2 -2
  55. package/dist/{chunk-RBTVFPHF.js → chunk-LQVRK2XJ.js} +4 -4
  56. package/dist/{chunk-MHMLXJ3I.js → chunk-LXRVTJ5D.js} +2 -2
  57. package/dist/{chunk-LLYIMSQQ.js → chunk-MDRCEA56.js} +10 -10
  58. package/dist/{chunk-KRCBZYTZ.js → chunk-MFW466PX.js} +4 -4
  59. package/dist/{chunk-RO5NM6UI.js → chunk-MGXUAID4.js} +2 -2
  60. package/dist/{chunk-OWHP3H5C.js → chunk-MPW6AHTC.js} +3 -3
  61. package/dist/{chunk-35NMVJ7I.js → chunk-MYSNNMJ3.js} +3 -3
  62. package/dist/{chunk-QGIBI6GL.js → chunk-NG4AQIYJ.js} +4 -4
  63. package/dist/{chunk-BLBAQRBM.js → chunk-NIKQQXI2.js} +2 -2
  64. package/dist/{chunk-55LX6FSX.js → chunk-NJHQE4LT.js} +2 -2
  65. package/dist/{chunk-TS5XLBZR.js → chunk-NMYH55MW.js} +4 -4
  66. package/dist/{chunk-GTYFIVIZ.js → chunk-NWK6SVBM.js} +5 -5
  67. package/dist/chunk-NWK6SVBM.js.map +1 -0
  68. package/dist/{chunk-IFOH7RBI.js → chunk-NZEGQWQ5.js} +4 -4
  69. package/dist/{chunk-DTFA5DO4.js → chunk-ODCEOSJF.js} +2 -2
  70. package/dist/{chunk-NYEFP7DY.js → chunk-OKBNFUUX.js} +2 -2
  71. package/dist/{chunk-SGDPRCC4.js → chunk-OKRXXFZZ.js} +3 -3
  72. package/dist/{chunk-IG6KUWBX.js → chunk-P6UIVLZK.js} +2 -2
  73. package/dist/{chunk-V6UQZA2H.js → chunk-PKBONLCP.js} +2 -2
  74. package/dist/{chunk-MSMJJB4J.js → chunk-PTSVGKSR.js} +2 -2
  75. package/dist/{chunk-IXNCZTWA.js → chunk-PWEMRXPO.js} +2 -2
  76. package/dist/{chunk-PTHKZWEH.js → chunk-PZRYKOKP.js} +2 -2
  77. package/dist/{chunk-KD4HGBJV.js → chunk-Q6MXHDSE.js} +3 -3
  78. package/dist/{chunk-RQ4ZI4ZI.js → chunk-QITP2JGX.js} +5 -5
  79. package/dist/{chunk-WBKZUO5V.js → chunk-QMCWYN6O.js} +3 -3
  80. package/dist/{chunk-4ZKNC6A6.js → chunk-QQL6XPPG.js} +2 -2
  81. package/dist/{chunk-TG634KCO.js → chunk-QTMZDMJ6.js} +2 -2
  82. package/dist/{chunk-AT2JJEKJ.js → chunk-RM4FIXY2.js} +4 -4
  83. package/dist/{chunk-AKKRXT23.js → chunk-RPWMDIGK.js} +2 -2
  84. package/dist/{chunk-NBXFCQX4.js → chunk-RQILGK3N.js} +8 -8
  85. package/dist/chunk-RQILGK3N.js.map +1 -0
  86. package/dist/{chunk-NM5UYF6Q.js → chunk-SBGXQK5I.js} +2 -2
  87. package/dist/{chunk-SF2ZIRD6.js → chunk-SL3PLML2.js} +3 -3
  88. package/dist/{chunk-3ECU57YH.js → chunk-TJOUKMWF.js} +8 -8
  89. package/dist/{chunk-QD46HPZG.js → chunk-U2ID5A2I.js} +2 -2
  90. package/dist/{chunk-X4MVWPHV.js → chunk-UC5Y7OEJ.js} +3 -3
  91. package/dist/{chunk-SBHN6QUT.js → chunk-US2AR4BI.js} +2 -2
  92. package/dist/{chunk-DQZXPGGZ.js → chunk-V3EGXDFN.js} +3 -3
  93. package/dist/{chunk-ZHDSUZQU.js → chunk-V4O6YZSP.js} +3 -3
  94. package/dist/{chunk-3HUYRN24.js → chunk-W7C7MMIS.js} +3 -3
  95. package/dist/{chunk-NLYALJMY.js → chunk-WFYKIDCS.js} +30 -11
  96. package/dist/chunk-WFYKIDCS.js.map +1 -0
  97. package/dist/{chunk-TWPK7KUJ.js → chunk-XID22NOA.js} +5 -5
  98. package/dist/{chunk-E23UGFVC.js → chunk-XVK7TULT.js} +2 -2
  99. package/dist/{chunk-WUHEP3HH.js → chunk-XX7YB5BI.js} +4 -4
  100. package/dist/{chunk-ZTLOXFPB.js → chunk-Y2PTKKIN.js} +2 -2
  101. package/dist/{chunk-KYRDJI5O.js → chunk-YA7Y3EZP.js} +10 -10
  102. package/dist/classified/index.js +4 -4
  103. package/dist/{classified-marker-LE54HWSX.js → classified-marker-ZALWKOBC.js} +3 -3
  104. package/dist/{collection-facade-DO2AABZT.js → collection-facade-KI53O6QB.js} +15 -15
  105. package/dist/{computed-AB45PS4V.js → computed-YOQCGUCS.js} +3 -3
  106. package/dist/consent/index.js +7 -7
  107. package/dist/cover/index.js +2 -2
  108. package/dist/custody/index.js +9 -9
  109. package/dist/{dead-filter-V3LVWYEJ.js → dead-filter-6DVWST6U.js} +2 -2
  110. package/dist/debug/index.js +1 -1
  111. package/dist/{delegation-JDUMAF6L.js → delegation-WMO3Q3O5.js} +8 -8
  112. package/dist/derivations/index.js +10 -10
  113. package/dist/{derive-ZPGVLE2Q.js → derive-P2NXWUNB.js} +8 -8
  114. package/dist/directory/index.js +8 -8
  115. package/dist/{dispatch-W7NWQ637.js → dispatch-TKV4UCKB.js} +16 -16
  116. package/dist/{dispatch-6TV3DGO6.js → dispatch-VNR3TLBX.js} +5 -5
  117. package/dist/{enclave-YFCLPIDR.js → enclave-YWP3QAIQ.js} +7 -7
  118. package/dist/executor-M4ZZNX6S.js +28 -0
  119. package/dist/executor-TI64S4LE.js +9 -0
  120. package/dist/executor-YBK3I2OT.js +9 -0
  121. package/dist/export-accessible-GBLYLGW4.js +23 -0
  122. package/dist/extract-partition-SFV35U2R.js +38 -0
  123. package/dist/{fanout-sidecar-273RDMYS.js → fanout-sidecar-WYXO6QQT.js} +7 -7
  124. package/dist/find-HUSSZRBR.js +11 -0
  125. package/dist/forget/index.js +7 -7
  126. package/dist/guards/index.js +5 -5
  127. package/dist/history/index.js +10 -10
  128. package/dist/i18n/index.js +12 -12
  129. package/dist/index.d.ts +1 -1
  130. package/dist/index.js +86 -84
  131. package/dist/index.js.map +1 -1
  132. package/dist/indexing/index.js +2 -2
  133. package/dist/introspection/index.js +9 -9
  134. package/dist/issue-6TIJYWKS.js +19 -0
  135. package/dist/kernel/collection-config.d.ts +4 -0
  136. package/dist/kernel/collection.d.ts +24 -6
  137. package/dist/kernel/errors.d.ts +15 -0
  138. package/dist/kernel/put-many-atomic.d.ts +45 -0
  139. package/dist/kernel/vault.d.ts +14 -0
  140. package/dist/{ledger-XE7JF2I2.js → ledger-BLYDYRTQ.js} +9 -9
  141. package/dist/liberate-TSOW7IG5.js +24 -0
  142. package/dist/{link-set-CGYC3OH5.js → link-set-7F5ZPDEB.js} +9 -9
  143. package/dist/materialized-views/index.js +22 -22
  144. package/dist/money/index.js +3 -3
  145. package/dist/noydb-KFN6M6UJ.js +81 -0
  146. package/dist/overlay-views/index.js +4 -4
  147. package/dist/periods/index.js +11 -11
  148. package/dist/pod/index.js +9 -9
  149. package/dist/policy/index.js +2 -2
  150. package/dist/port/with/write-hooks.d.ts +6 -0
  151. package/dist/portability/index.js +8 -8
  152. package/dist/{post-register-LY35EDTJ.js → post-register-PQSY544J.js} +6 -6
  153. package/dist/query/index.js +3 -3
  154. package/dist/reduce/index.js +4 -4
  155. package/dist/{register-6RIBIT3I.js → register-S3ECUZPV.js} +10 -10
  156. package/dist/registry-FZOHKUME.js +18 -0
  157. package/dist/registry-RISV7IDZ.js +19 -0
  158. package/dist/registry-ZE35A7WC.js +9 -0
  159. package/dist/{request-withdrawal-FT3ORAWN.js → request-withdrawal-KXVTQKR5.js} +12 -12
  160. package/dist/{reveal-T34ADTPY.js → reveal-HY7DZST4.js} +4 -4
  161. package/dist/{revoke-HC7WG3HE.js → revoke-J473JJ22.js} +9 -9
  162. package/dist/satellites/index.js +1 -1
  163. package/dist/schema-update/index.js +2 -2
  164. package/dist/sealed-record/index.js +10 -10
  165. package/dist/search/index.js +4 -4
  166. package/dist/{seed-JOV54PB3.js → seed-ALU3BHFS.js} +13 -13
  167. package/dist/seed-ALU3BHFS.js.map +1 -0
  168. package/dist/sequence/index.js +7 -7
  169. package/dist/session/index.js +7 -7
  170. package/dist/shadow/index.js +2 -2
  171. package/dist/{signer-CTWOH6KT.js → signer-XLUKCCH3.js} +8 -8
  172. package/dist/snapshots/index.js +8 -8
  173. package/dist/{stale-T3V7XEOB.js → stale-U3WO5MYN.js} +8 -8
  174. package/dist/{storage-LLNLPWWB.js → storage-IQONEOYY.js} +8 -8
  175. package/dist/sync/index.js +8 -8
  176. package/dist/team/index.js +11 -11
  177. package/dist/tiers/index.js +8 -8
  178. package/dist/to/index.js +1 -1
  179. package/dist/transactions/index.js +3 -3
  180. package/dist/util/index.js +1 -1
  181. package/dist/{verify-7XWHJWUN.js → verify-JEIXSK5U.js} +5 -5
  182. package/dist/walk-BF36V4SR.js +21 -0
  183. package/dist/with-commit/tx/atomic-eligibility.d.ts +13 -11
  184. package/dist/with-sync/engine.d.ts +13 -0
  185. package/dist/{withdraw-accessible-ANSVG6XG.js → withdraw-accessible-TYTA23XH.js} +11 -11
  186. package/package.json +3 -3
  187. package/dist/api-SI2IVBQO.js +0 -20
  188. package/dist/chunk-GTYFIVIZ.js.map +0 -1
  189. package/dist/chunk-NBXFCQX4.js.map +0 -1
  190. package/dist/chunk-NLYALJMY.js.map +0 -1
  191. package/dist/chunk-QZWTRENR.js.map +0 -1
  192. package/dist/chunk-S7GIXBXV.js.map +0 -1
  193. package/dist/chunk-WYUAEZSC.js.map +0 -1
  194. package/dist/chunk-YGK2HMLR.js.map +0 -1
  195. package/dist/chunk-ZBYFMI6D.js.map +0 -1
  196. package/dist/executor-FPHKWDWT.js +0 -28
  197. package/dist/executor-IEBLTBCW.js +0 -9
  198. package/dist/executor-RM7XWQDU.js +0 -9
  199. package/dist/export-accessible-EKM3HGB2.js +0 -23
  200. package/dist/extract-partition-LS4ET5A6.js +0 -38
  201. package/dist/find-OZMTRIK3.js +0 -11
  202. package/dist/issue-LIA7FXBJ.js +0 -19
  203. package/dist/liberate-WZ3RHVKW.js +0 -24
  204. package/dist/noydb-ZLPVCDES.js +0 -81
  205. package/dist/registry-7Y5WF7GS.js +0 -9
  206. package/dist/registry-MUSL4AW6.js +0 -19
  207. package/dist/registry-RON4WHAP.js +0 -18
  208. package/dist/seed-JOV54PB3.js.map +0 -1
  209. package/dist/walk-G3NFEP5L.js +0 -21
  210. /package/dist/{api-SI2IVBQO.js.map → api-M7REIE7H.js.map} +0 -0
  211. /package/dist/{backup-X7F3TCFV.js.map → backup-ENTZYW37.js.map} +0 -0
  212. /package/dist/{chunk-6ZNSB3H6.js.map → chunk-3LYMOSY7.js.map} +0 -0
  213. /package/dist/{chunk-LXRTP3AQ.js.map → chunk-4DGBZEV6.js.map} +0 -0
  214. /package/dist/{chunk-LRRX57UA.js.map → chunk-4MSNAB64.js.map} +0 -0
  215. /package/dist/{chunk-MXUT7FTE.js.map → chunk-4SG5TOXK.js.map} +0 -0
  216. /package/dist/{chunk-W66AM5IB.js.map → chunk-4TXO442D.js.map} +0 -0
  217. /package/dist/{chunk-UADPR6F4.js.map → chunk-5EKL6BXI.js.map} +0 -0
  218. /package/dist/{chunk-SU6SGWXM.js.map → chunk-623QEHDB.js.map} +0 -0
  219. /package/dist/{chunk-IVYQAVWO.js.map → chunk-653KOQ7A.js.map} +0 -0
  220. /package/dist/{chunk-2BET5QTS.js.map → chunk-6PFST3FC.js.map} +0 -0
  221. /package/dist/{chunk-PWPYO73B.js.map → chunk-6RDTG6E5.js.map} +0 -0
  222. /package/dist/{chunk-DAFBJS4Y.js.map → chunk-7P4LL3JH.js.map} +0 -0
  223. /package/dist/{chunk-L3YYLT4E.js.map → chunk-ALUVACKT.js.map} +0 -0
  224. /package/dist/{chunk-5DRROK5W.js.map → chunk-BFG7LD6Z.js.map} +0 -0
  225. /package/dist/{chunk-6UBZ6I5Z.js.map → chunk-DDB626I7.js.map} +0 -0
  226. /package/dist/{chunk-W3G5REIU.js.map → chunk-EAN4TAPC.js.map} +0 -0
  227. /package/dist/{chunk-4JQK3L4V.js.map → chunk-EBETHILL.js.map} +0 -0
  228. /package/dist/{chunk-467SWYT5.js.map → chunk-ECGDJU5R.js.map} +0 -0
  229. /package/dist/{chunk-ZFG5EBI3.js.map → chunk-F2WWHKO7.js.map} +0 -0
  230. /package/dist/{chunk-NJ4DYYO5.js.map → chunk-F5UWVF6Z.js.map} +0 -0
  231. /package/dist/{chunk-Q36YXK77.js.map → chunk-FHK6WWUE.js.map} +0 -0
  232. /package/dist/{chunk-SHEEBRZ4.js.map → chunk-FT5Y4VSP.js.map} +0 -0
  233. /package/dist/{chunk-JQ2AX4T5.js.map → chunk-FUECZSRM.js.map} +0 -0
  234. /package/dist/{chunk-Q5YJCVJY.js.map → chunk-FZAP4JNC.js.map} +0 -0
  235. /package/dist/{chunk-SFBYQMZM.js.map → chunk-G3ORJ3IQ.js.map} +0 -0
  236. /package/dist/{chunk-HLKXPJ4V.js.map → chunk-G7ZIMGPQ.js.map} +0 -0
  237. /package/dist/{chunk-QJNCB5SK.js.map → chunk-GIGLOQL7.js.map} +0 -0
  238. /package/dist/{chunk-ERGECZEI.js.map → chunk-GTQF32TP.js.map} +0 -0
  239. /package/dist/{chunk-JYJFGD2H.js.map → chunk-GYJRDALN.js.map} +0 -0
  240. /package/dist/{chunk-HZZP2ZIG.js.map → chunk-HGDXJVK2.js.map} +0 -0
  241. /package/dist/{chunk-ZNWSG7XC.js.map → chunk-IHYSIPEK.js.map} +0 -0
  242. /package/dist/{chunk-5GQEU4DN.js.map → chunk-IJV56FWY.js.map} +0 -0
  243. /package/dist/{chunk-5UQ7Y6SQ.js.map → chunk-IM2KST7E.js.map} +0 -0
  244. /package/dist/{chunk-7H3WWH6J.js.map → chunk-IQ423YMK.js.map} +0 -0
  245. /package/dist/{chunk-P4JO3H6R.js.map → chunk-J7YVY7TW.js.map} +0 -0
  246. /package/dist/{chunk-2J6UEN2V.js.map → chunk-K5OFKXUG.js.map} +0 -0
  247. /package/dist/{chunk-JEI6JJNI.js.map → chunk-KDWBVCIX.js.map} +0 -0
  248. /package/dist/{chunk-T2MOJF76.js.map → chunk-KJNMTE2W.js.map} +0 -0
  249. /package/dist/{chunk-NFZGZ4AK.js.map → chunk-L67H6FAQ.js.map} +0 -0
  250. /package/dist/{chunk-RBTVFPHF.js.map → chunk-LQVRK2XJ.js.map} +0 -0
  251. /package/dist/{chunk-MHMLXJ3I.js.map → chunk-LXRVTJ5D.js.map} +0 -0
  252. /package/dist/{chunk-LLYIMSQQ.js.map → chunk-MDRCEA56.js.map} +0 -0
  253. /package/dist/{chunk-KRCBZYTZ.js.map → chunk-MFW466PX.js.map} +0 -0
  254. /package/dist/{chunk-RO5NM6UI.js.map → chunk-MGXUAID4.js.map} +0 -0
  255. /package/dist/{chunk-OWHP3H5C.js.map → chunk-MPW6AHTC.js.map} +0 -0
  256. /package/dist/{chunk-35NMVJ7I.js.map → chunk-MYSNNMJ3.js.map} +0 -0
  257. /package/dist/{chunk-QGIBI6GL.js.map → chunk-NG4AQIYJ.js.map} +0 -0
  258. /package/dist/{chunk-BLBAQRBM.js.map → chunk-NIKQQXI2.js.map} +0 -0
  259. /package/dist/{chunk-55LX6FSX.js.map → chunk-NJHQE4LT.js.map} +0 -0
  260. /package/dist/{chunk-TS5XLBZR.js.map → chunk-NMYH55MW.js.map} +0 -0
  261. /package/dist/{chunk-IFOH7RBI.js.map → chunk-NZEGQWQ5.js.map} +0 -0
  262. /package/dist/{chunk-DTFA5DO4.js.map → chunk-ODCEOSJF.js.map} +0 -0
  263. /package/dist/{chunk-NYEFP7DY.js.map → chunk-OKBNFUUX.js.map} +0 -0
  264. /package/dist/{chunk-SGDPRCC4.js.map → chunk-OKRXXFZZ.js.map} +0 -0
  265. /package/dist/{chunk-IG6KUWBX.js.map → chunk-P6UIVLZK.js.map} +0 -0
  266. /package/dist/{chunk-V6UQZA2H.js.map → chunk-PKBONLCP.js.map} +0 -0
  267. /package/dist/{chunk-MSMJJB4J.js.map → chunk-PTSVGKSR.js.map} +0 -0
  268. /package/dist/{chunk-IXNCZTWA.js.map → chunk-PWEMRXPO.js.map} +0 -0
  269. /package/dist/{chunk-PTHKZWEH.js.map → chunk-PZRYKOKP.js.map} +0 -0
  270. /package/dist/{chunk-KD4HGBJV.js.map → chunk-Q6MXHDSE.js.map} +0 -0
  271. /package/dist/{chunk-RQ4ZI4ZI.js.map → chunk-QITP2JGX.js.map} +0 -0
  272. /package/dist/{chunk-WBKZUO5V.js.map → chunk-QMCWYN6O.js.map} +0 -0
  273. /package/dist/{chunk-4ZKNC6A6.js.map → chunk-QQL6XPPG.js.map} +0 -0
  274. /package/dist/{chunk-TG634KCO.js.map → chunk-QTMZDMJ6.js.map} +0 -0
  275. /package/dist/{chunk-AT2JJEKJ.js.map → chunk-RM4FIXY2.js.map} +0 -0
  276. /package/dist/{chunk-AKKRXT23.js.map → chunk-RPWMDIGK.js.map} +0 -0
  277. /package/dist/{chunk-NM5UYF6Q.js.map → chunk-SBGXQK5I.js.map} +0 -0
  278. /package/dist/{chunk-SF2ZIRD6.js.map → chunk-SL3PLML2.js.map} +0 -0
  279. /package/dist/{chunk-3ECU57YH.js.map → chunk-TJOUKMWF.js.map} +0 -0
  280. /package/dist/{chunk-QD46HPZG.js.map → chunk-U2ID5A2I.js.map} +0 -0
  281. /package/dist/{chunk-X4MVWPHV.js.map → chunk-UC5Y7OEJ.js.map} +0 -0
  282. /package/dist/{chunk-SBHN6QUT.js.map → chunk-US2AR4BI.js.map} +0 -0
  283. /package/dist/{chunk-DQZXPGGZ.js.map → chunk-V3EGXDFN.js.map} +0 -0
  284. /package/dist/{chunk-ZHDSUZQU.js.map → chunk-V4O6YZSP.js.map} +0 -0
  285. /package/dist/{chunk-3HUYRN24.js.map → chunk-W7C7MMIS.js.map} +0 -0
  286. /package/dist/{chunk-TWPK7KUJ.js.map → chunk-XID22NOA.js.map} +0 -0
  287. /package/dist/{chunk-E23UGFVC.js.map → chunk-XVK7TULT.js.map} +0 -0
  288. /package/dist/{chunk-WUHEP3HH.js.map → chunk-XX7YB5BI.js.map} +0 -0
  289. /package/dist/{chunk-ZTLOXFPB.js.map → chunk-Y2PTKKIN.js.map} +0 -0
  290. /package/dist/{chunk-KYRDJI5O.js.map → chunk-YA7Y3EZP.js.map} +0 -0
  291. /package/dist/{classified-marker-LE54HWSX.js.map → classified-marker-ZALWKOBC.js.map} +0 -0
  292. /package/dist/{collection-facade-DO2AABZT.js.map → collection-facade-KI53O6QB.js.map} +0 -0
  293. /package/dist/{computed-AB45PS4V.js.map → computed-YOQCGUCS.js.map} +0 -0
  294. /package/dist/{dead-filter-V3LVWYEJ.js.map → dead-filter-6DVWST6U.js.map} +0 -0
  295. /package/dist/{delegation-JDUMAF6L.js.map → delegation-WMO3Q3O5.js.map} +0 -0
  296. /package/dist/{derive-ZPGVLE2Q.js.map → derive-P2NXWUNB.js.map} +0 -0
  297. /package/dist/{dispatch-W7NWQ637.js.map → dispatch-TKV4UCKB.js.map} +0 -0
  298. /package/dist/{dispatch-6TV3DGO6.js.map → dispatch-VNR3TLBX.js.map} +0 -0
  299. /package/dist/{enclave-YFCLPIDR.js.map → enclave-YWP3QAIQ.js.map} +0 -0
  300. /package/dist/{executor-FPHKWDWT.js.map → executor-M4ZZNX6S.js.map} +0 -0
  301. /package/dist/{executor-IEBLTBCW.js.map → executor-TI64S4LE.js.map} +0 -0
  302. /package/dist/{executor-RM7XWQDU.js.map → executor-YBK3I2OT.js.map} +0 -0
  303. /package/dist/{export-accessible-EKM3HGB2.js.map → export-accessible-GBLYLGW4.js.map} +0 -0
  304. /package/dist/{extract-partition-LS4ET5A6.js.map → extract-partition-SFV35U2R.js.map} +0 -0
  305. /package/dist/{fanout-sidecar-273RDMYS.js.map → fanout-sidecar-WYXO6QQT.js.map} +0 -0
  306. /package/dist/{find-OZMTRIK3.js.map → find-HUSSZRBR.js.map} +0 -0
  307. /package/dist/{issue-LIA7FXBJ.js.map → issue-6TIJYWKS.js.map} +0 -0
  308. /package/dist/{ledger-XE7JF2I2.js.map → ledger-BLYDYRTQ.js.map} +0 -0
  309. /package/dist/{liberate-WZ3RHVKW.js.map → liberate-TSOW7IG5.js.map} +0 -0
  310. /package/dist/{link-set-CGYC3OH5.js.map → link-set-7F5ZPDEB.js.map} +0 -0
  311. /package/dist/{noydb-ZLPVCDES.js.map → noydb-KFN6M6UJ.js.map} +0 -0
  312. /package/dist/{post-register-LY35EDTJ.js.map → post-register-PQSY544J.js.map} +0 -0
  313. /package/dist/{register-6RIBIT3I.js.map → register-S3ECUZPV.js.map} +0 -0
  314. /package/dist/{registry-7Y5WF7GS.js.map → registry-FZOHKUME.js.map} +0 -0
  315. /package/dist/{registry-MUSL4AW6.js.map → registry-RISV7IDZ.js.map} +0 -0
  316. /package/dist/{registry-RON4WHAP.js.map → registry-ZE35A7WC.js.map} +0 -0
  317. /package/dist/{request-withdrawal-FT3ORAWN.js.map → request-withdrawal-KXVTQKR5.js.map} +0 -0
  318. /package/dist/{reveal-T34ADTPY.js.map → reveal-HY7DZST4.js.map} +0 -0
  319. /package/dist/{revoke-HC7WG3HE.js.map → revoke-J473JJ22.js.map} +0 -0
  320. /package/dist/{signer-CTWOH6KT.js.map → signer-XLUKCCH3.js.map} +0 -0
  321. /package/dist/{stale-T3V7XEOB.js.map → stale-U3WO5MYN.js.map} +0 -0
  322. /package/dist/{storage-LLNLPWWB.js.map → storage-IQONEOYY.js.map} +0 -0
  323. /package/dist/{verify-7XWHJWUN.js.map → verify-JEIXSK5U.js.map} +0 -0
  324. /package/dist/{walk-G3NFEP5L.js.map → walk-BF36V4SR.js.map} +0 -0
  325. /package/dist/{withdraw-accessible-ANSVG6XG.js.map → withdraw-accessible-TYTA23XH.js.map} +0 -0
@@ -28,17 +28,19 @@
28
28
  * write set can't express "this key changes twice in sequence."
29
29
  * 4. Every touched collection reports `_txAtomicSafe(op.type)` — see that
30
30
  * method's doc comment on `Collection` for what it excludes and why.
31
- * Note it also excludes a collection with live user write-hooks or an
32
- * `afterPut`/`afterDelete` bus handler: both fire inside `Collection.put()`
33
- * / `.delete()`, the wrappers the atomic path bypasses, and a `beforeWrite`
34
- * hook may REFUSE a write (#906).
35
- * Delete in particular gates on `refEnforcer !== undefined` rather than
36
- * a `RefRegistry.getInbound()` lookup: `Vault.enforceRefsOnDelete`
37
- * cascades from THREE sources (lookup-ref edges, classic inbound refs,
38
- * managed-link `onDelete`), and only the blanket check is at least as
39
- * strict as all three a `getInbound`-only check would be narrower
40
- * and wrongly admit unsafe atomic deletes (see `with-shape/links/
41
- * vault-facade.ts` `enforceRefsOnDelete`, lines ~180-263).
31
+ * #931: of the wrapper-level write signals, only a live `onBeforeWrite`
32
+ * hook still excludes it may REFUSE a write, which only
33
+ * `Collection.put()`/`.delete()` honors. After-hooks and the
34
+ * `afterPut`/`afterDelete` observe bus are refusal-free observers, so
35
+ * the atomic path fires them itself per leg post-finalize
36
+ * (`Collection._fireAtomicAfterWrite`) instead of forfeiting the batch.
37
+ * Delete gates on the enforcer's `_deleteCascadesPossible(name)` (#922):
38
+ * `Vault.enforceRefsOnDelete` cascades from THREE sources (lookup-ref
39
+ * edges, classic inbound refs, managed-link `onDelete`), and the Vault
40
+ * predicate unions exactly those three a `getInbound`-only check would
41
+ * be narrower and wrongly admit unsafe atomic deletes, because
42
+ * `_prepareDelete` runs the cascades DURING prepare (see
43
+ * `with-shape/links/vault-facade.ts` `enforceRefsOnDelete`).
42
44
  *
43
45
  * @internal
44
46
  */
@@ -158,6 +158,19 @@ export declare class SyncEngine {
158
158
  * ordinary put. `isTombstoneShape` covers a forgotten-elsewhere record arriving as a shred;
159
159
  * `isDeleteMarker` covers an ordinary (#589) delete — both route to the SAME 'delete' action
160
160
  * (sync delete ≠ forget: freshness only, no shred/residue channel on the receiving side). */
161
+ /**
162
+ * #936 — a local-wins resolution write must SUPERSEDE the remote, never
163
+ * overwrite it in place: when the winner's `_v` does not already exceed
164
+ * the remote's (the same-`_v` push tie), re-stamp it at `remote._v + 1`.
165
+ * Without this the loser's next pull sees no delta (`_v`-based
166
+ * detection) and the peers stay silently diverged at the same version.
167
+ * `_v` is envelope metadata — AEAD-unbound, and `_vdig` is deliberately
168
+ * `_v`-independent — so the engine may restamp ciphertext. Callers must
169
+ * mirror the advanced envelope locally (`applyRemote`) so both sides
170
+ * agree. The 'merged' branch needs none of this: resolver output is
171
+ * already stamped `max(local, remote) + 1`.
172
+ */
173
+ private advancePastRemote;
161
174
  private applyRemote;
162
175
  /** Record + emit a tombstone enforcement (#590). */
163
176
  private reportErasure;
@@ -4,19 +4,19 @@ import {
4
4
  freezeSnapshotOnly,
5
5
  randomId,
6
6
  withdrawAccessibleData
7
- } from "./chunk-SFBYQMZM.js";
8
- import "./chunk-P4JO3H6R.js";
9
- import "./chunk-JEI6JJNI.js";
10
- import "./chunk-Q36YXK77.js";
11
- import "./chunk-SU6SGWXM.js";
7
+ } from "./chunk-G3ORJ3IQ.js";
8
+ import "./chunk-J7YVY7TW.js";
9
+ import "./chunk-KDWBVCIX.js";
10
+ import "./chunk-FHK6WWUE.js";
11
+ import "./chunk-623QEHDB.js";
12
12
  import "./chunk-EFJAAFBW.js";
13
- import "./chunk-35NMVJ7I.js";
14
- import "./chunk-NFZGZ4AK.js";
15
- import "./chunk-QJNCB5SK.js";
13
+ import "./chunk-MYSNNMJ3.js";
14
+ import "./chunk-L67H6FAQ.js";
15
+ import "./chunk-GIGLOQL7.js";
16
16
  import "./chunk-LP7BEXCT.js";
17
- import "./chunk-AKKRXT23.js";
17
+ import "./chunk-RPWMDIGK.js";
18
18
  import "./chunk-77AEMXFA.js";
19
- import "./chunk-QZWTRENR.js";
19
+ import "./chunk-AR5D76T2.js";
20
20
  import "./chunk-PZ5AY32C.js";
21
21
  export {
22
22
  FROZEN_SNAPSHOTS_COLLECTION,
@@ -25,4 +25,4 @@ export {
25
25
  randomId,
26
26
  withdrawAccessibleData
27
27
  };
28
- //# sourceMappingURL=withdraw-accessible-ANSVG6XG.js.map
28
+ //# sourceMappingURL=withdraw-accessible-TYTA23XH.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy-db/hub",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Zero-knowledge, offline-first, encrypted document store — core library with AES-256-GCM, PBKDF2, multi-user keyring, and sync engine",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
@@ -208,14 +208,14 @@
208
208
  "node": ">=22.0.0"
209
209
  },
210
210
  "dependencies": {
211
- "@noy-db/attestation": "0.4.0"
211
+ "@noy-db/attestation": "0.5.0"
212
212
  },
213
213
  "devDependencies": {
214
214
  "@types/node": "^22.0.0",
215
215
  "esbuild": "^0.25.0",
216
216
  "zod": "^4.0.0",
217
217
  "zod-to-json-schema": "^3.25.2",
218
- "@noy-db/on-shamir": "0.4.0"
218
+ "@noy-db/on-shamir": "0.5.0"
219
219
  },
220
220
  "peerDependencies": {
221
221
  "zod-to-json-schema": "^3.25.0"
@@ -1,20 +0,0 @@
1
- import {
2
- UserApi,
3
- createUserApi
4
- } from "./chunk-SF2ZIRD6.js";
5
- import "./chunk-2BET5QTS.js";
6
- import "./chunk-SU6SGWXM.js";
7
- import "./chunk-EFJAAFBW.js";
8
- import "./chunk-35NMVJ7I.js";
9
- import "./chunk-NFZGZ4AK.js";
10
- import "./chunk-QJNCB5SK.js";
11
- import "./chunk-LP7BEXCT.js";
12
- import "./chunk-AKKRXT23.js";
13
- import "./chunk-77AEMXFA.js";
14
- import "./chunk-QZWTRENR.js";
15
- import "./chunk-PZ5AY32C.js";
16
- export {
17
- UserApi,
18
- createUserApi
19
- };
20
- //# sourceMappingURL=api-SI2IVBQO.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-commit/tx/atomic-eligibility.ts","../src/kernel/best-effort-revert.ts","../src/with-commit/tx/transaction.ts"],"sourcesContent":["/**\n * #893/#906-prep — the atomic-commit eligibility gate.\n *\n * `runTransaction` (Task 5) consults `canCommitAtomically` right after the\n * body returns, to decide whether the whole staged batch can be prepared and\n * submitted as ONE `store.tx(ops)` call instead of the per-op abortable\n * path (Phase 1 pre-flight + Phase 2 Collection-layer execute + Phase 3\n * best-effort revert — see `transaction.ts`'s module doc).\n *\n * Pure decision logic: no side effects, no store reads. Every input is\n * already sitting on `db` / `ctx`.\n *\n * ALL of the following must hold. (Commit-time changeset invariants are NOT a\n * condition: that phase lives after Phase 2 in `runTransaction` and runs\n * unchanged on either path — a failing invariant reverts the atomic batch\n * through the same `ctx._executed` plan.)\n *\n * 1. The store declares `capabilities.txAtomic === true` AND implements\n * `tx()`. Both — mirrors the pairing rule `bestEffortRevert` already\n * enforces (`kernel/best-effort-revert.ts:78`): an undeclared `tx()` is\n * never used, even if present.\n * 2. Not an amendment transaction (`ctx._amendment === false`) — amendments\n * need the guard-registry change-set + invariant machinery the atomic\n * path skips entirely.\n * 3. No `(vault, collection, id)` is touched twice in the batch. The\n * abortable path's Phase 1 snapshots each key once and Phase 2 replays\n * every op against that same snapshot in order; a single `store.tx()`\n * write set can't express \"this key changes twice in sequence.\"\n * 4. Every touched collection reports `_txAtomicSafe(op.type)` — see that\n * method's doc comment on `Collection` for what it excludes and why.\n * Note it also excludes a collection with live user write-hooks or an\n * `afterPut`/`afterDelete` bus handler: both fire inside `Collection.put()`\n * / `.delete()`, the wrappers the atomic path bypasses, and a `beforeWrite`\n * hook may REFUSE a write (#906).\n * Delete in particular gates on `refEnforcer !== undefined` rather than\n * a `RefRegistry.getInbound()` lookup: `Vault.enforceRefsOnDelete`\n * cascades from THREE sources (lookup-ref edges, classic inbound refs,\n * managed-link `onDelete`), and only the blanket check is at least as\n * strict as all three — a `getInbound`-only check would be narrower\n * and wrongly admit unsafe atomic deletes (see `with-shape/links/\n * vault-facade.ts` `enforceRefsOnDelete`, lines ~180-263).\n *\n * @internal\n */\n\nimport type { Noydb } from '../../kernel/noydb.js'\nimport type { TxContext } from './transaction.js'\nimport { keyOf } from './transaction.js'\n\nexport function canCommitAtomically(db: Noydb, ctx: TxContext): boolean {\n const store = db._store\n if (store.capabilities?.txAtomic !== true || typeof store.tx !== 'function') return false\n if (ctx._amendment) return false\n\n const seen = new Set<string>()\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (seen.has(key)) return false\n seen.add(key)\n }\n\n for (const op of ctx._ops) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n if (!coll._txAtomicSafe(op.type)) return false\n }\n\n return true\n}\n","/**\n * Best-effort reverse-revert — the shape shared by two independent rollback\n * paths that used to duplicate it: satellite fan-out\n * (`with-shape/satellites/fanout.ts`'s `revertAndCompensate`) and\n * multi-record transactions (`with-commit/tx/transaction.ts`'s\n * `revertExecuted`). Both revert a list of already-executed writes on\n * failure by walking them in REVERSE order and, per leg, restoring the\n * captured prior envelope straight through the raw adapter — `put(prior)`\n * when one existed, `delete` when the leg was a fresh insert — bypassing\n * the Collection layer so the revert itself doesn't re-fire\n * encryption/ledger/change-event machinery. Each leg's raw-adapter revert\n * is best-effort: a throw is swallowed so a revert-path failure never masks\n * the original error that triggered the rollback, and the loop moves on to\n * the next leg.\n *\n * An optional per-leg `compensate` callback runs immediately after a\n * successful raw-adapter revert (still inside the same try, so a throwing\n * callback is swallowed the same way as a throwing raw revert). What the\n * callback does is entirely caller-defined — satellites' fan-out fires\n * `_compensateRevertedWrite` only for legs whose write actually landed\n * (#596); with-commit's transaction executor invalidates the Collection\n * cache. Neither concern belongs here: this helper only knows the generic\n * reverse/best-effort/raw-revert shape.\n *\n * Lives in `kernel/` — not a `with-*` service — so both consumers (one a\n * gated service, `with-commit`; one an always-on schema feature,\n * `with-shape/satellites`) can import it without creating a\n * `with-* → with-*` edge, which would force either family to always bundle\n * the other and defeat the opt-in tree-shaking both are built around.\n *\n * @internal — implementation-sharing only, not part of the public surface.\n */\nimport type { EncryptedEnvelope, StoreCapabilities, TxOp } from './types.js'\n\n/** One already-executed write a revert pass needs to unwind. */\nexport interface BestEffortRevertLeg {\n readonly vaultName: string\n readonly collectionName: string\n readonly id: string\n /** Envelope captured before the write, or `null` if the id didn't exist yet. */\n readonly prior: EncryptedEnvelope | null\n}\n\n/** The subset of `NoydbStore` a raw-adapter revert needs. */\nexport interface BestEffortRevertAdapter {\n put(vaultName: string, collectionName: string, id: string, envelope: EncryptedEnvelope): Promise<void>\n delete(vaultName: string, collectionName: string, id: string): Promise<void>\n /**\n * Optional storage-layer transaction (#886). When the store declares\n * `txAtomic`, the whole revert is submitted as ONE operation instead of a\n * per-leg loop, so a crash mid-revert can no longer leave the vault\n * half-unwound.\n */\n tx?(ops: readonly TxOp[]): Promise<void>\n readonly capabilities?: StoreCapabilities\n}\n\n/**\n * Revert `executed` in reverse order via the raw adapter, best-effort.\n * `compensate`, when supplied, runs once per leg immediately after that\n * leg's own raw revert succeeds.\n */\nexport async function bestEffortRevert<T extends BestEffortRevertLeg>(\n executed: readonly T[],\n adapter: BestEffortRevertAdapter,\n compensate?: (leg: T) => Promise<void> | void,\n): Promise<void> {\n const legs = [...executed].reverse()\n\n // #886 — atomic revert when the store can do it. The legs already carry RAW\n // prior envelopes (captured pre-write), which is exactly the shape `tx()`\n // wants, so this needs none of the Collection-layer machinery that makes\n // delegating the FORWARD write path a much larger job.\n //\n // Failure stays best-effort: if the store rejects the batch we fall through\n // to the per-leg loop rather than surfacing a revert-path error, because a\n // revert failure must never mask the original error that triggered it.\n if (adapter.capabilities?.txAtomic === true && typeof adapter.tx === 'function') {\n const ops: TxOp[] = legs.map(leg =>\n leg.prior !== null\n ? { type: 'put', vault: leg.vaultName, collection: leg.collectionName, id: leg.id, envelope: leg.prior }\n : { type: 'delete', vault: leg.vaultName, collection: leg.collectionName, id: leg.id },\n )\n try {\n await adapter.tx(ops)\n if (compensate) for (const leg of legs) { try { await compensate(leg) } catch { /* best-effort */ } }\n return\n } catch {\n // fall through to the per-leg path below\n }\n }\n\n for (const leg of legs) {\n try {\n if (leg.prior !== null) {\n await adapter.put(leg.vaultName, leg.collectionName, leg.id, leg.prior)\n } else {\n await adapter.delete(leg.vaultName, leg.collectionName, leg.id)\n }\n if (compensate) await compensate(leg)\n } catch {\n // best-effort — a revert-path failure must not mask the original\n // error that triggered the rollback (matches both callers' prior\n // independent implementations).\n }\n }\n}\n","/**\n * Multi-record atomic transactions.\n *\n * Lets an application stage writes across two or more collections (or\n * vaults) and commit them all-or-nothing.\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * const inv = tx.vault('acme').collection<Invoice>('invoices')\n * const pay = tx.vault('acme').collection<Payment>('payments')\n * await inv.put(invoiceId, { ...invoice, status: 'paid' })\n * await pay.put(paymentId, { invoiceId, amount, paidAt })\n * })\n * // If the body throws before returning: nothing persisted.\n * // If the body returns: all puts committed; any CAS mismatch rolls\n * // the batch back and surfaces as ConflictError.\n * ```\n *\n * ## Atomicity semantics\n *\n * Ops are buffered during the body. On body-return the hub:\n *\n * 1. **Pre-flight** — re-reads every touched envelope and enforces\n * any caller-supplied `expectedVersion`. A mismatch throws\n * `ConflictError` with *no* writes performed.\n * 2. **Execute** — calls `Collection.put()` / `.delete()` for each\n * staged op in declaration order. History snapshots, ledger\n * appends, and change events fire as normal per op.\n * 3. **Unwind on failure** — if step 2 throws mid-batch, each\n * already-committed op is reverted via the raw store (restoring\n * the captured prior envelope, or deleting if none existed). The\n * ledger is NOT rewritten — audit history preserves the partial\n * commit and the revert.\n *\n * **Atomic delegation (#906).** Steps 1–3 above describe the OCC\n * fallback. When the store declares `StoreCapabilities.txAtomic` AND\n * implements `tx()`, AND the staged batch is statically safe\n * (`canCommitAtomically` — see `atomic-eligibility.ts`), the commit\n * instead: prepares every op through `Collection._preparePut` /\n * `_prepareDelete` (encrypt, resolve the prior version, mint the #589\n * marker — no observable side effect), submits the whole write set as\n * ONE `store.tx(ops)` call with a per-leg `expectedVersion`, then\n * finalizes each op in staged order. The visible difference: history\n * snapshots, ledger entries and change events all fire AFTER the bytes\n * are durable, instead of interleaving per op.\n *\n * **Crash window.** On the OCC fallback, steps 2–3 are not a\n * storage-layer transaction — if the process dies between two executed\n * ops, the on-disk state is partial. The atomic path above closes that\n * window for the write set itself (`to-memory` and the SQL stores in\n * `noy-db-to` implement `tx()`); a crash between the batch landing and\n * the finalize loop finishing still leaves per-op side effects (history,\n * ledger, cache) incomplete. Stores that cannot commit a batch\n * atomically (file, S3) omit `tx()` and keep the fallback.\n *\n * ## Not covered\n *\n * - Cross-sync-peer atomicity. Transactions commit against the\n * primary store only; the sync engine pushes on its normal\n * schedule. For cross-peer two-phase commit use `SyncTransaction`\n * via `db.transaction(vaultName)`.\n * - Read-your-writes within the body. `tx.collection().get(id)`\n * returns the most-recently-staged value for that id when one\n * exists; if no staged op has touched the id, it reads the current\n * committed state. Version numbers returned by `get` reflect the\n * pre-transaction state (staged puts have no version yet).\n *\n * @module\n */\n\nimport type { Noydb } from '../../kernel/noydb.js'\nimport type { Vault } from '../../kernel/vault.js'\nimport type { Collection } from '../../kernel/collection.js'\nimport type { EncryptedEnvelope, TxOp } from '../../kernel/types.js'\nimport type { PreparedPut, PreparedDelete } from '../../kernel/prepared-write.js'\nimport { canCommitAtomically } from './atomic-eligibility.js'\nimport {\n AmendmentForbiddenError,\n ConflictError,\n InvariantError,\n ValidationError,\n} from '../../kernel/errors.js'\nimport { generateULID } from '../../with-pod/ulid.js'\nimport type { GuardExecutor as GuardExecutorModule } from '../../with-audit/guards/executor.js'\nimport type { LedgerEntry } from '../history/ledger/entry.js'\nimport type { TransactionInvariant } from './invariants.js'\nimport type { GuardChange, GuardContext, ReadOnlyVaultFacade } from '../../with-audit/guards/types.js'\nimport { bestEffortRevert } from '../../kernel/best-effort-revert.js'\n\n/** One op buffered inside a running `TxContext`. @internal */\nexport interface StagedOp {\n type: 'put' | 'delete'\n vaultName: string\n collectionName: string\n id: string\n record?: unknown\n expectedVersion?: number\n /**\n * Optional human-readable tag forwarded to the resulting ledger\n * entry's `reason` field. Set by callers via\n * `tx.vault(v).collection(c).put(id, record, { reason })`.\n */\n reason?: string\n}\n\n/**\n * One executed op (main staged op or recursive side-effect like a\n * derivation output) paired with the envelope captured before the write.\n * `revertExecuted` walks this array in reverse on rollback.\n * @internal\n */\nexport interface ExecutedOp {\n op: StagedOp\n priorEnvelope: EncryptedEnvelope | null\n}\n\n/**\n * Options accepted by `db.transaction({ amendment, reason }, fn)`.\n * Only the amendment variant uses these — a plain `db.transaction(fn)`\n * never sees this shape.\n */\nexport interface AmendmentTxOptions {\n /** Opt into amendment mode. Required to be `true`. */\n readonly amendment: true\n /** Human-readable rationale recorded in the ledger entry. Required. */\n readonly reason: string\n}\n\n/**\n * Transaction handle passed to the user's body. Use\n * `tx.vault(name).collection<T>(name)` to get a per-collection\n * facade; its `put`/`delete`/`get` calls stage ops against the tx.\n */\nexport class TxContext {\n /** Stable id for this transaction; shared by all writes it performs. */\n readonly txId: string = generateULID()\n /** @internal */\n readonly _ops: StagedOp[] = []\n /**\n * @internal — write log built up in Phase 2. Each entry records the\n * envelope captured BEFORE the write so a mid-batch failure can\n * restore prior state via `revertExecuted`. Side-effect writes (e.g.\n * recursive derivation outputs fired inside `Collection.put`) are\n * appended here in execution order so they roll back alongside the\n * main staged ops.\n */\n readonly _executed: ExecutedOp[] = []\n /** @internal */\n readonly _db: Noydb\n /**\n * @internal — true when this TxContext was opened in amendment\n * mode. Toggles the lazy-`beginAmendment` + role-check path on first\n * `tx.vault(name)` and unlocks the post-Phase-2 invariant + audit run.\n */\n readonly _amendment: boolean\n /** @internal — vaults that have already had `beginAmendment` called. */\n readonly _amendmentVaults = new Map<string, Vault>()\n\n /** @internal */\n constructor(db: Noydb, amendment = false) {\n this._db = db\n this._amendment = amendment\n }\n\n /** Scope subsequent `collection()` calls to the named vault. */\n vault(name: string): TxVault {\n const v = this._db.vault(name)\n if (this._amendment && !this._amendmentVaults.has(name)) {\n // Role check is per-vault. The task spec (\"only admin or owner\n // can open an amendment\") is implemented lazy-on-first-touch\n // because the role lives on the vault's keyring, and `tx.vault()`\n // is the first place we know which vault we're addressing. The\n // observable effect is identical to an eager check in the single-\n // vault case the tests exercise; multi-vault amendments check\n // each touched vault as they first appear.\n const role = v.role\n // FR-6: custodian is admin-rank for operational mutations, and an\n // amendment is an operational (data-correcting) act — not an ownership\n // meta-capability — so custodian is allowed alongside owner/admin.\n if (role !== 'admin' && role !== 'owner' && role !== 'custodian') {\n throw new AmendmentForbiddenError(v.userId, role)\n }\n // Amendments require an initialised guard registry — they\n // produce a structured invariant + change-set audit. A vault\n // opened without `guardStrategies` (or via the sync fallback\n // path) has a null registry and cannot run an amendment.\n const reg = v._getGuardRegistry()\n if (reg === null) {\n throw new ValidationError(\n `Vault \"${name}\": amendment mode requires at least one ` +\n `guardStrategy registered via createNoydb({ guardStrategies }). ` +\n `Open the vault with guardStrategies before calling ` +\n `db.transaction({ amendment: true }).`,\n )\n }\n reg.beginAmendment()\n this._amendmentVaults.set(name, v)\n }\n return new TxVault(this, v)\n }\n}\n\n/** Per-vault facade inside a running transaction. */\nexport class TxVault {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault) {\n this._ctx = ctx\n this._vault = vault\n }\n\n /** Scope subsequent op calls to the named collection. */\n collection<T>(name: string): TxCollection<T> {\n const c = this._vault.collection<T>(name)\n return new TxCollection<T>(this._ctx, this._vault, c, name)\n }\n}\n\n/** Per-collection facade inside a running transaction. */\nexport class TxCollection<T> {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n /** @internal */\n readonly _coll: Collection<T>\n /** @internal */\n readonly _name: string\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault, coll: Collection<T>, name: string) {\n this._ctx = ctx\n this._vault = vault\n this._coll = coll\n this._name = name\n }\n\n /**\n * Read the current committed value, or the most-recently-staged\n * value from the same transaction if one exists.\n */\n async get(id: string): Promise<T | null> {\n for (let i = this._ctx._ops.length - 1; i >= 0; i--) {\n const op = this._ctx._ops[i]!\n if (\n op.vaultName === this._vault.name &&\n op.collectionName === this._name &&\n op.id === id\n ) {\n if (op.type === 'delete') return null\n return op.record as T\n }\n }\n return this._coll.get(id)\n }\n\n /**\n * Stage a put. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n put(id: string, record: T, options?: { expectedVersion?: number; reason?: string }): void {\n const op: StagedOp = {\n type: 'put',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n record,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n if (options?.reason !== undefined) op.reason = options.reason\n this._ctx._ops.push(op)\n }\n\n /**\n * Stage a delete. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n delete(id: string, options?: { expectedVersion?: number }): void {\n const op: StagedOp = {\n type: 'delete',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n this._ctx._ops.push(op)\n }\n}\n\n/**\n * Commit plan: pre-flight check + execution + revert plan.\n *\n * @internal — driven by `withTransactions()` (via `tx/active.ts`) for\n * user-facing `db.transaction(...)` calls and by the `amendment` path\n * in `noydb.ts`. `Collection.putManyAtomic` runs its own Phase 2 loop\n * but shares the `_activeTxContext` mechanism (and the `revertExecuted`\n * helper) so nested side-effect derivation writes get registered for\n * revert alongside the bulk-put source ops.\n */\nexport async function runTransaction<T>(\n db: Noydb,\n fn: (tx: TxContext) => Promise<T> | T,\n options?: AmendmentTxOptions,\n txInvariants?: ReadonlyArray<TransactionInvariant>,\n): Promise<T> {\n // ─── Amendment-mode pre-flight ───────────────────────────────\n // `reason` is the only thing we can validate before the body runs;\n // the per-vault role check happens lazily on first `tx.vault(name)`\n // because we don't know which vaults the body will touch ahead of\n // time. Throwing here keeps the failure mode close to the call site\n // so the developer doesn't have to walk an async stack to find the\n // missing-reason mistake.\n if (options?.amendment) {\n if (typeof options.reason !== 'string' || options.reason.trim().length === 0) {\n throw new ValidationError(\n 'db.transaction({ amendment: true }) requires a non-empty `reason` string.',\n )\n }\n }\n\n const ctx = new TxContext(db, options?.amendment === true)\n const bodyResult = await fn(ctx)\n\n if (ctx._ops.length === 0) {\n // Body produced no ops. If amendment mode was active we still\n // need to close any opened windows so a subsequent (unrelated)\n // write doesn't surprise-collect into a stale change-set. Each\n // `beginAmendment` is matched by exactly one `consumeChanges`.\n if (ctx._amendment) {\n for (const v of ctx._amendmentVaults.values()) {\n // Registry is guaranteed non-null here — `tx.vault(name)`\n // threw above if it was null before adding to\n // `_amendmentVaults`.\n const reg = v._getGuardRegistry()\n if (reg !== null) {\n reg.consumeChanges()\n reg.consumeMeta()\n }\n }\n }\n return bodyResult\n }\n\n // Phase 1 — pre-flight: snapshot every touched envelope and enforce\n // any caller-supplied expectedVersion. Same (vault, coll, id) touched\n // more than once in one tx snapshots only the *initial* committed\n // state; the in-order replay in Phase 2 takes care of successor ops.\n const priorEnvelopes = new Map<string, EncryptedEnvelope | null>()\n const store = db._store\n\n // Commit-time changeset invariants need PLAINTEXT prior records\n // for `before`, but `priorEnvelopes` holds ENCRYPTED envelopes. So for\n // ops in a watched scope we additionally decrypt the prior record here,\n // in Phase 1, BEFORE Phase 2 overwrites it. Snapshots only the initial\n // committed state per (vault, coll, id), matching the envelope snapshot.\n const invariants = txInvariants ?? []\n const watchedScopes = new Set(invariants.map(i => i.scope))\n const plainBefore = new Map<string, unknown>()\n\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (!priorEnvelopes.has(key)) {\n const env = await store.get(op.vaultName, op.collectionName, op.id)\n priorEnvelopes.set(key, env)\n }\n if (watchedScopes.has(op.collectionName) && !plainBefore.has(key)) {\n const prior = await db\n .vault(op.vaultName)\n .collection(op.collectionName)\n .get(op.id)\n plainBefore.set(key, prior ?? null)\n }\n if (op.expectedVersion !== undefined) {\n const env = priorEnvelopes.get(key) ?? null\n const actual = env?._v ?? 0\n if (actual !== op.expectedVersion) {\n throw new ConflictError(\n actual,\n `Transaction pre-flight: ${op.vaultName}/${op.collectionName}/${op.id} ` +\n `expected v${op.expectedVersion}, found v${actual}`,\n )\n }\n }\n }\n\n // Phase 2 — execute via the Collection layer so history snapshots,\n // ledger entries, and change events fire normally. We capture each\n // successful op so a mid-batch throw can revert in Phase 3.\n //\n // `_activeTxContext` is published on the Noydb instance for the\n // duration of Phase 2 so recursive writes triggered inside\n // `Collection.put` (today: eager derivation outputs) can register\n // their own envelopes onto `ctx._executed` and roll back alongside\n // the main staged ops. The `finally` clears it before the\n // amendment commit phase runs.\n db._setActiveTxContext(ctx)\n try {\n if (canCommitAtomically(db, ctx)) {\n // #906 — the whole batch goes to the store as ONE `tx()` write set.\n // Tracked here because the atomic path bypasses `Collection.put()`,\n // which is where an ordinary write enters the queue: without this,\n // `hub.writeQueue.pending` would read false for the entire commit.\n // One tracked unit, not one per op — the batch IS one logical write.\n await db._writeQueueTracker.track(() => commitAtomicBatch(db, ctx, priorEnvelopes))\n } else {\n try {\n for (const op of ctx._ops) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n const key = keyOf(op)\n const prior = priorEnvelopes.get(key) ?? null\n // Record the revert plan BEFORE the call so a mid-`coll.put` throw\n // (e.g. strict-mode derivation failure firing after `store.put`\n // has already committed the envelope) still has its source write\n // reverted. `revertExecuted` is best-effort: putting prior back is\n // idempotent when the failing op never actually wrote, and\n // `_invalidateCacheEntry` is a no-op when the collection isn't\n // hydrated.\n ctx._executed.push({ op, priorEnvelope: prior })\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await coll.put(op.id, op.record as any, op.reason !== undefined ? { reason: op.reason } : undefined)\n } else {\n await coll.delete(op.id)\n }\n }\n } catch (err) {\n // Phase 3 — best-effort revert. See helper docstring.\n await revertExecuted(ctx._executed, store, db)\n // Drain amendment windows so the next transaction starts clean.\n if (ctx._amendment) {\n for (const v of ctx._amendmentVaults.values()) {\n const reg = v._getGuardRegistry()\n if (reg !== null) {\n reg.consumeChanges()\n reg.consumeMeta()\n }\n }\n }\n throw err\n }\n }\n } finally {\n db._clearActiveTxContext(ctx)\n }\n\n // ─── Amendment commit phase (only if amendment === true) ────\n // Body succeeded — now run each touched vault's invariants over the\n // collected change-set, then append a structured ledger entry. If\n // any invariant throws, treat it exactly like a mid-Phase-2 failure:\n // revert every executed op and re-throw the InvariantError.\n if (ctx._amendment) {\n // Lazy-load GuardExecutor at the dispatch site — keeps the floor\n // bundle free of the guards service when amendments aren't used.\n // Mirrors the deferred-load pattern from elsewhere in this module.\n const { GuardExecutor } = (await import('../../with-audit/guards/executor.js')) as {\n GuardExecutor: typeof GuardExecutorModule\n }\n try {\n for (const [vaultName, v] of ctx._amendmentVaults) {\n const registry = v._getGuardRegistry()\n // Registry is guaranteed non-null at this point — the\n // `tx.vault(name)` path that populates `_amendmentVaults`\n // throws if the registry is null. The defensive check here\n // is for TypeScript's narrowing.\n if (registry === null) continue\n const changesByCollection = registry.consumeChanges()\n const meta = registry.consumeMeta()\n if (changesByCollection.size === 0) continue\n\n const readOnlyVault = v._getReadOnlyFacade()\n if (readOnlyVault === null) continue\n\n // Build the invariant ctx once per vault — it's the same shape\n // every guard sees on the normal `check` path, just with a\n // synthetic `existing: null` (invariants get the full change\n // set in their first parameter; `existing` is a per-record\n // concept that doesn't apply here).\n const invariantsPassed: string[] = []\n for (const [collection, changes] of changesByCollection) {\n const guards = registry.guardsFor(collection).filter(g => g.amendment !== undefined)\n for (const guard of guards) {\n await GuardExecutor.runInvariant(guard, changes, {\n existing: null,\n vault: readOnlyVault,\n userId: v.userId,\n role: v.role,\n })\n }\n if (guards.length > 0) invariantsPassed.push(collection)\n }\n\n // Append the audit ledger entry. Silent no-op when the\n // history strategy isn't configured — the records still\n // committed, only the multi-record summary is unavailable.\n const ledger = v._getLedgerOrNull()\n if (ledger) {\n const role = v.role as 'admin' | 'owner'\n const amendment: NonNullable<LedgerEntry['amendment']> = {\n reason: options!.reason,\n role,\n changes: meta,\n invariantsPassed,\n }\n await ledger.append({\n op: 'amendment',\n collection: '',\n id: '',\n version: 0,\n actor: v.userId,\n // No payload to hash — the per-record entries already\n // captured `payloadHash` at their own append time. We use\n // a sha256 of the canonical reason string so the field is\n // populated with something deterministic and non-empty.\n payloadHash: '',\n amendment,\n })\n }\n void vaultName\n }\n } catch (err) {\n await revertExecuted(ctx._executed, store, db)\n throw err instanceof InvariantError ? err : new InvariantError(\n err instanceof Error ? err.message : `invariant violated: ${String(err)}`,\n )\n }\n }\n\n // ─── Commit-time changeset invariant phase ───────────\n // Runs for BOTH ordinary and amendment transactions (placed after the\n // amendment phase so an amendment commit is still subject to these\n // set-level constraints). Assemble the changeset from the executed\n // staged ops, deduped to the LAST write per (vault, coll, id) while\n // preserving write order, then group `GuardChange` by collection\n // (scope) and run each matching invariant. A throw mirrors the\n // amendment-phase failure mode exactly: revert every executed op and\n // re-throw as `InvariantError`.\n if (invariants.length > 0) {\n // Dedup ctx._ops to the last write per key, preserving first-seen\n // (write) order so the changeset is stable and order-meaningful.\n const lastOp = new Map<string, StagedOp>()\n const order: string[] = []\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (!lastOp.has(key)) order.push(key)\n lastOp.set(key, op)\n }\n\n // Group {before, after} pairs by collection name (the invariant\n // scope). `before` is the plaintext prior captured in Phase 1 (null\n // for inserts / unwatched — only watched scopes were captured, and\n // every grouped key belongs to a watched scope). `after` is the\n // written record, null for a delete.\n const changesByScope = new Map<string, GuardChange<unknown>[]>()\n // Parallel map: scope → the vault name of its (last-seen) op, used to\n // build the per-invariant read-only ctx (facade + userId + role).\n const scopeVault = new Map<string, string>()\n for (const key of order) {\n const op = lastOp.get(key)!\n if (!watchedScopes.has(op.collectionName)) continue\n const before = plainBefore.get(key) ?? null\n const after = op.type === 'delete' ? null : (op.record ?? null)\n const change = { before, after } as GuardChange<unknown>\n const arr = changesByScope.get(op.collectionName)\n if (arr) arr.push(change)\n else changesByScope.set(op.collectionName, [change])\n\n // Stash the vault name alongside so we can build a per-vault ctx.\n // (All ops in a scope group could span vaults; we resolve the\n // vault per change below via a parallel map keyed the same way.)\n scopeVault.set(op.collectionName, op.vaultName)\n }\n\n try {\n for (const inv of invariants) {\n const changes = changesByScope.get(inv.scope)\n if (changes === undefined || changes.length === 0) continue\n const vaultName = scopeVault.get(inv.scope)!\n const v = db.vault(vaultName)\n // Prefer the real read-only facade so the invariant can read\n // sibling collections; fall back to a minimal read-only stub.\n const facade: ReadOnlyVaultFacade =\n v._getReadOnlyFacade() ?? {\n collection<R = unknown>(name: string) {\n const c = v.collection<R>(name)\n return {\n get: (id: string) => c.get(id),\n list: () => c.list(),\n query: () => c.query(),\n }\n },\n }\n const ctxForInv: GuardContext<unknown> = {\n existing: null,\n vault: facade,\n userId: v.userId,\n role: v.role,\n }\n await inv.check(changes, ctxForInv)\n }\n } catch (err) {\n await revertExecuted(ctx._executed, store, db)\n throw err instanceof InvariantError ? err : new InvariantError(\n err instanceof Error ? err.message : `invariant violated: ${String(err)}`,\n )\n }\n }\n\n return bodyResult\n}\n\n/**\n * One prepared leg of an atomic batch: the `store.tx()` op to submit plus the\n * carrier its finalize half needs.\n * @internal\n */\ninterface AtomicLeg {\n readonly op: StagedOp\n readonly coll: Collection<unknown>\n readonly txOp: TxOp\n readonly prepared: PreparedPut<unknown> | PreparedDelete<unknown>\n}\n\n/**\n * #906 — the atomic commit path: prepare every staged op, submit the whole\n * write set as ONE `store.tx()` call, then finalize each op in staged order.\n *\n * Only ever reached through `canCommitAtomically` (`atomic-eligibility.ts`),\n * whose exclusions are what make this safe — no CRDT, no refs, no\n * derivation/MV source, no unique constraints, no amendment, no id touched\n * twice. Do not call it without that blessing.\n *\n * @internal\n */\nasync function commitAtomicBatch(\n db: Noydb,\n ctx: TxContext,\n priorEnvelopes: ReadonlyMap<string, EncryptedEnvelope | null>,\n): Promise<void> {\n const store = db._store\n const legs: AtomicLeg[] = []\n\n // ─── Prepare ───────────────────────────────────────────────────\n // Encrypt, resolve the prior version, mint the #589 marker — with zero\n // observable side effects on the collections the gate admits. A throw here\n // therefore needs no unwind: nothing has been written yet, and the caller\n // sees the refusal exactly as it would from `Collection.put()`. The revert\n // plan is recorded all the same, because a FINALIZE failure below does need\n // it (same record-before-the-call convention as the OCC loop).\n for (const op of ctx._ops) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n // The two refusals `Collection.put()` / `.delete()` assert before anything\n // else — schema-update gate + schema fence. They live in those wrappers,\n // not in the prepare halves this path calls, so assert them here, per op.\n await coll._assertWriteGates()\n const prior = priorEnvelopes.get(keyOf(op)) ?? null\n // Every leg carries CAS against the Phase-1 snapshot, so a writer landing\n // between the body returning and the batch reaching the store loses.\n const base = { vault: op.vaultName, collection: op.collectionName, id: op.id, expectedVersion: prior?._v ?? 0 }\n ctx._executed.push({ op, priorEnvelope: prior })\n if (op.type === 'put') {\n const prepared = await coll._preparePut(op.id, op.record, op.reason !== undefined ? { reason: op.reason } : undefined)\n legs.push({ op, coll, prepared, txOp: { type: 'put', ...base, envelope: prepared.envelope } })\n } else {\n const prepared = await coll._prepareDelete(op.id, false)\n if (prepared === null) {\n // Nothing to delete (no live record / already a marker / shredded) —\n // the case `_doDelete` answers with `false`. Drop the op and its\n // revert entry rather than sending a leg for it.\n ctx._executed.pop()\n continue\n }\n legs.push({\n op, coll, prepared,\n // Under sync the delete is a marker PUT at `live._v + 1` (#589);\n // without sync it is a physical removal.\n txOp: prepared.marker ? { type: 'put', ...base, envelope: prepared.marker } : { type: 'delete', ...base },\n })\n }\n }\n\n // Every op turned out to be a no-op delete — same as the OCC loop, which\n // would have written nothing either. Don't hand the store an empty batch.\n if (legs.length === 0) return\n\n // ─── The batch ─────────────────────────────────────────────────\n // Deliberately NOT inside a revert-guarded try: a rejection means the store\n // applied nothing (all-or-nothing is the capability we gated on), so there\n // is nothing to unwind and a revert pass would write over records this\n // transaction never touched. No ledger entry, history snapshot or change\n // event has fired either — every one of those lives in finalize below. The\n // error (a `ConflictError` when a leg lost its CAS) surfaces unwrapped.\n await store.tx!(legs.map(l => l.txOp))\n\n // ─── Finalize ──────────────────────────────────────────────────\n // History snapshot, ledger entry, cache/index update, change event — per op,\n // in staged order, all AFTER the bytes are durable (where the OCC loop\n // interleaves them per op).\n try {\n for (const leg of legs) {\n if (leg.op.type === 'put') await leg.coll._finalizePut(leg.prepared as PreparedPut<unknown>)\n else await leg.coll._finalizeDelete(leg.prepared as PreparedDelete<unknown>)\n }\n } catch (err) {\n // The bytes ARE durable now, so this is today's best-effort unwind over\n // the plan recorded above. No amendment window to drain — the gate\n // excludes amendment transactions.\n await revertExecuted(ctx._executed, store, db)\n throw err\n }\n}\n\n/**\n * Phase 3 helper — restore captured prior envelopes via the raw store\n * to avoid re-firing Collection-level side effects (we don't want a\n * cascade of change events undoing themselves). The ledger is left\n * as-is: each committed op appended an entry; the revert is\n * deliberately NOT recorded as a compensating entry because the\n * caller-facing contract is \"atomic or not at all,\" not \"every write\n * visible in the audit trail.\" Auditors who need the intermediate\n * state can still reconstruct it by walking the ledger through the\n * failed-tx timestamp.\n *\n * Delegates the reverse/best-effort/raw-revert shape to the shared\n * `bestEffortRevert` helper (`kernel/best-effort-revert.ts`); the cache\n * invalidation below rides along as that helper's per-leg `compensate`\n * callback, gated on `db` exactly as before.\n *\n * @internal — shared between `runTransaction` and\n * `Collection.putManyAtomic`. Both register source ops + nested\n * derivation side-effect ops onto `_executed`; this helper unwinds the\n * combined list in reverse on rollback.\n */\nexport async function revertExecuted(\n executed: ReadonlyArray<ExecutedOp>,\n store: Noydb['_store'],\n db?: Noydb,\n): Promise<void> {\n const legs = executed.map(({ op, priorEnvelope }) => ({\n vaultName: op.vaultName,\n collectionName: op.collectionName,\n id: op.id,\n prior: priorEnvelope,\n }))\n await bestEffortRevert(\n legs,\n store,\n db\n ? async (leg) => {\n // Sync the Collection-layer cache with what we just wrote at\n // the raw store. Without this, eager-mode `get` would still\n // return the rolled-back record from its in-memory map. The\n // Collection's `_invalidateCacheEntry` is a no-op when the\n // collection hasn't yet been hydrated.\n const coll = db.vault(leg.vaultName).collection(leg.collectionName)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (coll as any)._invalidateCacheEntry(leg.id)\n }\n : undefined,\n )\n}\n\n/** @internal — shared (vault, collection, id) key shape; also used by `atomic-eligibility.ts`'s duplicate-key scan. */\nexport function keyOf(op: StagedOp): string {\n return `${op.vaultName}\\x00${op.collectionName}\\x00${op.id}`\n}\n"],"mappings":";;;;;;;;;;;AAiDO,SAAS,oBAAoB,IAAW,KAAyB;AACtE,QAAM,QAAQ,GAAG;AACjB,MAAI,MAAM,cAAc,aAAa,QAAQ,OAAO,MAAM,OAAO,WAAY,QAAO;AACpF,MAAI,IAAI,WAAY,QAAO;AAE3B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,MAAM,IAAI,MAAM;AACzB,UAAM,MAAM,MAAM,EAAE;AACpB,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AAAA,EACd;AAEA,aAAW,MAAM,IAAI,MAAM;AACzB,UAAM,OAAO,GAAG,MAAM,GAAG,SAAS,EAAE,WAAW,GAAG,cAAc;AAChE,QAAI,CAAC,KAAK,cAAc,GAAG,IAAI,EAAG,QAAO;AAAA,EAC3C;AAEA,SAAO;AACT;;;ACLA,eAAsB,iBACpB,UACA,SACA,YACe;AACf,QAAM,OAAO,CAAC,GAAG,QAAQ,EAAE,QAAQ;AAUnC,MAAI,QAAQ,cAAc,aAAa,QAAQ,OAAO,QAAQ,OAAO,YAAY;AAC/E,UAAM,MAAc,KAAK;AAAA,MAAI,SAC3B,IAAI,UAAU,OACV,EAAE,MAAM,OAAO,OAAO,IAAI,WAAW,YAAY,IAAI,gBAAgB,IAAI,IAAI,IAAI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,EACR;AACF;AAuBA,eAAsB,eACpB,UACA,OACA,IACe;AACf,QAAM,OAAO,SAAS,IAAI,CAAC,EAAE,IAAI,cAAc,OAAO;AAAA,IACpD,WAAW,GAAG;AAAA,IACd,gBAAgB,GAAG;AAAA,IACnB,IAAI,GAAG;AAAA,IACP,OAAO;AAAA,EACT,EAAE;AACF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,KACI,OAAO,QAAQ;AAMb,YAAM,OAAO,GAAG,MAAM,IAAI,SAAS,EAAE,WAAW,IAAI,cAAc;AAElE,YAAO,KAAa,sBAAsB,IAAI,EAAE;AAAA,IAClD,IACA;AAAA,EACN;AACF;AAGO,SAAS,MAAM,IAAsB;AAC1C,SAAO,GAAG,GAAG,SAAS,KAAO,GAAG,cAAc,KAAO,GAAG,EAAE;AAC5D;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-commit/sequence/active.ts","../src/with-commit/sequence/strategy.ts","../src/with-commit/sequence/index.ts"],"sourcesContent":["/**\n * Enable the atomic-sequence capability.\n * Pass to `createNoydb({ sequenceStrategy: withSequence() })` to make\n * `vault.sequence('name').next()` / `.peek()` / `.seedTo()` live. The\n * {@link SequenceStore} CAS engine is statically imported here, so it is pulled\n * into the bundle only when `withSequence()` is referenced (the floor never\n * imports it).\n */\nimport type { SequenceStrategy } from './strategy.js'\nimport { SequenceStore } from './index.js'\n\nexport function withSequence(): SequenceStrategy {\n return {\n createStore(opts) {\n return new SequenceStore(opts)\n },\n }\n}\n","/**\n * Sequence capability strategy — the single on-demand factory the vault routes\n * `vault.sequence()` through to build its atomic-CAS {@link SequenceStore}. The\n * active engine ({@link withSequence}) constructs the real store (kept out of\n * the floor bundle — the store class is reached only via the opt-in\n * `active.ts` chunk); {@link NO_SEQUENCE} throws. The vault always assembles the\n * per-call {@link SequenceStoreOptions} and delegates here, so an un-opted-in\n * caller hits `NO_SEQUENCE`'s throw at `vault.sequence()`.\n *\n * Note: `vault.sequence()` is synchronous, so the factory is a plain (sync)\n * constructor — the engine is tree-shaken by reachability (only `withSequence()`\n * pulls `active.ts`, which statically imports the store), not by a dynamic\n * import. Deferred-numbering series (`withDeferredNumbering`) are a distinct\n * capability and are NOT routed through this strategy.\n * @internal\n */\nimport type { SequenceStore, SequenceStoreOptions } from './index.js'\nimport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport interface SequenceStrategy {\n createStore(opts: SequenceStoreOptions): SequenceStore\n}\n\n/**\n * No-op stub — the floor default. The capability factory throws\n * {@link SequenceNotEnabledError}; opt in with `sequenceStrategy: withSequence()`\n * in createNoydb. @internal\n */\nexport const NO_SEQUENCE: SequenceStrategy = {\n createStore(): SequenceStore {\n throw new SequenceNotEnabledError()\n },\n}\n","/**\n * Atomic sequence primitive — online-coordinated gap-free numbering.\n *\n * `vault.sequence('invoice-2026').next()` returns 1, 2, 3, … with no\n * gaps and no duplicates, even under concurrent callers. Each named\n * sequence is an independent counter record at `_sequences/<name>`,\n * incremented with an optimistic compare-and-swap retry loop — the same\n * proven pattern as the ledger head (`history/ledger/store.ts`).\n *\n * **Explicitly online-only.** Gap-free numbering requires single-authority\n * serialization, which an offline / non-CAS store cannot provide. `next()`\n * throws {@link SequenceOfflineError} unless the backing store advertises\n * `capabilities.casAtomic`. This is a deliberate, honest wall — an offline\n * writer cannot safely allocate a global sequence number.\n *\n * Note on \"gap-free\": the *sequence* is gap-free (each `next()` yields a\n * unique, +1 value). If a caller discards a value without using it, that\n * is a gap in *usage*, not in the sequence — assign each `next()` result\n * to its record in the same operation.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ConflictError, SequenceContentionError, SequenceOfflineError, ValidationError } from '../../kernel/errors.js'\n\n// Capability opt-in seam (S4): `vault.sequence()` builds its CAS store through\n// the sequenceStrategy, so it throws SequenceNotEnabledError unless opted in.\nexport { withSequence } from './active.js'\nexport { NO_SEQUENCE, type SequenceStrategy } from './strategy.js'\nexport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport const SEQUENCE_COLLECTION = '_sequences'\n// A sequence is a single hot CAS row — higher contention than a ledger\n// append. A larger budget + jittered backoff absorbs moderate concurrency;\n// a genuine burst beyond this surfaces SequenceContentionError so the\n// caller can retry / queue (the honest online-only contract).\nconst MAX_NEXT_ATTEMPTS = 16\n\ninterface SequenceState {\n value: number\n}\n\n/** Options for `SequenceHandle.next`. Deferred-numbering series use `for`; the CAS counter ignores all of these. */\nexport interface NextOptions {\n /** Deferred mode: the record id to number. Ignored by the CAS counter. */\n readonly for?: string\n /** Deferred mode: reject after this many ms if still unsealed (reserved; not yet enforced in this slice). */\n readonly timeoutMs?: number\n}\n\n/**\n * Partitioning for a CAS sequence. A partitioned sequence is an\n * independent counter scoped to one tuple of values — e.g.\n * `sequence('invoice', { partition: [2026, 'EU'] })` numbers EU-2026 invoices\n * separately from `[2026, 'US']` and from the bare `invoice` series.\n *\n * Partition components are URI-encoded (so `/`, null bytes and other\n * separators in a value can never collide with the structural separators) and\n * `'/'`-joined, then appended to the series with a null-byte (`\\x00`)\n * separator. The null byte is illegal in a plain series name, which guarantees\n * a partitioned key is always disjoint from any unpartitioned series.\n */\nexport interface SequenceOptions {\n /** Partition tuple. Each component is URI-encoded and `'/'`-joined. */\n readonly partition?: readonly (string | number)[]\n /**\n * Render template for the serial string. When set, `vault.sequence`\n * returns a {@link FormattedSequenceHandle} whose `next()` resolves to\n * `{ serial, formatted }`. Tokens:\n * - `{seq}` — the allocated integer\n * - `{seq:0N}` — zero-padded to width N (e.g. `{seq:04}` → `0001`)\n * - `{partition.i}` — the i-th `partition` component (original value)\n *\n * Any other token, or a `{partition.i}` index beyond the supplied\n * `partition`, throws `ValidationError` at `vault.sequence()` construction.\n * Per-partition reset is inherent: a new partition tuple starts at 1.\n */\n readonly format?: string\n}\n\n/**\n * A formatted sequence handle. Identical to {@link SequenceHandle}\n * except `next()` also returns the rendered `formatted` string. `peek()` /\n * `seedTo()` operate on the underlying integer counter, unchanged.\n */\nexport interface FormattedSequenceHandle {\n /** Allocate the next value and return it with its rendered serial string. */\n next(opts?: NextOptions): Promise<{ serial: number; formatted: string }>\n /** Read the current integer value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /** Set-if-greater on the underlying integer counter. See {@link SequenceHandle.seedTo}. */\n seedTo(n: number): Promise<void>\n}\n\n// Matches a single `{...}` token with no nested braces.\nconst SEQ_FORMAT_TOKEN = /\\{([^{}]*)\\}/g\nconst SEQ_PAD_TOKEN = /^seq:0(\\d+)$/\nconst SEQ_PARTITION_TOKEN = /^partition\\.(\\d+)$/\n\n/**\n * Validate a sequence `format` against the supplied partition and return a\n * pure `(serial) => string` renderer. Eager validation: every token is\n * checked now, so a bad pattern throws `ValidationError` at construction —\n * never at `next()` time.\n */\nexport function compileSequenceFormat(\n format: string,\n series: string,\n partition: readonly (string | number)[] | undefined,\n): (serial: number) => string {\n const parts = partition ?? []\n for (const m of format.matchAll(SEQ_FORMAT_TOKEN)) {\n const token = m[1] ?? ''\n if (token === 'seq') continue\n if (SEQ_PAD_TOKEN.test(token)) continue\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) {\n const idx = Number(partMatch[1])\n if (idx >= parts.length) {\n throw new ValidationError(\n `sequence(\"${series}\"): format token \"{${token}}\" references partition index ${idx}, ` +\n `but only ${parts.length} partition component(s) were supplied.`,\n )\n }\n continue\n }\n throw new ValidationError(\n `sequence(\"${series}\"): format contains unknown token \"{${token}}\". ` +\n `Accepted tokens: {seq}, {seq:0N}, {partition.i}.`,\n )\n }\n return (serial: number): string =>\n format.replace(SEQ_FORMAT_TOKEN, (full, token: string) => {\n if (token === 'seq') return String(serial)\n const padMatch = SEQ_PAD_TOKEN.exec(token)\n if (padMatch) return String(serial).padStart(Number(padMatch[1]), '0')\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) return String(parts[Number(partMatch[1])])\n return full // unreachable — validated above\n })\n}\n\n/**\n * Resolve the CAS storage key for a (series, partition) pair.\n *\n * With no partition the key is `series` verbatim. With a partition the key is\n * `${series}\\x00${parts}` where `parts` is each component passed through\n * `encodeURIComponent(String(part))` and `'/'`-joined. The null-byte separator\n * is illegal in a plain series name, so partitioned keys never collide with\n * unpartitioned ones; URI-encoding keeps any component containing `/` distinct\n * from a multi-component partition.\n *\n * @throws {ValidationError} if any partition component is empty after `String()`\n * or is a non-finite number (`NaN`, `±Infinity`).\n */\nexport function resolveSequenceKey(series: string, opts?: SequenceOptions): string {\n const partition = opts?.partition\n if (!partition || partition.length === 0) return series\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`sequence partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('sequence partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${series}\\x00${parts.join('/')}`\n}\n\nexport interface SequenceHandle {\n /** Atomically allocate and return the next value (1, 2, 3, …). Deferred series resolve at the next pass. */\n next(opts?: NextOptions): Promise<number>\n /** Read the current value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /**\n * Set-if-greater: advance the counter to at least `n`. A no-op if the\n * current value is already `>= n` (so it never rewinds), and `seedTo(0)` is\n * a no-op. Idempotent and CAS-safe under concurrent `next()` / `seedTo()`.\n *\n * Use after a bundle / CSV import to fast-forward the counter past the\n * highest imported serial, so subsequent `next()` calls cannot re-use a\n * number that is already on a record.\n *\n * Online-only: throws {@link SequenceOfflineError} on a non-CAS store.\n */\n seedTo(n: number): Promise<void>\n}\n\nasync function sleepBackoff(attempt: number): Promise<void> {\n // Exponential backoff with full jitter to break the thundering herd\n // when many writers contend on the same counter row.\n const ceil = Math.min(2 ** attempt, 32)\n const ms = Math.floor(Math.random() * ceil)\n await new Promise((r) => setTimeout(r, ms))\n}\n\n/** Per-call context the vault assembles to build a {@link SequenceStore}. */\nexport interface SequenceStoreOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\nexport class SequenceStore {\n private readonly adapter: NoydbStore\n private readonly vault: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly actor: string\n /**\n * Memoized DEK promise. The `_sequences` collection DEK is created on\n * first access; without sharing one promise, a burst of concurrent\n * `next()` calls would each trigger DEK creation and diverge (one\n * writer's ciphertext unreadable by another). One shared promise → one\n * DEK.\n */\n private dekPromise: Promise<EnclaveKey> | null = null\n\n constructor(opts: SequenceStoreOptions) {\n this.adapter = opts.adapter\n this.vault = opts.vault\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.actor = opts.actor\n }\n\n /** A handle bound to one sequence name. */\n handle(name: string): SequenceHandle {\n return {\n next: () => this.next(name),\n peek: () => this.peek(name),\n seedTo: (n) => this.seedTo(name, n),\n }\n }\n\n private assertOnline(): void {\n if (this.adapter.capabilities?.casAtomic !== true) {\n throw new SequenceOfflineError()\n }\n }\n\n private dek(): Promise<EnclaveKey> {\n if (!this.dekPromise) this.dekPromise = this.getDEK(SEQUENCE_COLLECTION)\n return this.dekPromise\n }\n\n private async read(name: string): Promise<{ env: EncryptedEnvelope | null; value: number }> {\n const env = await this.adapter.get(this.vault, SEQUENCE_COLLECTION, name)\n if (!env) return { env: null, value: 0 }\n const json = this.encrypted ? await openEnvelopeJson(env, await this.dek()) : env._data\n const state = JSON.parse(json) as SequenceState\n return { env, value: state.value }\n }\n\n private async encryptState(state: SequenceState, version: number): Promise<EncryptedEnvelope> {\n const json = JSON.stringify(state)\n if (!this.encrypted) {\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: '', _data: json, _by: this.actor }\n }\n const { iv, data } = await encrypt(json, await this.dek())\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: iv, _data: data, _by: this.actor }\n }\n\n async peek(name: string): Promise<number> {\n return (await this.read(name)).value\n }\n\n async next(name: string): Promise<number> {\n this.assertOnline()\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n const nextValue = value + 1\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: nextValue }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return nextValue\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n\n async seedTo(name: string, n: number): Promise<void> {\n this.assertOnline()\n if (n <= 0) return // set-if-greater: 0 (and any non-positive seed) is a no-op\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n if (value >= n) return // already at or past the floor — no write, idempotent\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: n }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWO,SAAS,eAAiC;AAC/C,SAAO;AAAA,IACL,YAAY,MAAM;AAChB,aAAO,IAAI,cAAc,IAAI;AAAA,IAC/B;AAAA,EACF;AACF;;;ACWO,IAAM,cAAgC;AAAA,EA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;AACF,cAAM,KAAK,QAAQ,IAAI,KAAK,OAAO,qBAAqB,MAAM,UAAU,eAAe;AACvF,eAAO;AAAA,MACT,SAAS,KAAK;AACZ,YAAI,eAAe,eAAe;AAChC,yBAAe;AACf,cAAI,UAAU,oBAAoB,EAAG,OAAM,aAAa,OAAO;AAC/D;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AACA,SAAK;AACL,UAAM,IAAI,wBAAwB,MAAM,iBAAiB;AAAA,EAC3D;AAAA,EAEA,MAAM,OAAO,MAAc,GAA0B;AACnD,SAAK,aAAa;AAClB,QAAI,KAAK,EAAG;AACZ,QAAI;AACJ,aAAS,UAAU,GAAG,UAAU,mBAAmB,WAAW;AAC5D,YAAM,EAAE,KAAK,MAAM,IAAI,MAAM,KAAK,KAAK,IAAI;AAC3C,UAAI,SAAS,EAAG;AAChB,YAAM,kBAAkB,KAAK,MAAM;AACnC,YAAM,WAAW,MAAM,KAAK,aAAa,EAAE,OAAO,EAAE,GAAG,kBAAkB,CAAC;AAC1E,UAAI;AACF,cAAM,KAAK,QAAQ,IAAI,KAAK,OAAO,qBAAqB,MAAM,UAAU,eAAe;AACvF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,eAAe,eAAe;AAChC,yBAAe;AACf,cAAI,UAAU,oBAAoB,EAAG,OAAM,aAAa,OAAO;AAC/D;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AACA,SAAK;AACL,UAAM,IAAI,wBAAwB,MAAM,iBAAiB;AAAA,EAC3D;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-sync/presence.ts","../src/with-sync/period-scope.ts","../src/with-sync/engine.ts","../src/with-sync/transaction.ts"],"sourcesContent":["/**\n * Presence handle — real-time awareness of who is viewing/editing a collection.\n * encrypted ephemeral channel keyed by collection DEK via HKDF.\n *\n * The presence key is derived from the collection DEK so:\n * - The adapter never learns user identities from presence payloads.\n * - Presence rotates automatically when the DEK rotates (revoked users\n * can no longer participate after a DEK rotation).\n *\n * Two transport strategies:\n * 1. **Pub/sub** (real-time): used when the adapter implements\n * `presencePublish` and `presenceSubscribe`.\n * 2. **Storage-poll** (fallback): presence records are written to a\n * reserved `_presence_<collection>` collection on the sync adapter\n * (if available) or local adapter, and polled periodically.\n */\n\nimport type { NoydbStore, PresencePeer } from '../kernel/types.js'\nimport { encrypt, decrypt, generateIV, bufferToBase64, derivePresenceKey, type EnclaveKey } from '../kernel/enclave/index.js'\n\n/** Options for constructing a PresenceHandle. @internal */\nexport interface PresenceHandleOpts {\n /** Local adapter for storage-poll fallback. */\n adapter: NoydbStore\n /** Remote (sync) adapter — preferred for broadcasting presence if available. */\n syncAdapter?: NoydbStore\n /** Vault name — used as part of the channel and storage key. */\n vault: string\n /** Collection name — used as HKDF `info` and channel suffix. */\n collectionName: string\n /** Calling user's ID, embedded unencrypted in storage records. */\n userId: string\n /** Whether encryption is active. When false, presence payloads are stored as JSON. */\n encrypted: boolean\n /** Callback that resolves the collection DEK (used to derive the presence key). */\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n /** How long (ms) before a peer's presence is considered stale. Default: 30_000. */\n staleMs?: number\n /** Poll interval (ms) for the storage-poll fallback. Default: 5_000. */\n pollIntervalMs?: number\n}\n\n/**\n * Internal storage envelope for the storage-poll fallback.\n * Written to `_presence_<collection>` as `{ userId, lastSeen, iv, data }`.\n */\ninterface StoragePresenceRecord {\n userId: string\n lastSeen: string\n iv: string // base64 AES-GCM IV (empty when not encrypted)\n data: string // base64 ciphertext or JSON string when not encrypted\n}\n\n/** Presence handle for a single collection. */\nexport class PresenceHandle<P> {\n private readonly adapter: NoydbStore\n private readonly syncAdapter: NoydbStore | undefined\n private readonly vault: string\n private readonly collectionName: string\n private readonly userId: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly staleMs: number\n private readonly pollIntervalMs: number\n private readonly channel: string\n private readonly storageCollection: string\n\n private presenceKey: EnclaveKey | null = null\n private subscribers: Array<(peers: PresencePeer<P>[]) => void> = []\n private unsubscribePubSub: (() => void) | null = null\n private pollTimer: ReturnType<typeof setInterval> | null = null\n private stopped = false\n\n constructor(opts: PresenceHandleOpts) {\n this.adapter = opts.adapter\n this.syncAdapter = opts.syncAdapter\n this.vault = opts.vault\n this.collectionName = opts.collectionName\n this.userId = opts.userId\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.staleMs = opts.staleMs ?? 30_000\n this.pollIntervalMs = opts.pollIntervalMs ?? 5_000\n // Channel used by pub/sub adapters — vault-scoped so two collections\n // in the same vault don't bleed into each other's presence channels.\n this.channel = `${opts.vault}:${opts.collectionName}:presence`\n // Reserved collection name for the storage-poll fallback.\n this.storageCollection = `_presence_${opts.collectionName}`\n }\n\n /**\n * Announce yourself (or update your cursor/status).\n * Encrypts `payload` with the presence key and publishes it.\n */\n async update(payload: P): Promise<void> {\n if (this.stopped) return\n\n const key = await this.getPresenceKey()\n const now = new Date().toISOString()\n const plaintext = JSON.stringify({ userId: this.userId, lastSeen: now, payload })\n let encryptedPayload: string\n\n if (this.encrypted && key) {\n const iv = generateIV()\n const ivB64 = bufferToBase64(iv)\n const { data } = await encrypt(plaintext, key)\n encryptedPayload = JSON.stringify({ iv: ivB64, data })\n } else {\n encryptedPayload = plaintext\n }\n\n // Pub/sub path — publish to any adapter that supports it\n const pubAdapter = this.getPubSubAdapter()\n if (pubAdapter?.presencePublish) {\n await pubAdapter.presencePublish(this.channel, encryptedPayload)\n }\n\n // Storage-poll path — write a record to the storage adapter\n await this.writeStorageRecord(payload, now)\n }\n\n /**\n * Subscribe to presence updates. The callback receives a filtered, decrypted\n * list of all currently-active peers (excluding yourself, excluding stale).\n *\n * Returns an unsubscribe function. Also call `stop()` to release all resources.\n */\n subscribe(cb: (peers: PresencePeer<P>[]) => void): () => void {\n if (this.stopped) return () => {}\n\n this.subscribers.push(cb)\n\n // Start pub/sub listener on first subscriber\n if (this.subscribers.length === 1) {\n this.startListening()\n }\n\n return () => {\n this.subscribers = this.subscribers.filter(s => s !== cb)\n if (this.subscribers.length === 0) this.stopListening()\n }\n }\n\n /** Stop all listening and clear resources. */\n stop(): void {\n this.stopped = true\n this.stopListening()\n this.subscribers = []\n }\n\n // ─── Private ────────────────────────────────────────────────────────\n\n private async getPresenceKey(): Promise<EnclaveKey | null> {\n if (!this.encrypted) return null\n if (!this.presenceKey) {\n try {\n const dek = await this.getDEK(this.collectionName)\n this.presenceKey = await derivePresenceKey(dek, this.collectionName)\n } catch {\n // no-op — presence degrades gracefully if crypto fails\n }\n }\n return this.presenceKey\n }\n\n private getPubSubAdapter(): NoydbStore | undefined {\n // Prefer the sync adapter (it broadcasts to other devices)\n if (this.syncAdapter?.presencePublish) return this.syncAdapter\n if (this.adapter.presencePublish) return this.adapter\n return undefined\n }\n\n private startListening(): void {\n const pubAdapter = this.getPubSubAdapter()\n\n if (pubAdapter?.presenceSubscribe) {\n // Real-time pub/sub path\n this.unsubscribePubSub = pubAdapter.presenceSubscribe(\n this.channel,\n (encryptedPayload) => { void this.handlePubSubMessage(encryptedPayload) },\n )\n } else {\n // Storage-poll fallback\n this.pollTimer = setInterval(\n () => { void this.pollStoragePresence() },\n this.pollIntervalMs,\n )\n // Kick off an immediate poll\n void this.pollStoragePresence()\n }\n }\n\n private stopListening(): void {\n if (this.unsubscribePubSub) {\n this.unsubscribePubSub()\n this.unsubscribePubSub = null\n }\n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = null\n }\n }\n\n private async handlePubSubMessage(encryptedPayload: string): Promise<void> {\n try {\n const peer = await this.decryptPresencePayload(encryptedPayload)\n if (!peer || peer.userId === this.userId) return\n\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n if (peer.lastSeen < cutoff) return\n\n // Deliver only this new peer to subscribers; a full snapshot poll follows\n // on next interval. For pub/sub, we could maintain a map of active peers,\n // but for simplicity: emit a snapshot read from storage.\n await this.pollStoragePresence()\n } catch {\n // Decrypt failure — stale key or tampered payload, ignore\n }\n }\n\n private async decryptPresencePayload(\n encryptedPayload: string,\n ): Promise<{ userId: string; lastSeen: string; payload: P } | null> {\n const key = await this.getPresenceKey()\n\n if (!this.encrypted || !key) {\n return JSON.parse(encryptedPayload) as { userId: string; lastSeen: string; payload: P }\n }\n\n const { iv: ivB64, data } = JSON.parse(encryptedPayload) as { iv: string; data: string }\n const plaintext = await decrypt(ivB64, data, key)\n return JSON.parse(plaintext) as { userId: string; lastSeen: string; payload: P }\n }\n\n private async writeStorageRecord(payload: P, now: string): Promise<void> {\n const key = await this.getPresenceKey()\n const plaintext = JSON.stringify(payload)\n let iv = ''\n let data: string\n\n if (this.encrypted && key) {\n const ivBytes = generateIV()\n iv = bufferToBase64(ivBytes)\n const result = await encrypt(plaintext, key)\n data = result.data\n } else {\n data = plaintext\n }\n\n const record: StoragePresenceRecord = { userId: this.userId, lastSeen: now, iv, data }\n const json = JSON.stringify(record)\n\n // Use the sync adapter if available (so other devices can read it);\n // fall back to local adapter.\n const storeAdapter = this.syncAdapter ?? this.adapter\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: now,\n _iv: '',\n _data: json,\n }\n try {\n await storeAdapter.put(\n this.vault,\n this.storageCollection,\n this.userId,\n envelope,\n )\n } catch {\n // Presence write failure is non-fatal — the user is still present locally\n }\n }\n\n private async pollStoragePresence(): Promise<void> {\n if (this.stopped || this.subscribers.length === 0) return\n\n try {\n const storeAdapter = this.syncAdapter ?? this.adapter\n const ids = await storeAdapter.list(this.vault, this.storageCollection)\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n const peers: PresencePeer<P>[] = []\n\n for (const id of ids) {\n if (id === this.userId) continue // skip ourselves\n const envelope = await storeAdapter.get(this.vault, this.storageCollection, id)\n if (!envelope) continue\n\n const record = JSON.parse(envelope._data) as StoragePresenceRecord\n if (record.lastSeen < cutoff) continue\n\n let peerPayload: P\n if (this.encrypted && this.presenceKey && record.iv) {\n const plaintext = await decrypt(record.iv, record.data, this.presenceKey)\n peerPayload = JSON.parse(plaintext) as P\n } else {\n peerPayload = JSON.parse(record.data) as P\n }\n\n peers.push({ userId: record.userId, payload: peerPayload, lastSeen: record.lastSeen })\n }\n\n for (const cb of this.subscribers) {\n cb(peers)\n }\n } catch {\n // Poll failure is non-fatal\n }\n }\n}\n","/**\n * #807 — period-scoped pull support for the `SyncEngine` (thin-client\n * bootstrap: first sync pulls the current period + the period summaries;\n * historical periods backfill on demand via `pull({ periods: ['<name>'] })`).\n *\n * ## Membership law\n *\n * The engine only ever sees ciphertext envelopes, so period membership at\n * the sync tier is by write-time `_ts` against the closed periods' windows\n * (`periodExclusiveUpperBound`) — the SAME store-tier law freeze (#604) and\n * archive (#613) use, NOT the business-date (`dateField`) seal the write\n * guard applies inside the trust boundary. A late-booked record (in-period\n * business date, current write-time) therefore syncs with the current\n * period — mirroring how it archives at the NEXT period's archive.\n *\n * Closed periods partition the timeline by their exclusive upper bounds:\n * the earliest closed period's window is unbounded below (a close seals\n * everything at-or-before its `endDate`), each later one starts at its\n * predecessor's bound, and the CURRENT window is everything at-or-after\n * the latest closed bound (everything, when no period was ever closed).\n *\n * ## What a period filter can never drop\n *\n * - **Period summaries** (`_periods` + freeze/archive/target-purge\n * companions) — the navigation index; always pulled in full, exempt from\n * every filter (`collections`, `periods`, `modifiedSince`).\n * - **Delete markers and tombstones** — an erasure or delete must never be\n * skipped by partial sync (the #589/#590 law, mirroring the\n * `modifiedSince` exemption). This is what makes a device that never\n * pulled period P converge instead of resurrecting P's deleted records\n * when it later backfills.\n * - **Reserved lookups** (`_dict_*`/`_lookup_*`) — vocabulary/config rows\n * are not period-partitioned data; their explicit pull loop is exempt.\n *\n * Push is NEVER period-filtered — `PushOptions` has no `periods` member at\n * all; a thin client's writes always flow up in full.\n */\nimport type { EncryptedEnvelope } from '../kernel/types.js'\nimport { ValidationError } from '../kernel/errors.js'\nimport { isTombstoneShape, isDeleteMarker } from '../kernel/enclave/index.js'\nimport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n periodExclusiveUpperBound,\n} from '../with-audit/periods/window.js'\n\nexport { PERIODS_COLLECTION }\n\n/**\n * The reserved period-metadata collections a period-scoped pull always\n * fetches first (phase 1, \"summaries\"): the hash-chained `_periods` index\n * plus its freeze/archive/target-purge companions.\n */\nexport const PERIOD_SUMMARY_COLLECTIONS: readonly string[] = [\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n]\n\n/** The subset of a decrypted `PeriodRecord` the window computation needs. */\nexport interface PeriodSyncRecord {\n readonly name: string\n readonly kind: 'closed' | 'opened'\n readonly endDate: string\n}\n\n/**\n * Vault-injected source of decrypted period records, wired via\n * `SyncEngine.setPeriodPullSource` (same injection pattern as\n * `setReservedLookupSource`). MUST re-read from the local store on every\n * call — the engine invokes it right after the summaries phase applied\n * freshly pulled `_periods` envelopes.\n */\nexport interface PeriodPullSource {\n periods(): Promise<readonly PeriodSyncRecord[]>\n}\n\nconst SHAPE_MSG =\n 'pull: `periods` must be an array of closed-period names, or `{ current: true }`.'\n\n/** Validate the raw `PullOptions.periods` value (runtime shape only). */\nexport function validatePeriodsOption(\n periods: unknown,\n): asserts periods is readonly string[] | { readonly current: true } {\n if (Array.isArray(periods)) {\n for (const p of periods) {\n if (typeof p !== 'string' || p.length === 0) throw new ValidationError(SHAPE_MSG)\n }\n return\n }\n if (\n typeof periods === 'object' && periods !== null &&\n (periods as { current?: unknown }).current === true &&\n Object.keys(periods).length === 1\n ) {\n return\n }\n throw new ValidationError(SHAPE_MSG)\n}\n\n/**\n * Resolve the selected `_ts` windows and return the pull-scope predicate:\n * `true` = the envelope is in scope for this pull. Tombstones and delete\n * markers are unconditionally in scope (see module doc).\n *\n * Throws `ValidationError` for a name that is not a closed period in the\n * (freshly synced) `_periods` index — a typo'd backfill must fail loudly,\n * never silently pull nothing.\n */\nexport function buildPeriodScope(\n option: readonly string[] | { readonly current: true },\n records: readonly PeriodSyncRecord[],\n): (envelope: EncryptedEnvelope) => boolean {\n const closed = records\n .filter((r) => r.kind === 'closed')\n .map((r) => ({ name: r.name, bound: periodExclusiveUpperBound(r.endDate) }))\n .sort((a, b) => a.bound.localeCompare(b.bound))\n\n let windows: ReadonlyArray<{ lower: string | null; upper: string | null }>\n if (Array.isArray(option)) {\n windows = (option as readonly string[]).map((name) => {\n const idx = closed.findIndex((c) => c.name === name)\n if (idx < 0) {\n const other = records.find((r) => r.name === name)\n throw new ValidationError(\n other\n ? `pull: period \"${name}\" is \"${other.kind}\" — only closed periods have a backfill window; use \\`{ current: true }\\` for the open period.`\n : `pull: no closed period named \"${name}\" in this vault's _periods index.`,\n )\n }\n return { lower: idx > 0 ? closed[idx - 1]!.bound : null, upper: closed[idx]!.bound }\n })\n } else {\n // { current: true } — everything at-or-after the latest closed bound\n // (everything, when no period was ever closed: with no closed periods\n // there is nothing historical to exclude, so nothing is silently dropped).\n windows = [{ lower: closed.length > 0 ? closed[closed.length - 1]!.bound : null, upper: null }]\n }\n\n return (envelope: EncryptedEnvelope): boolean => {\n if (isTombstoneShape(envelope) || isDeleteMarker(envelope)) return true\n return windows.some(\n (w) =>\n (w.lower === null || envelope._ts >= w.lower) &&\n (w.upper === null || envelope._ts < w.upper),\n )\n }\n}\n","import type {\n NoydbStore,\n DirtyEntry,\n Conflict,\n ConflictStrategy,\n CollectionConflictResolver,\n PushOptions,\n PullOptions,\n PushResult,\n PullResult,\n SyncStatus,\n EncryptedEnvelope,\n SyncMetadata,\n SyncTargetRole,\n ErasureEnforcement,\n} from '../kernel/types.js'\nimport { NOYDB_SYNC_VERSION } from '../kernel/types.js'\nimport { ConflictError, ValidationError } from '../kernel/errors.js'\nimport {\n PERIOD_SUMMARY_COLLECTIONS,\n PERIODS_COLLECTION,\n buildPeriodScope,\n validatePeriodsOption,\n type PeriodPullSource,\n} from './period-scope.js'\nimport type { NoydbEventEmitter } from '../kernel/events.js'\nimport type { SyncPolicy } from '../kernel/sync-policy.js'\nimport { SyncScheduler } from '../kernel/sync-policy.js'\nimport { isTombstoneShape, isDeleteMarker, envelopeBodySize } from '../kernel/enclave/index.js'\n\n/** #650 Task 4 (#647) — the declared reserved-lookup (`_dict_*`/`_lookup_*`) collection-name\n * registry a `SyncEngine` enumerates on pull. Explicit, not a blanket underscore-glob — other\n * `_`-prefixed namespaces keep their `loadAll`-skip semantics untouched. */\nexport interface ReservedLookupSource {\n /** Declared reserved-lookup collection names to enumerate on pull. */\n collections(): readonly string[]\n}\n\n/** Sync engine: dirty tracking, push, pull, conflict resolution, scheduling. */\nexport class SyncEngine {\n private readonly local: NoydbStore\n private readonly remote: NoydbStore\n private readonly strategy: ConflictStrategy\n private readonly emitter: NoydbEventEmitter\n private readonly vault: string\n readonly role: SyncTargetRole\n readonly label: string | undefined\n\n private dirty: DirtyEntry[] = []\n private lastPush: string | null = null\n private lastPull: string | null = null\n private loaded = false\n private autoSyncInterval: ReturnType<typeof setInterval> | null = null\n private isOnline = true\n\n /** Sync scheduler. Manages push/pull timing. */\n readonly scheduler: SyncScheduler | null\n\n /** Per-collection conflict resolvers registered by Collection instances. */\n private readonly conflictResolvers = new Map<string, CollectionConflictResolver>()\n\n /**\n * Expands a collection-name filter to include its satellite pair partner(s)\n * (spec #591 convergence rule 5b) — wired from vault satellite declaration\n * via `setPairExpander`. `undefined` when no satellite has ever been\n * declared for this vault: identity behavior, zero change for non-satellite\n * users.\n */\n private pairExpander?: (names: readonly string[]) => readonly string[]\n\n /** #598: refreshes Collection in-memory views after a sync-applied local write. Wired by the\n * vault at open. `action` (#640): `'delete'` for a pulled tombstone/delete-marker, `'put'`\n * otherwise — classified at `applyRemote`, the one choke point that holds the envelope. */\n private cacheInvalidator?: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>\n\n /** Wire the Collection-cache invalidation hook (#598). Same injection pattern as `setPairExpander`. */\n setCacheInvalidator(fn: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>): void {\n this.cacheInvalidator = fn\n }\n\n /** #638 Task 4: opens/flushes the vault's graph-dispatch touch batch around a whole `pull()`/\n * `push()` call, so N `applyRemote`d records feeding the same derivation/rollup/MV target\n * recompute once. Wired by the vault at open, mirroring `cacheInvalidator`. */\n private graphBatchController?: { begin(): void; flush(): Promise<void> }\n\n /** Wire the graph-dispatch batch controller (#638 Task 4). Same injection pattern as `setCacheInvalidator`. */\n setGraphBatchController(controller: { begin(): void; flush(): Promise<void> }): void {\n this.graphBatchController = controller\n }\n\n /** #650 Task 4 (#647): declared reserved-lookup collections `pull()` enumerates explicitly (the\n * store's `list()` does not skip `_`-prefixed names, unlike `loadAll()`). Wired by the vault at\n * open, same injection pattern as `setCacheInvalidator`/`setGraphBatchController`. */\n private reservedLookup?: ReservedLookupSource\n\n /** Wire the reserved-lookup source (#650 Task 4). */\n setReservedLookupSource(source: ReservedLookupSource): void {\n this.reservedLookup = source\n }\n\n /** #653: expands a (pair-expanded) collection-name filter to include the reserved `_dict_*`\n * collections those names depend on via their lookup fields — mirrors `pairExpander` so a\n * partial `push`/`pull({collections:[...]})` never drops the dictionary a named collection's\n * labels/membership rely on. Wired unconditionally from the vault's `dictKeyFieldRegistry` via\n * `setReservedDictExpander` (returns `[]` when the vault has no dict-backed collections); only\n * `undefined` on a standalone engine that was never vault-attached. */\n private reservedDictExpander?: (names: readonly string[]) => readonly string[]\n\n /** Wire the reserved-dict expansion function (#653). Same injection pattern as `setPairExpander`. */\n setReservedDictExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.reservedDictExpander = expander\n }\n\n /** #807: vault-injected source of decrypted period records — resolves the `_ts` windows a\n * `pull({ periods })` scopes to. Re-read AFTER the summaries phase, so a fresh device's\n * freshly pulled `_periods` index is what the windows are computed from. `undefined` on a\n * standalone engine that was never vault-attached (period-scoped pull then throws). */\n private periodPullSource?: PeriodPullSource\n\n /** Wire the period-window source (#807). Same injection pattern as `setReservedLookupSource`. */\n setPeriodPullSource(source: PeriodPullSource): void {\n this.periodPullSource = source\n }\n\n /** #807: KPI accumulator `applyRemote` feeds during a period-scoped `pull()` — pointed at the\n * active phase's counters (summaries → records) and cleared before pull returns. Approximate\n * by design: a push interleaved mid-pull on the same engine would attribute its converge\n * applies to the open phase; the counters are a download-budget KPI, not an audit source. */\n private pullByteSink: { records: number; bytes: number } | null = null\n\n constructor(opts: {\n local: NoydbStore\n remote: NoydbStore\n vault: string\n strategy: ConflictStrategy\n emitter: NoydbEventEmitter\n syncPolicy?: SyncPolicy\n role?: SyncTargetRole\n label?: string\n }) {\n this.local = opts.local\n this.remote = opts.remote\n this.vault = opts.vault\n this.strategy = opts.strategy\n this.emitter = opts.emitter\n this.role = opts.role ?? 'sync-peer'\n this.label = opts.label\n\n // Create a scheduler when the policy asks for ANY automatic behaviour.\n // #897: this used to test `push.mode !== 'manual'` alone, so a policy of\n // `{ push: manual, pull: interval }` silently got no scheduler and its pull\n // mode was ignored.\n const policy = opts.syncPolicy\n if (policy && (policy.push.mode !== 'manual' || policy.pull.mode !== 'manual')) {\n this.scheduler = new SyncScheduler(policy, {\n push: () => this.push().then(() => {}),\n // #618 — role-gate the SCHEDULER-INITIATED pull. The Noydb layer gates\n // pull-from-sink for explicit calls, but the scheduler calls the engine\n // directly and would bypass it: a backup/archive-only primary with an\n // `interval`/`on-focus` pull policy would pull ungated, reintroducing\n // #616. This guards the engine self-initiating on a timer; an explicit\n // `engine.pull()` still pulls for every role.\n // `collections` is set by a 'phased' sequence — one collection per phase.\n // A role-gated skip reports 'incomplete': nothing was pulled, so the\n // phase must not mark its collection ready.\n pull: (collections) =>\n this.role === 'sync-peer'\n ? this.pull(collections ? { collections: [...collections] } : undefined)\n // PullResult.errors accumulates WITHOUT throwing, so a partial\n // failure is only visible here — not via a rejected promise.\n .then(r => (r.errors.length === 0 ? 'complete' : 'incomplete'))\n : Promise.resolve('incomplete'),\n getDirtyCount: () => this.dirty.length,\n })\n } else {\n this.scheduler = null\n }\n }\n\n /** Start the sync scheduler. Called after vault is fully opened. */\n startScheduler(): void {\n this.scheduler?.start()\n }\n\n /** Stop the sync scheduler. Called on close. */\n stopScheduler(): void {\n this.scheduler?.stop()\n }\n\n /**\n * Register a per-collection conflict resolver.\n * Called by Collection when `conflictPolicy` is set.\n *\n * Pair-coupled (#591 rule 5b): registering for one satellite-pair member\n * registers the same resolver for both — the pair converges under one\n * resolution policy. Expands with whatever the pair-expander knows *at this\n * call*; resolvers registered before their pair existed are covered by\n * `remirrorPairResolvers` at pair-registration time.\n */\n registerConflictResolver(collection: string, resolver: CollectionConflictResolver): void {\n for (const n of this.pairExpander?.([collection]) ?? [collection]) this.conflictResolvers.set(n, resolver)\n }\n\n /**\n * Wire a satellite pair-expansion function (vault registration, #591 Task 11).\n * The closure re-reads the live `SatelliteRegistry` on every call, so pairs\n * declared after this is set are still picked up by `push`/`pull` filters.\n */\n setPairExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.pairExpander = expander\n }\n\n /**\n * Retroactively mirror per-collection conflict resolvers across a newly\n * registered satellite pair (#591 rule 5b) — covers the NORMAL declaration\n * order, where the base's `conflictPolicy` resolver was registered before\n * the satellite was declared (so the call-time expansion in\n * `registerConflictResolver` saw no pair yet). Tie-break: when BOTH members\n * already carry (different) resolvers, the FIRST name in `names` wins —\n * callers pass `[base, satellite]`, so the base's resolver is canonical.\n * Idempotent; a later explicit registration on either member still\n * overwrites both (last-wins, via the call-time expansion above).\n */\n remirrorPairResolvers(names: readonly string[]): void {\n const canonical = names.map(n => this.conflictResolvers.get(n)).find(r => r !== undefined)\n if (!canonical) return\n for (const n of names) this.conflictResolvers.set(n, canonical)\n }\n\n /** Record a local change for later push. */\n async trackChange(collection: string, id: string, action: 'put' | 'delete', version: number): Promise<void> {\n await this.ensureLoaded()\n\n // Deduplicate: if same collection+id already in dirty, update it\n const idx = this.dirty.findIndex(d => d.collection === collection && d.id === id)\n const entry: DirtyEntry = {\n vault: this.vault,\n collection,\n id,\n action,\n version,\n timestamp: new Date().toISOString(),\n }\n\n if (idx >= 0) {\n this.dirty[idx] = entry\n } else {\n this.dirty.push(entry)\n }\n\n await this.persistMeta()\n\n // Notify scheduler of the write (triggers on-change or debounce)\n this.scheduler?.notifyChange()\n }\n\n /** Remove a dirty entry (satellite fan-out revert cleanup — spec #591). */\n async removeDirty(collection: string, id: string): Promise<void> {\n const before = this.dirty.length\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n if (this.dirty.length !== before) await this.persistMeta()\n }\n\n /** Push dirty records to remote adapter. Accepts optional `PushOptions` for partial sync. */\n async push(options?: PushOptions): Promise<PushResult> {\n await this.ensureLoaded()\n this.graphBatchController?.begin() // #638 Task 4\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — a locally-dirty\n // dict edit pushes alongside push({collections:['orders']}), symmetric with pull below.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(entry.collection)) {\n continue\n }\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n // Record was deleted locally after being marked dirty\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (err instanceof ConflictError) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n await this.remote.put(this.vault, entry.collection, entry.id, conflict.local)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n // Merged envelope is stored in conflict.local (the winner)\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n // handled === 'deferred': leave in dirty log\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n // Remove completed entries from dirty log (reverse order to preserve indices)\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.lastPush = new Date().toISOString()\n try {\n await this.persistMeta()\n } finally {\n // #644 item 1: flush (which clears `_graphBatch` unconditionally, vault.ts:1316-1320) must\n // run even if `persistMeta()` throws — else a throw here leaves the batch open, corrupting\n // the NEXT pull()/push() call's wave with THIS call's stale touches.\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /** Pull remote records to local adapter. Accepts optional `PullOptions` for partial sync. */\n async pull(options?: PullOptions): Promise<PullResult> {\n await this.ensureLoaded()\n\n let pulled = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n\n // ── #807 period-scoped pull: validate the option, sync the period summaries\n // (`_periods` + companions — the navigation index, ALWAYS pulled in full,\n // exempt from every filter), then resolve the selected `_ts` windows from the\n // freshly synced index. All BEFORE the graph batch opens, so an invalid\n // option throws without leaving a batch dangling; summary applies route\n // through `applyRemote` like any pull (reserved names have no Collection\n // instance, so the invalidator/graph seams are no-ops for them). ──\n let periodScope: ((envelope: EncryptedEnvelope) => boolean) | null = null\n let phases: { summaries: { records: number; bytes: number }; records: { records: number; bytes: number } } | null = null\n if (options?.periods !== undefined) {\n validatePeriodsOption(options.periods)\n if (!this.periodPullSource) {\n throw new ValidationError(\n 'period-scoped pull requires a vault-attached sync engine (open the vault via createNoydb + openVault).',\n )\n }\n phases = { summaries: { records: 0, bytes: 0 }, records: { records: 0, bytes: 0 } }\n let remotePeriodCount = 0\n this.pullByteSink = phases.summaries\n try {\n for (const collName of PERIOD_SUMMARY_COLLECTIONS) {\n for (const id of await this.remote.list(this.vault, collName)) {\n if (collName === PERIODS_COLLECTION) remotePeriodCount++\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope || remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } finally {\n this.pullByteSink = null\n }\n const periodRecords = await this.periodPullSource.periods()\n if (remotePeriodCount > 0 && periodRecords.length === 0) {\n throw new ValidationError(\n 'period-scoped pull: the vault holds _periods records but none are readable — enable the ' +\n 'periods service (`periodsStrategy: withPeriods()`) so pull can resolve the period windows.',\n )\n }\n periodScope = buildPeriodScope(options.periods, periodRecords)\n }\n\n this.graphBatchController?.begin() // #638 Task 4\n if (phases) this.pullByteSink = phases.records\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — adopters never\n // name `_dict_*` in a `collections` filter, so a named collection's lookup-field dependency\n // must be pulled alongside it or its labels/membership go stale.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n try {\n const remoteSnapshot = await this.remote.loadAll(this.vault)\n\n for (const [collName, records] of Object.entries(remoteSnapshot)) {\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(collName)) {\n continue\n }\n\n for (const [id, remoteEnvelope] of Object.entries(records)) {\n // Partial sync: modifiedSince filter — arriving tombstones are exempt (#590):\n // an erasure must never be skipped by partial sync.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isTombstoneShape(remoteEnvelope) &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n // #807: period scope — a record whose `_ts` falls outside every selected\n // window is skipped. Tombstones and delete markers are ALWAYS in scope\n // (built into the predicate): an erasure or delete must never be skipped\n // by partial sync, mirroring the modifiedSince exemption above — that is\n // what lets a device that never pulled a period backfill it later without\n // resurrecting its deleted records.\n if (periodScope !== null && !periodScope(remoteEnvelope)) {\n continue\n }\n\n try {\n const localEnvelope = await this.local.get(this.vault, collName, id)\n const remoteIsTombstone = isTombstoneShape(remoteEnvelope)\n\n if (!localEnvelope) {\n // New record from remote (tombstones included — durable erasure evidence)\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (isTombstoneShape(localEnvelope)) {\n if (remoteIsTombstone) {\n // Both shredded — keep the higher version counter\n if (remoteEnvelope._v > localEnvelope._v) await this.applyRemote(collName, id, remoteEnvelope)\n } else {\n // Terminal rule (#590): a tombstone is never overwritten by a live\n // envelope, regardless of _v. Re-assert the shred outward instead.\n erasures.push(await this.reassertTombstone(collName, id, localEnvelope, remoteEnvelope))\n }\n } else if (remoteIsTombstone) {\n // Terminal rule (#590): an arriving tombstone wins over any local live\n // envelope — even a newer, dirty one. Resolvers are never consulted.\n const wasDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n if (wasDirty) erasures.push(this.reportErasure(collName, id, remoteEnvelope, localEnvelope, 'pull'))\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // #589: true concurrent delete-vs-edit at the SAME version. Version order\n // can't break the tie. A per-collection resolver decides if one is set;\n // otherwise DELETE wins (the db-level 'version' default is deliberately NOT\n // consulted — it would resolve a tie to local-wins).\n const resolver = this.conflictResolvers.get(collName)\n if (resolver) {\n const winner = await resolver(id, localEnvelope, remoteEnvelope)\n if (winner !== localEnvelope && winner !== null) {\n // #589 (review): a novel/merged winner (neither side verbatim) must also be\n // pushed to remote — mirrors handleConflict's 'merged' handling — so both\n // sides converge instead of local applying it while remote keeps its old copy.\n if (winner !== remoteEnvelope) {\n await this.remote.put(this.vault, collName, id, winner)\n }\n await this.applyRemote(collName, id, winner)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // winner === localEnvelope or null → keep local (its dirty entry, if any, pushes out)\n } else if (isDeleteMarker(remoteEnvelope)) {\n // no resolver → delete wins; the incoming marker is the delete\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // no resolver and LOCAL is the marker → keep local marker; its dirty 'put' pushes it outward\n } else if (remoteEnvelope._v > localEnvelope._v) {\n // Remote is newer — check if we have a dirty entry for this\n const isDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n if (isDirty) {\n // Both changed — conflict\n const { handled, conflict } = await this.handleConflict(\n collName,\n id,\n localEnvelope,\n remoteEnvelope,\n 'pull',\n )\n conflicts.push(conflict)\n if (handled === 'remote') {\n await this.applyRemote(collName, id, conflict.remote)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n } else if (handled === 'merged' && conflict.local !== localEnvelope) {\n const merged = conflict.local\n await this.applyRemote(collName, id, merged)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // 'local' or 'deferred': push handles it\n } else {\n // Remote is newer, no local changes — update\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n }\n // Same version or local is newer — skip (push will handle)\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n\n // #650 Task 4 (#647) — reserved lookup collections (`_dict_*`/`_lookup_*`) are invisible to\n // `remote.loadAll()` above (the store contract skips `_`-prefixed names) but DO sync via\n // this EXPLICIT, declared registry — not a blanket underscore-glob; other `_` namespaces\n // keep their `loadAll`-skip semantics untouched. Applied through the SAME `applyRemote` path,\n // still inside this try block, BEFORE `persistMeta`/`flush` below — so a pulled vocabulary\n // row lands before the wave (flushed at the end of `pull()`) recomputes any dependent.\n //\n // #647 fix wave 1: `LookupHandle.delete()`/`rename()` now write a version-ordered\n // delete-marker row (mirroring #589) instead of a raw adapter delete, so a removed key is\n // a normal row here too — reachable via `remote.list()` like any other id, applied by\n // version like any other write. The only reserved-tier-specific rule is the same-version\n // tie-break below: reserved lookups have no per-collection conflict-resolver concept\n // (dictionaries are admin-edited, not multi-actor-negotiated), so a converging delete\n // unconditionally wins over a same-version live edit.\n //\n // #807: the period scope deliberately does NOT apply here — vocabularies/config rows are\n // not period-partitioned data (a thin client's lookups must be complete regardless of\n // which periods it pulled), the same always-pull rule as the `_periods` summaries phase.\n for (const collName of this.reservedLookup?.collections() ?? []) {\n if (filter && !filter.has(collName)) continue\n for (const id of await this.remote.list(this.vault, collName)) {\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n\n // Partial sync: modifiedSince filter — a delete marker is exempt, mirroring the\n // main loop's tombstone/marker exemption above: a deletion must never be silently\n // skipped by a time-window partial pull.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // Same-version delete-vs-edit tie (#589's rule, reserved-tier default: no\n // resolver concept here, so delete always wins).\n if (isDeleteMarker(remoteEnvelope)) {\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // else: local already holds the marker (a local delete not yet observed\n // remotely) — keep it; push re-asserts it.\n } else if (remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n // Drop any now-superseded local dirty entry so a subsequent push doesn't\n // redundantly re-fight a CAS conflict over content pull just overwrote.\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n\n this.lastPull = new Date().toISOString()\n try {\n await this.persistMeta()\n } finally {\n this.pullByteSink = null // #807: stop attributing applies to this pull's KPI counters\n // #644 item 1: flush must run even if `persistMeta()` throws (see push()'s identical guard).\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PullResult = { pulled, conflicts, errors, erasures, ...(phases !== null ? { phases } : {}) }\n this.emitter.emit('sync:pull', result)\n return result\n }\n\n /** Bidirectional sync: pull then push. */\n async sync(options?: { push?: PushOptions; pull?: PullOptions }): Promise<{ pull: PullResult; push: PushResult }> {\n const pullResult = await this.pull(options?.pull)\n const pushResult = await this.push(options?.push)\n return { pull: pullResult, push: pushResult }\n }\n\n /**\n * Push a specific subset of dirty entries (for sync transactions, ).\n * Entries are matched by collection+id from the dirty log; matched entries\n * are removed from the dirty log on success.\n */\n async pushFiltered(predicate: (entry: DirtyEntry) => boolean): Promise<PushResult> {\n await this.ensureLoaded()\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n if (!predicate(entry)) continue\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (err instanceof ConflictError) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n await this.remote.put(this.vault, entry.collection, entry.id, conflict.local)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.lastPush = new Date().toISOString()\n await this.persistMeta()\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /** Get current sync status. */\n status(): SyncStatus {\n // #809 — readiness rides the status surface that already exists rather than\n // a second accessor, so an app asks one question to learn everything about\n // this vault's sync. Absent entirely unless a phased policy is running.\n const scheduled = this.scheduler?.status\n return {\n dirty: this.dirty.length,\n lastPush: this.lastPush,\n lastPull: this.lastPull,\n online: this.isOnline,\n ...(scheduled && scheduled.readiness.size > 0\n ? { readiness: scheduled.readiness, phase: scheduled.phase }\n : {}),\n }\n }\n\n // ─── Auto-Sync ───────────────────────────────────────────────────\n\n /** Start auto-sync: listen for online/offline events, optional periodic sync. */\n startAutoSync(intervalMs?: number): void {\n // Online/offline detection\n if (typeof globalThis.addEventListener === 'function') {\n globalThis.addEventListener('online', this.handleOnline)\n globalThis.addEventListener('offline', this.handleOffline)\n }\n\n // Periodic sync\n if (intervalMs && intervalMs > 0) {\n this.autoSyncInterval = setInterval(() => {\n if (this.isOnline) {\n void this.sync()\n }\n }, intervalMs)\n }\n }\n\n /** Stop auto-sync and scheduler. */\n stopAutoSync(): void {\n this.stopScheduler()\n if (typeof globalThis.removeEventListener === 'function') {\n globalThis.removeEventListener('online', this.handleOnline)\n globalThis.removeEventListener('offline', this.handleOffline)\n }\n if (this.autoSyncInterval) {\n clearInterval(this.autoSyncInterval)\n this.autoSyncInterval = null\n }\n }\n\n private handleOnline = (): void => {\n this.isOnline = true\n this.emitter.emit('sync:online', undefined as never)\n void this.sync()\n }\n\n private handleOffline = (): void => {\n this.isOnline = false\n this.emitter.emit('sync:offline', undefined as never)\n }\n\n /** Apply an envelope to the local store and refresh in-memory views (#598). `action` (#640):\n * classified HERE — the one choke point that still holds the envelope — so the\n * cacheInvalidator seam (and, downstream, the dispatch wave) can tell a pulled delete from an\n * ordinary put. `isTombstoneShape` covers a forgotten-elsewhere record arriving as a shred;\n * `isDeleteMarker` covers an ordinary (#589) delete — both route to the SAME 'delete' action\n * (sync delete ≠ forget: freshness only, no shred/residue channel on the receiving side). */\n private async applyRemote(collection: string, id: string, envelope: EncryptedEnvelope): Promise<void> {\n await this.local.put(this.vault, collection, id, envelope)\n if (this.pullByteSink !== null) {\n // #807: KPI — one applied envelope; bytes ≈ ciphertext payload size.\n this.pullByteSink.records++\n this.pullByteSink.bytes += envelopeBodySize(envelope)\n }\n const action: 'put' | 'delete' = isTombstoneShape(envelope) || isDeleteMarker(envelope) ? 'delete' : 'put'\n await this.cacheInvalidator?.(collection, id, action)\n }\n\n /** Record + emit a tombstone enforcement (#590). */\n private reportErasure(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressed: EncryptedEnvelope,\n direction: 'pull' | 'push',\n ): ErasureEnforcement {\n const enforcement: ErasureEnforcement = { vault: this.vault, collection, id, tombstone, suppressed, direction }\n this.emitter.emit('sync:erasure', enforcement)\n return enforcement\n }\n\n /**\n * Re-assert a local tombstone over a live remote envelope (#590): the shred\n * wins in both directions, regardless of `_v`. Bumps the tombstone to the\n * suppressed envelope's `_v` when higher so per-key version counters stay\n * monotonic on every store; `_by` (the shredding actor) is preserved.\n */\n private async reassertTombstone(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressedRemote: EncryptedEnvelope,\n ): Promise<ErasureEnforcement> {\n let winner = tombstone\n if (suppressedRemote._v > tombstone._v) {\n winner = { ...tombstone, _v: suppressedRemote._v, _ts: new Date().toISOString() }\n await this.applyRemote(collection, id, winner)\n }\n await this.remote.put(this.vault, collection, id, winner)\n // The re-assert already delivered the tombstone remotely — drop any dirty\n // entry so the following push doesn't redundantly re-put it.\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n return this.reportErasure(collection, id, winner, suppressedRemote, 'pull')\n }\n\n /**\n * Resolve a conflict, checking per-collection resolvers first,\n * then falling back to the db-level `ConflictStrategy`.\n *\n * Returns the resolved `Conflict` object (possibly with `resolve` set for\n * manual mode) and a `handled` discriminant:\n * - `'local'` — keep the local envelope; push it to remote.\n * - `'remote'` — keep the remote envelope; update local.\n * - `'merged'` — a custom merge fn produced a new envelope stored as `conflict.local`.\n * - `'deferred'` — manual mode, resolve was not called synchronously.\n */\n private async handleConflict(\n collection: string,\n id: string,\n local: EncryptedEnvelope,\n remote: EncryptedEnvelope,\n _phase: 'push' | 'pull',\n ): Promise<{ handled: 'local' | 'remote' | 'merged' | 'deferred'; conflict: Conflict }> {\n const resolver = this.conflictResolvers.get(collection)\n\n if (resolver) {\n // Per-collection resolver is responsible for emitting sync:conflict\n // (manual policy emits with a resolve callback; LWW/FWW/custom are silent).\n const winner = await resolver(id, local, remote)\n const base: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n if (winner === null) return { handled: 'deferred', conflict: base }\n if (winner === local) return { handled: 'local', conflict: base }\n if (winner === remote) return { handled: 'remote', conflict: base }\n // Custom merge fn produced a new envelope — store as conflict.local for the caller\n return {\n handled: 'merged',\n conflict: { ...base, local: winner, localVersion: winner._v },\n }\n }\n\n // Fall back to db-level strategy — emit once\n const baseConflict: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n this.emitter.emit('sync:conflict', baseConflict)\n const side = this.legacyResolve(baseConflict)\n return { handled: side, conflict: baseConflict }\n }\n\n /** DB-level ConflictStrategy resolution (legacy, kept for backward compat). */\n private legacyResolve(conflict: Conflict): 'local' | 'remote' {\n if (typeof this.strategy === 'function') {\n return this.strategy(conflict)\n }\n switch (this.strategy) {\n case 'local-wins': return 'local'\n case 'remote-wins': return 'remote'\n case 'version':\n default:\n return conflict.localVersion >= conflict.remoteVersion ? 'local' : 'remote'\n }\n }\n\n // ─── Persistence ─────────────────────────────────────────────────\n\n private async ensureLoaded(): Promise<void> {\n if (this.loaded) return\n\n const envelope = await this.local.get(this.vault, '_sync', 'meta')\n if (envelope) {\n const meta = JSON.parse(envelope._data) as SyncMetadata\n this.dirty = [...meta.dirty]\n this.lastPush = meta.last_push\n this.lastPull = meta.last_pull\n }\n\n this.loaded = true\n }\n\n private async persistMeta(): Promise<void> {\n const meta: SyncMetadata = {\n _noydb_sync: NOYDB_SYNC_VERSION,\n last_push: this.lastPush,\n last_pull: this.lastPull,\n dirty: this.dirty,\n }\n\n const envelope: EncryptedEnvelope = {\n _noydb: 1,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(meta),\n }\n\n await this.local.put(this.vault, '_sync', 'meta', envelope)\n }\n}\n","import type { SyncTransactionResult } from '../kernel/types.js'\nimport type { SyncEngine } from './engine.js'\nimport type { Vault } from '../kernel/vault.js'\n\ninterface TxOp {\n readonly type: 'put' | 'delete'\n readonly collection: string\n readonly id: string\n readonly record?: unknown\n}\n\n/**\n * Sync transaction.\n *\n * Stages local writes and then pushes only those records to remote in a\n * single batch. If any record conflicts during the push, the result\n * carries `status: 'conflict'` — no automatic rollback is performed;\n * the caller handles conflict resolution.\n *\n * Obtain via `db.transaction(compartmentName)`.\n */\nexport class SyncTransaction {\n private readonly comp: Vault\n private readonly engine: SyncEngine\n private readonly ops: TxOp[] = []\n\n /** @internal — constructed by `Noydb.transaction()` */\n constructor(comp: Vault, engine: SyncEngine) {\n this.comp = comp\n this.engine = engine\n }\n\n /** Stage a record write. Does not write to any adapter until `commit()`. */\n put(collection: string, id: string, record: unknown): this {\n this.ops.push({ type: 'put', collection, id, record })\n return this\n }\n\n /** Stage a record delete. Does not write to any adapter until `commit()`. */\n delete(collection: string, id: string): this {\n this.ops.push({ type: 'delete', collection, id })\n return this\n }\n\n /**\n * Commit the transaction.\n *\n * Phase 1 — writes all staged operations to the local adapter via the\n * collection layer (encryption + dirty-log tracking).\n *\n * Phase 2 — pushes only the records that were written in this\n * transaction to the remote adapter. Existing dirty entries from\n * outside this transaction are not affected.\n *\n * If any record conflicts during the push, `status` is `'conflict'`\n * and `conflicts` lists the affected records. No automatic rollback is\n * performed.\n */\n async commit(): Promise<SyncTransactionResult> {\n // Phase 1: write all staged ops to local via collection layer\n for (const op of this.ops) {\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.comp.collection<any>(op.collection)).put(op.id, op.record as any)\n } else {\n await this.comp.collection(op.collection).delete(op.id)\n }\n }\n\n // Phase 2: push only the records from this transaction\n const opSet = new Set<string>()\n for (const op of this.ops) {\n opSet.add(`${op.collection}::${op.id}`)\n }\n\n const pushResult = await this.engine.pushFiltered(\n (entry) => opSet.has(`${entry.collection}::${entry.id}`),\n )\n\n return {\n status: pushResult.conflicts.length > 0 ? 'conflict' : 'committed',\n pushed: pushResult.pushed,\n conflicts: pushResult.conflicts,\n ...(pushResult.erasures?.length ? { erasures: pushResult.erasures } : {}),\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDO,IAAM,iBAAN,MAAwB;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,cAAiC;AAAA,EACjC,cAAyD,CAAC;AAAA,EAC1D,oBAAyC;AAAA,EACzC,YAAmD;AAAA,EACnD,UAAU;AAAA,EAElB,YAAY,MAA0B;AACpC,SAAK,UAAU,KAAK;AACpB,SAAK,cAAc,KAAK;AACxB,SAAK,QAAQ,KAAK;AAClB,SAAK,iBAAiB,KAAK;AAC3B,SAAK,SAAS,KAAK;AACnB,SAAK,YAAY,KAAK;AACtB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,iBAAiB,KAAK,kBAAkB;AAG7C,SAAK,UAAU,GAAG,KAAK,KAAK,IAAI,KAAK,cAAc;AAEnD,SAAK,oBAAoB,aAAa,KAAK,cAAc;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAO,SAA2B;AACtC,QAA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