@noy-db/hub 0.6.0-pre.8 → 0.6.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 (512) hide show
  1. package/CHANGELOG.md +7079 -0
  2. package/codemods/0.6.0-pre.json +211 -0
  3. package/dist/api-6X2VLZ7J.js +20 -0
  4. package/dist/attestation/index.js +19 -19
  5. package/dist/{backup-KULFZ2T4.js → backup-VL4GRIEW.js} +36 -18
  6. package/dist/backup-VL4GRIEW.js.map +1 -0
  7. package/dist/blobs/index.js +22 -20
  8. package/dist/blobs/index.js.map +1 -1
  9. package/dist/broker/index.js +12 -12
  10. package/dist/cargo/index.js +35 -35
  11. package/dist/{chunk-KUDZVJKQ.js → chunk-22GR3O4J.js} +2 -2
  12. package/dist/{chunk-CCZJJ4I2.js → chunk-2CBFYXJX.js} +6 -6
  13. package/dist/{chunk-JJNOLSG5.js → chunk-2J5IT37K.js} +15 -16
  14. package/dist/chunk-2J5IT37K.js.map +1 -0
  15. package/dist/{chunk-PNKHAKQ7.js → chunk-2ZCWHCLF.js} +17 -10
  16. package/dist/chunk-2ZCWHCLF.js.map +1 -0
  17. package/dist/{chunk-2BMRJ6LQ.js → chunk-2ZT4INZ4.js} +8 -11
  18. package/dist/{chunk-2BMRJ6LQ.js.map → chunk-2ZT4INZ4.js.map} +1 -1
  19. package/dist/{chunk-FAXZQ5UF.js → chunk-323MN67Z.js} +2 -2
  20. package/dist/{chunk-VMCCGUQB.js → chunk-36CEG6CM.js} +2 -2
  21. package/dist/{chunk-PDLLCOGD.js → chunk-3OE2QNSM.js} +20 -17
  22. package/dist/chunk-3OE2QNSM.js.map +1 -0
  23. package/dist/{chunk-AHLJSVRL.js → chunk-3YGUHUJA.js} +5 -7
  24. package/dist/chunk-3YGUHUJA.js.map +1 -0
  25. package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
  26. package/dist/chunk-4AOERLTV.js.map +1 -0
  27. package/dist/{chunk-J7FM3RAU.js → chunk-4ATF4BLF.js} +87 -34
  28. package/dist/chunk-4ATF4BLF.js.map +1 -0
  29. package/dist/{chunk-747LRSOO.js → chunk-4K6BIMLF.js} +2 -2
  30. package/dist/{chunk-PXCBVDFY.js → chunk-5ATC6UT4.js} +40 -7
  31. package/dist/chunk-5ATC6UT4.js.map +1 -0
  32. package/dist/{chunk-4GZ6XOVW.js → chunk-5F7BZAGV.js} +44 -42
  33. package/dist/chunk-5F7BZAGV.js.map +1 -0
  34. package/dist/{chunk-FNSMZQS4.js → chunk-5IHGJHWC.js} +2 -2
  35. package/dist/{chunk-4I72F5DF.js → chunk-5LZZQMIC.js} +11 -14
  36. package/dist/chunk-5LZZQMIC.js.map +1 -0
  37. package/dist/{chunk-JXIDGFKS.js → chunk-5O5ZSW7N.js} +4 -2
  38. package/dist/chunk-5O5ZSW7N.js.map +1 -0
  39. package/dist/{chunk-CEJWMBXO.js → chunk-5OT4G5N5.js} +6 -2
  40. package/dist/chunk-5OT4G5N5.js.map +1 -0
  41. package/dist/{chunk-GAG7QOVO.js → chunk-64WHKBMP.js} +53 -18
  42. package/dist/chunk-64WHKBMP.js.map +1 -0
  43. package/dist/{chunk-7TSYBD3E.js → chunk-65JXA63J.js} +2 -2
  44. package/dist/{chunk-Z45YRGFO.js → chunk-6NR36UNB.js} +2 -2
  45. package/dist/{chunk-W77KZHCW.js → chunk-6RH7PRTL.js} +16 -17
  46. package/dist/chunk-6RH7PRTL.js.map +1 -0
  47. package/dist/{chunk-3JVXVJ7L.js → chunk-7OBIBPCV.js} +10 -10
  48. package/dist/{chunk-AR2JDFAE.js → chunk-7Q3RHOA5.js} +2 -2
  49. package/dist/chunk-7ZGPQOFV.js +190 -0
  50. package/dist/chunk-7ZGPQOFV.js.map +1 -0
  51. package/dist/{chunk-QULVCV3M.js → chunk-AJGGBXWA.js} +4 -4
  52. package/dist/{chunk-CADUYBQD.js → chunk-ATL3ZVXT.js} +2 -2
  53. package/dist/{chunk-DMQCLZ4Z.js → chunk-ATY3ZASK.js} +2 -2
  54. package/dist/{chunk-4HDYQL3J.js → chunk-B4CRUZPR.js} +2 -2
  55. package/dist/{chunk-IMZLOJTK.js → chunk-BMU2DS3S.js} +30 -21
  56. package/dist/chunk-BMU2DS3S.js.map +1 -0
  57. package/dist/{chunk-6SAFL5YE.js → chunk-BZ3WMOYX.js} +3 -3
  58. package/dist/{chunk-UHXCLPGC.js → chunk-C3XWJCG7.js} +2 -2
  59. package/dist/chunk-C3XWJCG7.js.map +1 -0
  60. package/dist/{chunk-HXGUIPQB.js → chunk-CKKN25P2.js} +3 -3
  61. package/dist/{chunk-3URQC7EH.js → chunk-CXPOG3ZY.js} +355 -132
  62. package/dist/chunk-CXPOG3ZY.js.map +1 -0
  63. package/dist/{chunk-3FSX6LDG.js → chunk-D2YFQ7XG.js} +18 -3
  64. package/dist/{chunk-3FSX6LDG.js.map → chunk-D2YFQ7XG.js.map} +1 -1
  65. package/dist/{chunk-52JPHN5N.js → chunk-D6SXRMZZ.js} +27 -149
  66. package/dist/chunk-D6SXRMZZ.js.map +1 -0
  67. package/dist/{chunk-2DHSSLOD.js → chunk-DECNV4QK.js} +13 -15
  68. package/dist/chunk-DECNV4QK.js.map +1 -0
  69. package/dist/{chunk-6BU3L4UE.js → chunk-DNKVKO7K.js} +7 -10
  70. package/dist/chunk-DNKVKO7K.js.map +1 -0
  71. package/dist/{chunk-6HFM7EIT.js → chunk-EHRIDNZX.js} +2 -2
  72. package/dist/{chunk-3737A6EA.js → chunk-EHW7NLGD.js} +127 -31
  73. package/dist/chunk-EHW7NLGD.js.map +1 -0
  74. package/dist/{chunk-BEFVYAR5.js → chunk-EQOTJL76.js} +4 -4
  75. package/dist/chunk-EQOTJL76.js.map +1 -0
  76. package/dist/{chunk-E6427JU2.js → chunk-EV2TDHQZ.js} +19 -3
  77. package/dist/chunk-EV2TDHQZ.js.map +1 -0
  78. package/dist/{chunk-WFUIE565.js → chunk-FNYCT27B.js} +17 -14
  79. package/dist/chunk-FNYCT27B.js.map +1 -0
  80. package/dist/{chunk-RTAMLDWP.js → chunk-FU5VYEYK.js} +2 -2
  81. package/dist/chunk-FX3UIDCS.js +66 -0
  82. package/dist/chunk-FX3UIDCS.js.map +1 -0
  83. package/dist/{chunk-7F4DBNSP.js → chunk-GANFIM2M.js} +135 -18
  84. package/dist/chunk-GANFIM2M.js.map +1 -0
  85. package/dist/{chunk-4VUPLMZ6.js → chunk-GCU42IG7.js} +66 -71
  86. package/dist/chunk-GCU42IG7.js.map +1 -0
  87. package/dist/{chunk-RXYYFSBB.js → chunk-GKTW3KLV.js} +4 -4
  88. package/dist/chunk-HK67PX4J.js +27 -0
  89. package/dist/chunk-HK67PX4J.js.map +1 -0
  90. package/dist/{chunk-OF3L2SD6.js → chunk-HOPNIR5R.js} +2 -2
  91. package/dist/{chunk-WLZ47GSL.js → chunk-HSJBJIB2.js} +12 -10
  92. package/dist/{chunk-WLZ47GSL.js.map → chunk-HSJBJIB2.js.map} +1 -1
  93. package/dist/{chunk-ADW22QSB.js → chunk-HWI7GHJZ.js} +4 -4
  94. package/dist/{chunk-GQ3BX5EA.js → chunk-I3ISCYT7.js} +2 -2
  95. package/dist/{chunk-YJ6IONGA.js → chunk-IWKCJCLP.js} +11 -3
  96. package/dist/{chunk-YJ6IONGA.js.map → chunk-IWKCJCLP.js.map} +1 -1
  97. package/dist/{chunk-NJDQ4YSV.js → chunk-IWQPYT6S.js} +4 -4
  98. package/dist/{chunk-JRKZTEZZ.js → chunk-J6I5VR6P.js} +444 -73
  99. package/dist/chunk-J6I5VR6P.js.map +1 -0
  100. package/dist/{chunk-2Z3NCLNX.js → chunk-JHYKSMVX.js} +7 -7
  101. package/dist/{chunk-6FJWSWFT.js → chunk-JIHWBKMQ.js} +3 -3
  102. package/dist/{chunk-YAWK6AWF.js → chunk-JKATP6OE.js} +2 -2
  103. package/dist/{chunk-PL2GHSCM.js → chunk-JMJSCI7U.js} +157 -90
  104. package/dist/chunk-JMJSCI7U.js.map +1 -0
  105. package/dist/{chunk-Q6TEJXBX.js → chunk-JXHNUYQO.js} +31 -49
  106. package/dist/chunk-JXHNUYQO.js.map +1 -0
  107. package/dist/{chunk-WK5XUYYF.js → chunk-JYPRZWCZ.js} +473 -231
  108. package/dist/chunk-JYPRZWCZ.js.map +1 -0
  109. package/dist/{chunk-5ZKS6ZE2.js → chunk-K6CPIK3R.js} +4 -4
  110. package/dist/chunk-K6CPIK3R.js.map +1 -0
  111. package/dist/{chunk-CDB2HVQW.js → chunk-KM6ZXG7U.js} +14 -15
  112. package/dist/chunk-KM6ZXG7U.js.map +1 -0
  113. package/dist/{chunk-DG27IUVI.js → chunk-LC6NE4IQ.js} +2 -2
  114. package/dist/{chunk-WASHZV34.js → chunk-LIR2DJWP.js} +63 -25
  115. package/dist/chunk-LIR2DJWP.js.map +1 -0
  116. package/dist/{chunk-VZ3XFUQ7.js → chunk-LUYPYCHY.js} +16 -22
  117. package/dist/chunk-LUYPYCHY.js.map +1 -0
  118. package/dist/{chunk-G6S5VVHP.js → chunk-M7WBE3OR.js} +10 -10
  119. package/dist/chunk-M7WBE3OR.js.map +1 -0
  120. package/dist/{chunk-VJFMXYKP.js → chunk-MPKP6L5E.js} +2 -2
  121. package/dist/{chunk-IGJCYUT5.js → chunk-NSITFOCJ.js} +1 -1
  122. package/dist/chunk-NSITFOCJ.js.map +1 -0
  123. package/dist/{chunk-FUHKW252.js → chunk-OCJ3JA4O.js} +2 -2
  124. package/dist/{chunk-VCETL77O.js → chunk-ONPVHX2Y.js} +36 -7
  125. package/dist/chunk-ONPVHX2Y.js.map +1 -0
  126. package/dist/{chunk-WLYIROCJ.js → chunk-OQMCFHUX.js} +2 -2
  127. package/dist/{chunk-JRCYZEHU.js → chunk-OR2FYRYR.js} +2 -2
  128. package/dist/{chunk-HNHCQ556.js → chunk-PFWE7FJG.js} +2 -2
  129. package/dist/{chunk-NPP5R7FF.js → chunk-PJX72ICF.js} +22 -18
  130. package/dist/chunk-PJX72ICF.js.map +1 -0
  131. package/dist/{chunk-U5O6GIWZ.js → chunk-POFYIGQ2.js} +3 -3
  132. package/dist/{chunk-35EBKWQU.js → chunk-QH47SQLD.js} +4 -4
  133. package/dist/{chunk-FZ6NYJ7L.js → chunk-QQRRKO7W.js} +11 -8
  134. package/dist/chunk-QQRRKO7W.js.map +1 -0
  135. package/dist/{chunk-HVQGCKY4.js → chunk-QVXZFJBU.js} +2 -2
  136. package/dist/{chunk-FMQJZH4R.js → chunk-RDB66EKD.js} +6 -6
  137. package/dist/{chunk-X56RTUK3.js → chunk-RJZQ2PVD.js} +3 -3
  138. package/dist/{chunk-SUFG5E73.js → chunk-RPRASGEY.js} +2 -2
  139. package/dist/{chunk-XWX7GL56.js → chunk-S2I5MYSA.js} +7 -10
  140. package/dist/chunk-S2I5MYSA.js.map +1 -0
  141. package/dist/{chunk-FFDNKRCY.js → chunk-S6PJ6ZKE.js} +2 -2
  142. package/dist/chunk-S6PJ6ZKE.js.map +1 -0
  143. package/dist/{chunk-JIUVJ4M7.js → chunk-S7PM7Z4K.js} +3 -3
  144. package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
  145. package/dist/chunk-T7IR4N2S.js.map +1 -0
  146. package/dist/{chunk-N35NC4JH.js → chunk-TKBB62DN.js} +2 -2
  147. package/dist/{chunk-YPYHVOXP.js → chunk-UJ4Z67UQ.js} +2 -2
  148. package/dist/chunk-UJ4Z67UQ.js.map +1 -0
  149. package/dist/{chunk-7MNBICB5.js → chunk-W3HAIN6U.js} +16 -14
  150. package/dist/chunk-W3HAIN6U.js.map +1 -0
  151. package/dist/{chunk-4UVDI4XE.js → chunk-WPZ5FVAS.js} +4 -4
  152. package/dist/{chunk-MSWYQLMQ.js → chunk-XINT4VJA.js} +2 -2
  153. package/dist/{chunk-7G6VDWXB.js → chunk-XPEPMK4Y.js} +3 -3
  154. package/dist/chunk-XPEPMK4Y.js.map +1 -0
  155. package/dist/{chunk-W3TVWF6N.js → chunk-YCGLAANM.js} +2 -2
  156. package/dist/{chunk-O2ERS4UJ.js → chunk-YTUFV7U7.js} +80 -51
  157. package/dist/chunk-YTUFV7U7.js.map +1 -0
  158. package/dist/{chunk-FDX7OWWI.js → chunk-YYV53EHO.js} +2 -2
  159. package/dist/{chunk-HNGSV2YC.js → chunk-Z3BZXPRO.js} +67 -10
  160. package/dist/chunk-Z3BZXPRO.js.map +1 -0
  161. package/dist/{chunk-6NVPFKN3.js → chunk-ZIMQDXTQ.js} +92 -35
  162. package/dist/chunk-ZIMQDXTQ.js.map +1 -0
  163. package/dist/{chunk-5JY5TSVY.js → chunk-ZJUZOJVW.js} +25 -31
  164. package/dist/chunk-ZJUZOJVW.js.map +1 -0
  165. package/dist/{chunk-3IXIU6FP.js → chunk-ZY6P7M52.js} +7 -10
  166. package/dist/chunk-ZY6P7M52.js.map +1 -0
  167. package/dist/{chunk-H73G4XF4.js → chunk-ZYZJLYNS.js} +7 -11
  168. package/dist/chunk-ZYZJLYNS.js.map +1 -0
  169. package/dist/classified/index.js +5 -5
  170. package/dist/{classified-marker-2KJAXRRO.js → classified-marker-AZDSDG6V.js} +3 -3
  171. package/dist/collection-facade-WSUAYFJ4.js +45 -0
  172. package/dist/{computed-6G5M3UPH.js → computed-VG2PCM4L.js} +3 -3
  173. package/dist/consent/index.js +10 -10
  174. package/dist/cover/index.js +10 -3
  175. package/dist/custody/index.js +12 -11
  176. package/dist/{dead-filter-DCB62VWW.js → dead-filter-JNQNB3TA.js} +2 -2
  177. package/dist/debug/index.js +1 -1
  178. package/dist/{delegation-MO7YZYJS.js → delegation-5F36DRDH.js} +24 -23
  179. package/dist/delegation-5F36DRDH.js.map +1 -0
  180. package/dist/derivations/index.js +12 -12
  181. package/dist/derive-MPOGZ4NR.js +22 -0
  182. package/dist/directory/index.js +10 -10
  183. package/dist/{dispatch-MJ6SHB3Y.js → dispatch-3ZA733EY.js} +18 -18
  184. package/dist/{dispatch-FZEAWKVM.js → dispatch-TNM5CRLZ.js} +9 -6
  185. package/dist/dispatch-TNM5CRLZ.js.map +1 -0
  186. package/dist/{enclave-JU4YIEPB.js → enclave-Y2ALNDRD.js} +31 -9
  187. package/dist/executor-BBEEUFO3.js +9 -0
  188. package/dist/executor-G6G3YEWR.js +9 -0
  189. package/dist/executor-ZUTUMTPA.js +29 -0
  190. package/dist/export-accessible-S3KEB763.js +23 -0
  191. package/dist/extract-partition-KVCTSUVE.js +38 -0
  192. package/dist/{fanout-sidecar-NNAJQXMX.js → fanout-sidecar-3QZU7ZZX.js} +18 -27
  193. package/dist/fanout-sidecar-3QZU7ZZX.js.map +1 -0
  194. package/dist/find-V4FN5ITT.js +11 -0
  195. package/dist/forget/index.js +9 -9
  196. package/dist/guards/index.js +7 -7
  197. package/dist/history/index.js +23 -20
  198. package/dist/history/index.js.map +1 -1
  199. package/dist/i18n/index.js +14 -14
  200. package/dist/index.d.ts +30 -13
  201. package/dist/index.js +180 -188
  202. package/dist/index.js.map +1 -1
  203. package/dist/indexing/index.js +4 -4
  204. package/dist/introspection/index.js +11 -11
  205. package/dist/issue-5CFBWBRX.js +19 -0
  206. package/dist/kernel/collection.d.ts +8 -2
  207. package/dist/kernel/constants.d.ts +36 -0
  208. package/dist/kernel/enclave/crypto.d.ts +52 -4
  209. package/dist/kernel/enclave/index.d.ts +10 -3
  210. package/dist/kernel/enclave/record-aad.d.ts +131 -0
  211. package/dist/kernel/enclave/record-envelope.d.ts +76 -0
  212. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
  213. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
  214. package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
  215. package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
  216. package/dist/kernel/enclave/record-keys/rekey.d.ts +91 -0
  217. package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
  218. package/dist/kernel/errors.d.ts +132 -12
  219. package/dist/kernel/merge-authority.d.ts +25 -0
  220. package/dist/kernel/noydb.d.ts +27 -4
  221. package/dist/kernel/query/builder.d.ts +51 -4
  222. package/dist/kernel/query/join.d.ts +27 -0
  223. package/dist/kernel/query/live.d.ts +31 -9
  224. package/dist/kernel/query/predicate.d.ts +9 -0
  225. package/dist/kernel/refs.d.ts +3 -1
  226. package/dist/kernel/sync-policy.d.ts +0 -2
  227. package/dist/kernel/tier-visibility.d.ts +34 -0
  228. package/dist/kernel/types.d.ts +111 -13
  229. package/dist/kernel/vault.d.ts +14 -8
  230. package/dist/kernel/via/index.d.ts +11 -2
  231. package/dist/kernel/via/reconcile.d.ts +12 -0
  232. package/dist/{ledger-AETNF4OM.js → ledger-MQIIOTZB.js} +11 -11
  233. package/dist/liberate-LW7OKVBH.js +25 -0
  234. package/dist/{link-set-E5HNY67I.js → link-set-5PJBBR63.js} +11 -11
  235. package/dist/{managed-secret-CWQ6PND5.js → managed-secret-ETDG6AAE.js} +11 -3
  236. package/dist/materialized-views/index.js +24 -24
  237. package/dist/migrate-cek-V3VDRV24.js +19 -0
  238. package/dist/migrate-cek-V3VDRV24.js.map +1 -0
  239. package/dist/money/index.js +5 -5
  240. package/dist/noydb-LFDRMYZ5.js +85 -0
  241. package/dist/overlay-views/index.js +4 -4
  242. package/dist/periods/index.js +18 -12
  243. package/dist/pod/index.js +79 -89
  244. package/dist/pod-handle-AZ3CXY5Y.js +41 -0
  245. package/dist/pod-handle-AZ3CXY5Y.js.map +1 -0
  246. package/dist/policy/index.js +11 -4
  247. package/dist/port/to/index.d.ts +4 -4
  248. package/dist/port/to/locator.d.ts +54 -8
  249. package/dist/port/with/i18n-strategy.d.ts +4 -1
  250. package/dist/port/with/lookup-strategy.d.ts +4 -1
  251. package/dist/port/with/merge-authority.d.ts +52 -0
  252. package/dist/port/with/service-bus.d.ts +0 -4
  253. package/dist/port/with/strategies.d.ts +2 -0
  254. package/dist/port/with/team-strategy.d.ts +5 -1
  255. package/dist/portability/index.js +8 -8
  256. package/dist/{post-register-2XSSMGEQ.js → post-register-QCJYRMIK.js} +6 -6
  257. package/dist/query/index.js +6 -6
  258. package/dist/reduce/index.js +6 -6
  259. package/dist/register-JBOEHTVX.js +32 -0
  260. package/dist/registry-5DYHQFJS.js +9 -0
  261. package/dist/registry-EANV44W2.js +9 -0
  262. package/dist/registry-J25H6VB4.js +19 -0
  263. package/dist/registry-R23SQUQH.js +18 -0
  264. package/dist/request-withdrawal-KQ4W4UT5.js +31 -0
  265. package/dist/{reveal-BW36KCOQ.js → reveal-W7BKZSUP.js} +6 -6
  266. package/dist/revoke-H3VSTAIE.js +24 -0
  267. package/dist/satellites/index.js +1 -1
  268. package/dist/schema-update/index.js +2 -2
  269. package/dist/sealed-record/index.js +20 -13
  270. package/dist/sealed-record/index.js.map +1 -1
  271. package/dist/search/index.js +4 -4
  272. package/dist/{seed-GDV5PT4R.js → seed-55FPOMYP.js} +20 -22
  273. package/dist/seed-55FPOMYP.js.map +1 -0
  274. package/dist/sequence/index.js +9 -9
  275. package/dist/session/index.js +10 -10
  276. package/dist/shadow/index.js +2 -2
  277. package/dist/share-link/index.js +1 -1
  278. package/dist/signer-53AQ3BU2.js +25 -0
  279. package/dist/snapshots/index.js +10 -10
  280. package/dist/snapshots/index.js.map +1 -1
  281. package/dist/{stale-ARHFVL5U.js → stale-TH7SSVRV.js} +10 -10
  282. package/dist/storage-WSF7ZKTL.js +23 -0
  283. package/dist/{store-coordination-provider-GFCUOBR6.js → store-coordination-provider-R27VRD6K.js} +18 -12
  284. package/dist/store-coordination-provider-R27VRD6K.js.map +1 -0
  285. package/dist/sync/index.js +11 -11
  286. package/dist/team/index.js +15 -14
  287. package/dist/tiers/index.js +11 -10
  288. package/dist/to/index.js +17 -9
  289. package/dist/to/index.js.map +1 -1
  290. package/dist/transactions/index.js +4 -4
  291. package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
  292. package/dist/util/index.js +1 -1
  293. package/dist/vault-head/index.js +115 -0
  294. package/dist/vault-head/index.js.map +1 -0
  295. package/dist/{verify-RO5RTZOJ.js → verify-M5LQH43C.js} +5 -5
  296. package/dist/via/blob/index.d.ts +3 -0
  297. package/dist/via/lookup/handle.d.ts +4 -1
  298. package/dist/walk-NABCHDZN.js +21 -0
  299. package/dist/with-audit/periods/index.d.ts +3 -3
  300. package/dist/with-audit/periods/periods.d.ts +82 -2
  301. package/dist/with-audit/periods/strategy.d.ts +1 -1
  302. package/dist/with-audit/periods/vault-facade.d.ts +54 -1
  303. package/dist/with-audit/periods/window.d.ts +10 -0
  304. package/dist/with-audit/sealed-record/index.d.ts +13 -0
  305. package/dist/with-audit/tiers/index.d.ts +17 -2
  306. package/dist/with-cargo/adopt-partition.d.ts +1 -1
  307. package/dist/with-cargo/extract-partition.d.ts +1 -1
  308. package/dist/with-cargo/index.d.ts +1 -1
  309. package/dist/with-commit/history/history.d.ts +26 -0
  310. package/dist/with-commit/history/index.d.ts +2 -1
  311. package/dist/with-commit/history/ledger/store.d.ts +7 -1
  312. package/dist/with-commit/history/strategy.d.ts +11 -1
  313. package/dist/with-commit/numbering/index.d.ts +0 -5
  314. package/dist/with-commit/vault-head/active.d.ts +2 -0
  315. package/dist/with-commit/vault-head/head.d.ts +28 -0
  316. package/dist/with-commit/vault-head/index.d.ts +10 -0
  317. package/dist/with-commit/vault-head/strategy.d.ts +127 -0
  318. package/dist/with-commit/vault-head/verify.d.ts +90 -0
  319. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  320. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  321. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  322. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  323. package/dist/with-party/directory/cover/storage.d.ts +0 -8
  324. package/dist/with-party/directory/storage.d.ts +0 -11
  325. package/dist/with-party/directory/visibility.d.ts +0 -21
  326. package/dist/with-party/policy/storage.d.ts +0 -10
  327. package/dist/with-party/team/index.d.ts +1 -1
  328. package/dist/with-party/team/keyring.d.ts +139 -2
  329. package/dist/with-party/team/noydb-facade.d.ts +5 -1
  330. package/dist/with-party/team/roster-tag.d.ts +101 -0
  331. package/dist/with-party/team/tiers.d.ts +2 -1
  332. package/dist/with-pod/format.d.ts +10 -12
  333. package/dist/with-pod/index.d.ts +10 -10
  334. package/dist/with-pod/open.d.ts +2 -2
  335. package/dist/with-pod/pod-handle.d.ts +19 -0
  336. package/dist/with-pod/pod-store.d.ts +0 -8
  337. package/dist/with-pod/{bundle.d.ts → pod.d.ts} +11 -19
  338. package/dist/with-pod/ulid.d.ts +1 -1
  339. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  340. package/dist/with-shape/blobs/blob-set.d.ts +83 -11
  341. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  342. package/dist/with-shape/introspection/index.d.ts +1 -0
  343. package/dist/with-sync/engine.d.ts +54 -5
  344. package/dist/with-sync/strategy.d.ts +3 -0
  345. package/dist/withdraw-accessible-VCINIG6V.js +28 -0
  346. package/package.json +10 -4
  347. package/dist/api-RXUMEKT3.js +0 -20
  348. package/dist/backup-KULFZ2T4.js.map +0 -1
  349. package/dist/bundle-handle-GFNHT52M.js +0 -36
  350. package/dist/bundle-handle-GFNHT52M.js.map +0 -1
  351. package/dist/chunk-2DHSSLOD.js.map +0 -1
  352. package/dist/chunk-3737A6EA.js.map +0 -1
  353. package/dist/chunk-3IXIU6FP.js.map +0 -1
  354. package/dist/chunk-3URQC7EH.js.map +0 -1
  355. package/dist/chunk-4GZ6XOVW.js.map +0 -1
  356. package/dist/chunk-4I72F5DF.js.map +0 -1
  357. package/dist/chunk-4VUPLMZ6.js.map +0 -1
  358. package/dist/chunk-52JPHN5N.js.map +0 -1
  359. package/dist/chunk-55LKVALY.js.map +0 -1
  360. package/dist/chunk-5JY5TSVY.js.map +0 -1
  361. package/dist/chunk-5ZKS6ZE2.js.map +0 -1
  362. package/dist/chunk-6BU3L4UE.js.map +0 -1
  363. package/dist/chunk-6NVPFKN3.js.map +0 -1
  364. package/dist/chunk-7F4DBNSP.js.map +0 -1
  365. package/dist/chunk-7G6VDWXB.js.map +0 -1
  366. package/dist/chunk-7H73RIE3.js +0 -45
  367. package/dist/chunk-7H73RIE3.js.map +0 -1
  368. package/dist/chunk-7MNBICB5.js.map +0 -1
  369. package/dist/chunk-AFHQATY4.js +0 -47
  370. package/dist/chunk-AFHQATY4.js.map +0 -1
  371. package/dist/chunk-AHLJSVRL.js.map +0 -1
  372. package/dist/chunk-BEFVYAR5.js.map +0 -1
  373. package/dist/chunk-CDB2HVQW.js.map +0 -1
  374. package/dist/chunk-CEJWMBXO.js.map +0 -1
  375. package/dist/chunk-E6427JU2.js.map +0 -1
  376. package/dist/chunk-FFDNKRCY.js.map +0 -1
  377. package/dist/chunk-FZ6NYJ7L.js.map +0 -1
  378. package/dist/chunk-G6S5VVHP.js.map +0 -1
  379. package/dist/chunk-GAG7QOVO.js.map +0 -1
  380. package/dist/chunk-H73G4XF4.js.map +0 -1
  381. package/dist/chunk-HNGSV2YC.js.map +0 -1
  382. package/dist/chunk-IGJCYUT5.js.map +0 -1
  383. package/dist/chunk-IMZLOJTK.js.map +0 -1
  384. package/dist/chunk-J7FM3RAU.js.map +0 -1
  385. package/dist/chunk-JJNOLSG5.js.map +0 -1
  386. package/dist/chunk-JRKZTEZZ.js.map +0 -1
  387. package/dist/chunk-JXIDGFKS.js.map +0 -1
  388. package/dist/chunk-NPP5R7FF.js.map +0 -1
  389. package/dist/chunk-O2ERS4UJ.js.map +0 -1
  390. package/dist/chunk-PDLLCOGD.js.map +0 -1
  391. package/dist/chunk-PL2GHSCM.js.map +0 -1
  392. package/dist/chunk-PNKHAKQ7.js.map +0 -1
  393. package/dist/chunk-PXCBVDFY.js.map +0 -1
  394. package/dist/chunk-Q6TEJXBX.js.map +0 -1
  395. package/dist/chunk-UHXCLPGC.js.map +0 -1
  396. package/dist/chunk-VCETL77O.js.map +0 -1
  397. package/dist/chunk-VZ3XFUQ7.js.map +0 -1
  398. package/dist/chunk-W77KZHCW.js.map +0 -1
  399. package/dist/chunk-WASHZV34.js.map +0 -1
  400. package/dist/chunk-WFUIE565.js.map +0 -1
  401. package/dist/chunk-WK5XUYYF.js.map +0 -1
  402. package/dist/chunk-XWX7GL56.js.map +0 -1
  403. package/dist/chunk-YPYHVOXP.js.map +0 -1
  404. package/dist/chunk-ZJADGNYF.js.map +0 -1
  405. package/dist/collection-facade-QEJIM6BC.js +0 -45
  406. package/dist/delegation-MO7YZYJS.js.map +0 -1
  407. package/dist/derive-IUA6JFLB.js +0 -22
  408. package/dist/dispatch-FZEAWKVM.js.map +0 -1
  409. package/dist/executor-CYJQLKKI.js +0 -9
  410. package/dist/executor-S4QIKEHW.js +0 -9
  411. package/dist/executor-YIQB2S6N.js +0 -29
  412. package/dist/export-accessible-4S36PQNR.js +0 -23
  413. package/dist/extract-partition-IO7FDZ2P.js +0 -38
  414. package/dist/fanout-sidecar-NNAJQXMX.js.map +0 -1
  415. package/dist/find-RBBYKXI7.js +0 -11
  416. package/dist/issue-RIVHSY2S.js +0 -19
  417. package/dist/liberate-GFN4C7RR.js +0 -24
  418. package/dist/noydb-3MT74MZS.js +0 -83
  419. package/dist/register-4EFJCVYD.js +0 -32
  420. package/dist/registry-4SDHHOJ7.js +0 -18
  421. package/dist/registry-CZVINVQH.js +0 -9
  422. package/dist/registry-IKUR2MXD.js +0 -9
  423. package/dist/registry-OYTFGWVK.js +0 -19
  424. package/dist/request-withdrawal-KGXGDPVQ.js +0 -31
  425. package/dist/revoke-JFN773KF.js +0 -24
  426. package/dist/seed-GDV5PT4R.js.map +0 -1
  427. package/dist/signer-TA55QB6R.js +0 -25
  428. package/dist/storage-V7MTFAQJ.js +0 -23
  429. package/dist/store-coordination-provider-GFCUOBR6.js.map +0 -1
  430. package/dist/walk-3ZECBFDA.js +0 -21
  431. package/dist/with-pod/bundle-handle.d.ts +0 -9
  432. package/dist/withdraw-accessible-7PG4DYQK.js +0 -28
  433. /package/dist/{api-RXUMEKT3.js.map → api-6X2VLZ7J.js.map} +0 -0
  434. /package/dist/{chunk-KUDZVJKQ.js.map → chunk-22GR3O4J.js.map} +0 -0
  435. /package/dist/{chunk-CCZJJ4I2.js.map → chunk-2CBFYXJX.js.map} +0 -0
  436. /package/dist/{chunk-FAXZQ5UF.js.map → chunk-323MN67Z.js.map} +0 -0
  437. /package/dist/{chunk-VMCCGUQB.js.map → chunk-36CEG6CM.js.map} +0 -0
  438. /package/dist/{chunk-747LRSOO.js.map → chunk-4K6BIMLF.js.map} +0 -0
  439. /package/dist/{chunk-FNSMZQS4.js.map → chunk-5IHGJHWC.js.map} +0 -0
  440. /package/dist/{chunk-7TSYBD3E.js.map → chunk-65JXA63J.js.map} +0 -0
  441. /package/dist/{chunk-Z45YRGFO.js.map → chunk-6NR36UNB.js.map} +0 -0
  442. /package/dist/{chunk-3JVXVJ7L.js.map → chunk-7OBIBPCV.js.map} +0 -0
  443. /package/dist/{chunk-AR2JDFAE.js.map → chunk-7Q3RHOA5.js.map} +0 -0
  444. /package/dist/{chunk-QULVCV3M.js.map → chunk-AJGGBXWA.js.map} +0 -0
  445. /package/dist/{chunk-CADUYBQD.js.map → chunk-ATL3ZVXT.js.map} +0 -0
  446. /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-ATY3ZASK.js.map} +0 -0
  447. /package/dist/{chunk-4HDYQL3J.js.map → chunk-B4CRUZPR.js.map} +0 -0
  448. /package/dist/{chunk-6SAFL5YE.js.map → chunk-BZ3WMOYX.js.map} +0 -0
  449. /package/dist/{chunk-HXGUIPQB.js.map → chunk-CKKN25P2.js.map} +0 -0
  450. /package/dist/{chunk-6HFM7EIT.js.map → chunk-EHRIDNZX.js.map} +0 -0
  451. /package/dist/{chunk-RTAMLDWP.js.map → chunk-FU5VYEYK.js.map} +0 -0
  452. /package/dist/{chunk-RXYYFSBB.js.map → chunk-GKTW3KLV.js.map} +0 -0
  453. /package/dist/{chunk-OF3L2SD6.js.map → chunk-HOPNIR5R.js.map} +0 -0
  454. /package/dist/{chunk-ADW22QSB.js.map → chunk-HWI7GHJZ.js.map} +0 -0
  455. /package/dist/{chunk-GQ3BX5EA.js.map → chunk-I3ISCYT7.js.map} +0 -0
  456. /package/dist/{chunk-NJDQ4YSV.js.map → chunk-IWQPYT6S.js.map} +0 -0
  457. /package/dist/{chunk-2Z3NCLNX.js.map → chunk-JHYKSMVX.js.map} +0 -0
  458. /package/dist/{chunk-6FJWSWFT.js.map → chunk-JIHWBKMQ.js.map} +0 -0
  459. /package/dist/{chunk-YAWK6AWF.js.map → chunk-JKATP6OE.js.map} +0 -0
  460. /package/dist/{chunk-DG27IUVI.js.map → chunk-LC6NE4IQ.js.map} +0 -0
  461. /package/dist/{chunk-VJFMXYKP.js.map → chunk-MPKP6L5E.js.map} +0 -0
  462. /package/dist/{chunk-FUHKW252.js.map → chunk-OCJ3JA4O.js.map} +0 -0
  463. /package/dist/{chunk-WLYIROCJ.js.map → chunk-OQMCFHUX.js.map} +0 -0
  464. /package/dist/{chunk-JRCYZEHU.js.map → chunk-OR2FYRYR.js.map} +0 -0
  465. /package/dist/{chunk-HNHCQ556.js.map → chunk-PFWE7FJG.js.map} +0 -0
  466. /package/dist/{chunk-U5O6GIWZ.js.map → chunk-POFYIGQ2.js.map} +0 -0
  467. /package/dist/{chunk-35EBKWQU.js.map → chunk-QH47SQLD.js.map} +0 -0
  468. /package/dist/{chunk-HVQGCKY4.js.map → chunk-QVXZFJBU.js.map} +0 -0
  469. /package/dist/{chunk-FMQJZH4R.js.map → chunk-RDB66EKD.js.map} +0 -0
  470. /package/dist/{chunk-X56RTUK3.js.map → chunk-RJZQ2PVD.js.map} +0 -0
  471. /package/dist/{chunk-SUFG5E73.js.map → chunk-RPRASGEY.js.map} +0 -0
  472. /package/dist/{chunk-JIUVJ4M7.js.map → chunk-S7PM7Z4K.js.map} +0 -0
  473. /package/dist/{chunk-N35NC4JH.js.map → chunk-TKBB62DN.js.map} +0 -0
  474. /package/dist/{chunk-4UVDI4XE.js.map → chunk-WPZ5FVAS.js.map} +0 -0
  475. /package/dist/{chunk-MSWYQLMQ.js.map → chunk-XINT4VJA.js.map} +0 -0
  476. /package/dist/{chunk-W3TVWF6N.js.map → chunk-YCGLAANM.js.map} +0 -0
  477. /package/dist/{chunk-FDX7OWWI.js.map → chunk-YYV53EHO.js.map} +0 -0
  478. /package/dist/{classified-marker-2KJAXRRO.js.map → classified-marker-AZDSDG6V.js.map} +0 -0
  479. /package/dist/{collection-facade-QEJIM6BC.js.map → collection-facade-WSUAYFJ4.js.map} +0 -0
  480. /package/dist/{computed-6G5M3UPH.js.map → computed-VG2PCM4L.js.map} +0 -0
  481. /package/dist/{dead-filter-DCB62VWW.js.map → dead-filter-JNQNB3TA.js.map} +0 -0
  482. /package/dist/{derive-IUA6JFLB.js.map → derive-MPOGZ4NR.js.map} +0 -0
  483. /package/dist/{dispatch-MJ6SHB3Y.js.map → dispatch-3ZA733EY.js.map} +0 -0
  484. /package/dist/{enclave-JU4YIEPB.js.map → enclave-Y2ALNDRD.js.map} +0 -0
  485. /package/dist/{executor-CYJQLKKI.js.map → executor-BBEEUFO3.js.map} +0 -0
  486. /package/dist/{executor-S4QIKEHW.js.map → executor-G6G3YEWR.js.map} +0 -0
  487. /package/dist/{executor-YIQB2S6N.js.map → executor-ZUTUMTPA.js.map} +0 -0
  488. /package/dist/{export-accessible-4S36PQNR.js.map → export-accessible-S3KEB763.js.map} +0 -0
  489. /package/dist/{extract-partition-IO7FDZ2P.js.map → extract-partition-KVCTSUVE.js.map} +0 -0
  490. /package/dist/{find-RBBYKXI7.js.map → find-V4FN5ITT.js.map} +0 -0
  491. /package/dist/{issue-RIVHSY2S.js.map → issue-5CFBWBRX.js.map} +0 -0
  492. /package/dist/{ledger-AETNF4OM.js.map → ledger-MQIIOTZB.js.map} +0 -0
  493. /package/dist/{liberate-GFN4C7RR.js.map → liberate-LW7OKVBH.js.map} +0 -0
  494. /package/dist/{link-set-E5HNY67I.js.map → link-set-5PJBBR63.js.map} +0 -0
  495. /package/dist/{managed-secret-CWQ6PND5.js.map → managed-secret-ETDG6AAE.js.map} +0 -0
  496. /package/dist/{noydb-3MT74MZS.js.map → noydb-LFDRMYZ5.js.map} +0 -0
  497. /package/dist/{post-register-2XSSMGEQ.js.map → post-register-QCJYRMIK.js.map} +0 -0
  498. /package/dist/{register-4EFJCVYD.js.map → register-JBOEHTVX.js.map} +0 -0
  499. /package/dist/{registry-4SDHHOJ7.js.map → registry-5DYHQFJS.js.map} +0 -0
  500. /package/dist/{registry-CZVINVQH.js.map → registry-EANV44W2.js.map} +0 -0
  501. /package/dist/{registry-IKUR2MXD.js.map → registry-J25H6VB4.js.map} +0 -0
  502. /package/dist/{registry-OYTFGWVK.js.map → registry-R23SQUQH.js.map} +0 -0
  503. /package/dist/{request-withdrawal-KGXGDPVQ.js.map → request-withdrawal-KQ4W4UT5.js.map} +0 -0
  504. /package/dist/{reveal-BW36KCOQ.js.map → reveal-W7BKZSUP.js.map} +0 -0
  505. /package/dist/{revoke-JFN773KF.js.map → revoke-H3VSTAIE.js.map} +0 -0
  506. /package/dist/{signer-TA55QB6R.js.map → signer-53AQ3BU2.js.map} +0 -0
  507. /package/dist/{stale-ARHFVL5U.js.map → stale-TH7SSVRV.js.map} +0 -0
  508. /package/dist/{storage-V7MTFAQJ.js.map → storage-WSF7ZKTL.js.map} +0 -0
  509. /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
  510. /package/dist/{verify-RO5RTZOJ.js.map → verify-M5LQH43C.js.map} +0 -0
  511. /package/dist/{walk-3ZECBFDA.js.map → walk-NABCHDZN.js.map} +0 -0
  512. /package/dist/{withdraw-accessible-7PG4DYQK.js.map → withdraw-accessible-VCINIG6V.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/periods/periods.ts","../src/with-audit/periods/active.ts","../src/with-audit/periods/strategy.ts"],"sourcesContent":["/**\n * Accounting-period closure + opening.\n *\n * A closed period seals every record whose envelope `_ts` is at or\n * before the period's `endDate`: further writes (`put` / `delete`)\n * against such records throw {@link PeriodClosedError}. The period\n * itself is stored as a record in the reserved `_periods` collection\n * and written through the normal ledger-instrumented path, so every\n * closure appends a tamper-evident entry to the vault's hash chain.\n *\n * ## Closure model\n *\n * ```\n * vault.closePeriod({ name: 'FY2026-Q1', endDate: '2026-03-31' })\n * └─► PeriodRecord written to _periods/<name>\n * ├─ priorPeriodName / priorPeriodHash — chain to last close\n * ├─ closedAt / closedBy — provenance\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * Enforcement (`assertTsWritable`) is vault-local: the Vault caches\n * the list of closed periods on first read and consults that cache in\n * the `Collection.put` / `.delete` path via the `periodGuard` hook.\n *\n * ## Opening model\n *\n * ```\n * vault.openPeriod({\n * name: 'FY2026-Q2',\n * startDate: '2026-04-01',\n * fromPeriod: 'FY2026-Q1',\n * carryForward: async (priorView) => Record<string, Record<string, unknown>>,\n * })\n * ```\n *\n * `carryForward` receives a read-only `VaultInstant` anchored at the\n * prior period's `endDate` (built via `vault.at(endDate)`) so the\n * callback can compute closing aggregates from the sealed state. The\n * returned `{ [collectionName]: { [id]: record } }` map is written\n * before the new `PeriodRecord` lands — opening balances materialise\n * as normal records with fresh timestamps that fall outside every\n * closed period.\n *\n * ## Freeze\n *\n * ```\n * vault.freezePeriod('FY2026-Q1')\n * └─► physically purges delete markers whose write-time falls inside\n * the closed period's window (via the #589 `_purgeDeleteMarkers`\n * seam), then records the fact:\n * ├─ PeriodFreezeRecord written to _period_freezes/<name>\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * The chained `_periods/<name>` record is never mutated — `frozenAt` /\n * `frozenBy` / `purgedMarkerCount` are merged onto the returned\n * `PeriodRecord` at read time from the companion, so a tamper with the\n * freeze can never break the inter-period hash chain. Freezing is\n * terminal (a closed period, once frozen, stays frozen) and idempotent\n * (a second call is a no-op that returns the same merged record without\n * re-purging or re-appending a ledger entry). Freeze does NOT purge\n * forget-tombstones (GDPR crypto-shred erasure evidence), `_history`\n * versions, or live records — the delete-markers-only seam leaves all\n * three untouched by construction.\n *\n * Freeze purges the LOCAL adapter only. On a synced vault, markers already\n * pushed to sync targets survive there, and a later pull re-imports them\n * (benign — they still read deleted, but the space isn't reclaimed). A\n * re-imported marker keeps its original `_ts` (inside the already-frozen\n * period's window), so — like any late-booked delete — it is reclaimed by\n * the NEXT period's freeze, whose window covers it; freeze stays terminal\n * and does NOT re-purge an already-frozen period (#611). Sweeping the sync\n * targets themselves is a cross-target-purge concern deferred to the\n * cold-archival spec. Purging re-opens the #589 resurrection window for a\n * peer offline since before the cutoff, which is why the closed period is\n * the operator-asserted safe-point that gates the call.\n *\n * A period whose purge window has not fully elapsed cannot be frozen —\n * `freezePeriod` throws rather than purge markers for deletes that may not\n * have converged yet (#610).\n *\n * ## Archive\n *\n * ```\n * vault.archivePeriod('FY2026-Q1')\n * └─► relocates the closed period's in-window records (those with\n * `_ts < periodExclusiveUpperBound(endDate)`) from the hot store to\n * the configured cold tier (routeStore's `cold` route), then records:\n * ├─ PeriodArchiveRecord written to _period_archives/<name>\n * └─ a ledger entry attributed to _period_archives\n * ```\n *\n * Archival is NON-DESTRUCTIVE: routeStore reads fall through to the cold\n * tier on a hot miss, so an archived record still reads normally. It is\n * therefore gated only on `closed` (not `frozen`) — it does not re-open the\n * #589 resurrection window and needs no convergence safe-point. Freeze\n * (purge markers) and archive (relocate records) are independent and compose\n * in either order. Like freeze, archival keeps the chained `_periods/<name>`\n * record byte-immutable (state lives in the companion) and is idempotent.\n *\n * Bounds by write-time `_ts`, NOT business date: the store tier sees only\n * encrypted envelopes. A record with an in-period business date but a later\n * `_ts` (late-booked) archives at the NEXT period's archive — the same rule\n * freeze uses for late-booked delete markers. Requires a `routeStore` with a\n * cold route (`age: { cold }`); throws otherwise.\n *\n * Read cost: with `withLazy()` (per-id reads) archived records are truly\n * cold — fetched from cold only on access. In the default hydrated mode,\n * `loadAll` merges the cold store, so archived records still load into RAM\n * on vault open (hot-tier STORAGE is reclaimed; RAM is not). Summaries\n * (`_`-prefixed) always stay hot.\n *\n * ## Target-purge\n *\n * ```\n * vault.purgePeriodTargets('FY2026-Q1')\n * └─► sweeps delete markers (`_ts < periodExclusiveUpperBound(endDate)`) off\n * the vault's PUSH-ONLY sync targets (backup/archive roles), then records:\n * ├─ PeriodTargetPurgeRecord written to _period_target_purges/<name>\n * └─ a ledger entry attributed to _period_target_purges\n * ```\n *\n * Extends freeze's local marker purge to the vault's own remote sinks.\n * `sync-peer` (bidirectional) targets are SKIPPED: purging a marker there\n * re-opens the #589 resurrection window for a client offline before the\n * cutoff, an assertion no single vault can verify. Backup/archive targets are\n * push-only — never pulled from into convergence — so sweeping their markers\n * is safe. Requires the period be frozen first (closed → frozen →\n * target-purged) so the local safe-point is already established. Idempotent\n * once run; a vault with no push-only targets writes no companion and is\n * re-runnable (so a target added later is still swept). Single-vault only —\n * fleet-wide purge across sovereign vaults is klum's concern over\n * `@noy-db/hub/cargo`.\n *\n * ## Not covered\n *\n * - Partial re-opening of a closed period. If an auditor needs to\n * make a correction inside a sealed period, the sanctioned path is\n * a compensating entry in the NEW period, not an unlock of the\n * old one.\n * - Automatic period rollover. `closePeriod` / `openPeriod` are\n * deliberately explicit operator calls so the caller decides when\n * the boundary lands.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/index.js'\nimport { sha256Hex, canonicalJson } from '../../with-commit/history/ledger/index.js'\nimport { isDeleteMarker } from '../../kernel/enclave/index.js'\nimport { PeriodClosedError, ValidationError } from '../../kernel/errors.js'\n\n// The reserved collection names + `periodExclusiveUpperBound` moved to the\n// dependency-light `window.ts` so the sync engine's period-scoped pull (#807)\n// can import them without this module's ledger imports; re-exported here so\n// every existing import path keeps working.\nexport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n PERIOD_REOPENS_COLLECTION,\n periodExclusiveUpperBound,\n} from './window.js'\nimport { PERIODS_COLLECTION } from './window.js'\n\n/**\n * Companion record recording that a closed period was frozen (its delete\n * markers physically purged). Stored in {@link PERIOD_FREEZES_COLLECTION},\n * keyed by period name — kept OFF the hash-chained `_periods/<name>` record so\n * freeze never alters the inter-period chain.\n */\nexport interface PeriodFreezeRecord {\n readonly period: string\n readonly frozenAt: string\n readonly frozenBy: string\n readonly purgedMarkerCount: number\n}\n\n/**\n * Companion record noting that a closed period was cold-archived (its\n * in-window records physically relocated hot → cold). Stored in\n * {@link PERIOD_ARCHIVES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so archive never alters the chain.\n */\nexport interface PeriodArchiveRecord {\n readonly period: string\n readonly archivedAt: string\n readonly archivedBy: string\n readonly archivedRecordCount: number\n}\n\n/** Per-target count of delete markers purged off one push-only sync target (#615). */\nexport interface TargetPurgeCount {\n readonly label?: string\n readonly role: 'backup' | 'archive'\n readonly purgedCount: number\n}\n\n/**\n * One entry in a period's append-only reopen/reclose log (#1022).\n *\n * Real accounting close is a three-state lifecycle — open / closed / reopened\n * — not a one-way door. A month gets closed, a missing invoice arrives or a\n * filing is rejected, the month is reopened, corrected, and reclosed. The audit\n * value is not the ability to write again; it is the chain being able to say\n * *closed at T1, reopened at T2 by U, reclosed at T3*.\n */\nexport interface PeriodReopenEvent {\n readonly op: 'reopen' | 'reclose'\n /** ISO timestamp the event was recorded. */\n readonly at: string\n /** userId of the keyring that performed it. */\n readonly by: string\n /**\n * `reopen` only — ISO instant after which the period re-seals on its own,\n * with nobody acting. Absent means the window stays open until an explicit\n * `reclosePeriod`.\n */\n readonly until?: string\n /** Free-text justification, carried verbatim into the audit trail. */\n readonly reason?: string\n}\n\n/**\n * Companion holding a period's reopen/reclose history (#1022). Stored in\n * {@link PERIOD_REOPENS_COLLECTION}, keyed by the period's storage key — kept\n * OFF the hash-chained `_periods/<name>` record for the same reason freeze and\n * archive are: reopening must never rewrite the close, or the chain that proves\n * the close happened is the very thing the reopen destroys.\n *\n * `events` is APPEND-ONLY. Where the other companions are single-shot and\n * idempotent, this one accumulates, because the cycle repeats.\n */\nexport interface PeriodReopenRecord {\n readonly period: string\n readonly partition?: PeriodPartition\n readonly events: readonly PeriodReopenEvent[]\n}\n\n/**\n * Collapse an append-only reopen log into the return-only fields merged onto a\n * {@link PeriodRecord} on read.\n *\n * Expiry is deliberately NOT resolved here: `reopenedUntil` is carried through\n * verbatim and compared against the clock at write-guard time, so a bounded\n * window re-seals on its own without anything having to run.\n *\n * @internal\n */\nexport function resolveReopenState(events: readonly PeriodReopenEvent[]): {\n reopenedAt?: string\n reopenedBy?: string\n reopenedUntil?: string\n reopenReason?: string\n reclosedAt?: string\n reopenCount: number\n} {\n let lastReopen: PeriodReopenEvent | undefined\n let reclosedAfter: string | undefined\n let reopenCount = 0\n for (const e of events) {\n if (e.op === 'reopen') {\n lastReopen = e\n reclosedAfter = undefined\n reopenCount++\n } else if (lastReopen !== undefined) {\n reclosedAfter = e.at\n }\n }\n if (!lastReopen) return { reopenCount }\n return {\n reopenedAt: lastReopen.at,\n reopenedBy: lastReopen.by,\n ...(lastReopen.until !== undefined && { reopenedUntil: lastReopen.until }),\n ...(lastReopen.reason !== undefined && { reopenReason: lastReopen.reason }),\n ...(reclosedAfter !== undefined && { reclosedAt: reclosedAfter }),\n reopenCount,\n }\n}\n\n/**\n * Is this period writable right now on account of a reopen? (#1022)\n *\n * Three ways to be sealed again: never reopened, explicitly reclosed after the\n * last reopen, or a bounded window that has elapsed. The clock is read by the\n * caller and passed in, so the guard and any diagnostic agree on one instant.\n *\n * @internal\n */\nexport function isEffectivelyReopened(period: PeriodRecord, nowIso: string): boolean {\n if (period.reopenedAt === undefined) return false\n if (period.reclosedAt !== undefined && period.reclosedAt >= period.reopenedAt) return false\n if (period.reopenedUntil !== undefined && nowIso > period.reopenedUntil) return false\n return true\n}\n\n/**\n * Companion record noting that a closed+frozen period's delete markers were\n * swept off the vault's push-only sync targets (#615). Stored in\n * {@link PERIOD_TARGET_PURGES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so target-purge never alters the chain.\n */\nexport interface PeriodTargetPurgeRecord {\n readonly period: string\n readonly purgedAt: string\n readonly purgedBy: string\n readonly targets: readonly TargetPurgeCount[]\n}\n\n/**\n * Scope tuple for a period timeline (#1005).\n *\n * Identical in shape and semantics to `SequenceOptions.partition`: a\n * partitioned timeline is always disjoint from any unpartitioned one, and from\n * every other tuple. `['acme', 'vat']` and `['acme', 'wht']` are two\n * independent close calendars for the same subject — which is the whole point,\n * since sub-ledgers for one legal entity and one month routinely close on\n * different statutory deadlines.\n */\nexport type PeriodPartition = readonly (string | number)[]\n\n/**\n * Resolve the `_periods` storage key for a (name, partition) pair.\n *\n * Deliberately the same encoding as `resolveSequenceKey`: `name` verbatim when\n * unpartitioned, else `${name}\\x00${parts}` with each component\n * `encodeURIComponent`d and `'/'`-joined. The null-byte separator cannot occur\n * in a period name, so a partitioned key never collides with an unpartitioned\n * one; URI-encoding keeps `['a/b']` distinct from `['a','b']`.\n *\n * @throws {ValidationError} on an empty component or a non-finite number.\n * @internal\n */\nexport function resolvePeriodKey(name: string, partition?: PeriodPartition): string {\n if (!partition || partition.length === 0) return name\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`period partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('period partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${name}\\x00${parts.join('/')}`\n}\n\n/**\n * Do two partitions denote the same timeline? Absent and empty both mean \"the\n * unpartitioned timeline\", so they compare equal.\n *\n * @internal\n */\nexport function samePartition(a?: PeriodPartition, b?: PeriodPartition): boolean {\n const x = a ?? []\n const y = b ?? []\n if (x.length !== y.length) return false\n return x.every((v, i) => String(v) === String(y[i]))\n}\n\n/**\n * Resolves a record to the timeline that governs it. Supplied by\n * `withPeriods({ subjects })`; returns `undefined` for any collection with no\n * mapping, which is what keeps an unconfigured vault on the single vault-wide\n * timeline it has always had.\n *\n * @internal\n */\nexport type PartitionResolver = (\n collection: string,\n record: Record<string, unknown>,\n) => PeriodPartition | undefined\n\n/**\n * Stored record for one closed or opened accounting period. One entry\n * per period, keyed by `name` in the reserved `_periods` collection.\n *\n * The hash chain between periods is computed at read time by\n * `loadPeriods()` — each record carries the name + hash of its\n * predecessor so a tamper with any period's record breaks the chain\n * into the next one, the same way the ledger's `prevHash` works.\n */\nexport interface PeriodRecord {\n /**\n * Human-readable name (e.g., `'FY2026-Q1'`). Unique per PARTITION — two\n * timelines may each carry a `'2026-06'`, which is the normal case when one\n * vault serves several subjects (#1005). Unique per vault when unpartitioned.\n */\n readonly name: string\n /**\n * The timeline this period belongs to. Absent = the vault-wide timeline.\n * Two periods with the same `name` and different `partition` are unrelated:\n * separate hash chains, separate close state, and the write guard applies\n * each only to records that resolve to its own tuple.\n */\n readonly partition?: PeriodPartition\n /**\n * Role discriminator. A period is `'closed'` from the moment its\n * `closedAt` is recorded; `'opened'` marks a period whose opening\n * entries have been carried forward via {@link openPeriod}. Many\n * workflows will produce one opened period per closed period (the\n * opened one is the SUCCESSOR — its `startDate` equals the prior\n * `endDate + 1 day`).\n */\n readonly kind: 'closed' | 'opened'\n /** ISO date — inclusive upper bound for records belonging to this period. */\n readonly endDate: string\n /** ISO date — lower bound (present on opened periods only). */\n readonly startDate?: string\n /**\n * Record field carrying the business date (e.g. `'date'` on an\n * invoice, `'paidAt'` on a payment). The guard compares\n * `record[dateField]` against `endDate` — NOT the envelope `_ts`.\n * Accounting entries booked late (business date `2026-01-15`,\n * write-time `2026-04-22`) still get sealed when Q1 closes at\n * `2026-03-31` because the comparison uses the business date.\n *\n * Optional for backwards compat. When absent, the guard falls back\n * to envelope `_ts` — that's a write-time seal, appropriate for\n * content that doesn't carry a logical business date (e.g. system\n * settings) but almost never right for accounting ledgers.\n */\n readonly dateField?: string\n /** ISO timestamp recorded at `closePeriod()` / `openPeriod()` call time. */\n readonly closedAt: string\n /** userId of the keyring that invoked the close/open. */\n readonly closedBy: string\n /** Name of the prior period this one chains to, if any. */\n readonly priorPeriodName?: string\n /** sha256(canonicalJson(priorPeriod)) — empty for the first period. */\n readonly priorPeriodHash: string\n /**\n * Opened periods only — the names of the collections whose\n * carry-forward aggregates were written by {@link openPeriod}.\n * Recorded for auditability so a future `verifyPeriodChain()` can\n * cross-check the opening balances against the closing snapshot.\n */\n readonly openingCollections?: readonly string[]\n /** #604 return-only — merged from the `_period_freezes/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record (would break\n * the hash chain). Absent = not yet frozen. */\n readonly frozenAt?: string\n readonly frozenBy?: string\n readonly purgedMarkerCount?: number\n /** #613 return-only — merged from the `_period_archives/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record. Absent = not\n * yet archived. */\n readonly archivedAt?: string\n readonly archivedBy?: string\n readonly archivedRecordCount?: number\n /** #615 return-only — merged from the `_period_target_purges/<name>` companion\n * on read; NEVER written into the stored `_periods/<name>` record. Absent =\n * target-purge not yet run (or the vault has no push-only targets). */\n readonly targetsPurgedAt?: string\n readonly targetsPurgedBy?: string\n readonly targetsPurged?: readonly TargetPurgeCount[]\n /** #1022 return-only — collapsed from the `_period_reopens/<key>` append-only\n * log on read; NEVER written into the stored `_periods/<name>` record, so a\n * reopen cannot disturb the inter-period hash chain. Absent = never reopened.\n * `reclosedAt` present (and >= `reopenedAt`) means the window was closed\n * again explicitly; `reopenedUntil` in the past means it lapsed on its own.\n * Use {@link isEffectivelyReopened} rather than reading these directly. */\n readonly reopenedAt?: string\n readonly reopenedBy?: string\n readonly reopenedUntil?: string\n readonly reopenReason?: string\n readonly reclosedAt?: string\n /** How many times this period has been reopened, ever. */\n readonly reopenCount?: number\n}\n\n/** Options for `vault.closePeriod()`. */\nexport interface ClosePeriodOptions {\n /** Human-readable name. Must not collide with an existing period. */\n readonly name: string\n /**\n * Inclusive upper cutoff. A record is sealed when its\n * `record[dateField]` (or, if absent, the envelope `_ts`) is at or\n * before this ISO timestamp.\n */\n readonly endDate: string\n /**\n * Record field carrying the business date used for period\n * membership. Recommended for accounting workflows — e.g. an\n * invoice booked late (write-time after close) is still sealed\n * when its `invoice.date` falls inside the closed period.\n *\n * Omit to use envelope `_ts` (write-time seal). This fallback\n * rarely matches real-world accounting semantics; prefer passing\n * an explicit `dateField`.\n */\n readonly dateField?: string\n /**\n * Close only this timeline (#1005). Omit for the vault-wide timeline.\n *\n * ```ts\n * vault.closePeriod({\n * name: '2026-06', endDate: '2026-06-30', dateField: 'issuedAt',\n * partition: [clientId, 'vat'],\n * })\n * ```\n *\n * Which records the resulting seal applies to is decided by the\n * `subjects` map passed to `withPeriods()` — without one, no record ever\n * resolves to a partition and a partitioned close seals nothing.\n */\n readonly partition?: PeriodPartition\n}\n\n/** Options for `vault.openPeriod()`. */\nexport interface OpenPeriodOptions<TCollections = Record<string, Record<string, unknown>>> {\n /** Human-readable name for the new period. Must be unique. */\n readonly name: string\n /**\n * The timeline to open in. Must match the partition of `fromPeriod` — a\n * period cannot chain across timelines, since each carries its own hash\n * chain (#1005).\n */\n readonly partition?: PeriodPartition\n /** ISO lower bound of the new period (usually prior `endDate + 1 day`). */\n readonly startDate: string\n /**\n * Name of the prior CLOSED period this one chains from. The prior\n * period's record is verified to exist and to be `kind: 'closed'`;\n * its `endDate` is made available to the `carryForward` callback.\n */\n readonly fromPeriod: string\n /**\n * Receives a read-only facade over the vault's CURRENT state,\n * plus the prior period's `endDate`. Accounting semantics: after\n * a period closes, records with `record[dateField] <= endDate`\n * are frozen — current state equals closing state, so a caller\n * can compute closing balances by querying the live collection\n * with a `where('date', '<=', priorEndDate)` filter.\n *\n * Returns opening-balance records keyed by collection name.\n * Example:\n *\n * ```ts\n * carryForward: async (ctx) => {\n * const closing = await ctx.collection<Journal>('journal')\n * .query().where('date', '<=', ctx.priorEndDate).toArray()\n * const opening: Record<string, Journal> = {}\n * for (const entry of closing) {\n * opening[`OB-${entry.id}`] = { ...entry, date: '2026-04-01' }\n * }\n * return { journal: opening }\n * }\n * ```\n */\n readonly carryForward: (\n ctx: CarryForwardContext,\n ) => Promise<TCollections> | TCollections\n}\n\n/**\n * Context passed to `OpenPeriodOptions.carryForward`. Exposes a\n * read-only subset of the live vault (`collection(name).get/list`)\n * plus the prior period's `endDate` so business-date filters can\n * be built by the caller.\n *\n * Writes go via the return value, not via the facade — the\n * `collection()` here is deliberately restricted to reads.\n */\nexport interface CarryForwardContext {\n /** The prior period's `endDate` — the boundary of the closing snapshot. */\n readonly priorEndDate: string\n /** Read-only collection facade over current vault state. */\n collection<T = unknown>(name: string): ReadOnlyCollection<T>\n}\n\n/** Minimum read surface exposed to `carryForward`. */\nexport interface ReadOnlyCollection<T> {\n get(id: string): Promise<T | null>\n list(): Promise<T[]>\n}\n\n/**\n * Load every period record currently stored on the adapter.\n * Decrypting is the caller's responsibility (we return plain records\n * so the vault can use its own `_periods` DEK).\n *\n * @internal — called by Vault methods that need the closed-period\n * cache. Not part of the public API surface.\n */\nexport async function loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n): Promise<PeriodRecord[]> {\n const ids = await adapter.list(vault, PERIODS_COLLECTION)\n const records: PeriodRecord[] = []\n for (const id of ids) {\n const env = await adapter.get(vault, PERIODS_COLLECTION, id)\n if (env) records.push(await decrypt(id, env))\n }\n // Stable order by closedAt so chain verification is reproducible.\n records.sort((a, b) => a.closedAt.localeCompare(b.closedAt))\n return records\n}\n\n/**\n * Given the current ordered period list, pick the last entry that\n * belongs to the hash chain — used as the `priorPeriodHash` anchor\n * for the next closure/opening.\n *\n * @internal\n */\nexport async function chainAnchor(\n records: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): Promise<{ priorPeriodName?: string; priorPeriodHash: string }> {\n // #1005 — each timeline carries its OWN chain. Anchoring a partitioned close\n // to whatever happened to be written last vault-wide would interleave\n // unrelated subjects into one chain, so verifying client A's June would\n // depend on client B never having closed in between.\n const inTimeline = records.filter((p) => samePartition(p.partition, partition))\n const last = inTimeline[inTimeline.length - 1]\n if (!last) return { priorPeriodHash: '' }\n const hash = await sha256Hex(canonicalJson(last as unknown as Record<string, unknown>))\n return { priorPeriodName: last.name, priorPeriodHash: hash }\n}\n\n/**\n * Throw `PeriodClosedError` if the record being touched falls within\n * any closed period.\n *\n * Three signals, evaluated per period:\n *\n * 1. If the period declares a `dateField`, the guard reads\n * `record[dateField]` on BOTH the existing (prior) record AND the\n * incoming (new) record. Either comparing `<= endDate` triggers\n * the error — callers cannot slide a record into a closed period\n * by editing its date field.\n * 2. If the period has no `dateField`, the guard falls back to the\n * envelope `_ts` of the existing record. Fresh inserts (no\n * existing envelope) pass.\n * 3. For a delete, only the existing side is checked.\n *\n * @internal\n */\nexport function assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incomingRecord: Record<string, unknown> | null,\n closedPeriods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n): void {\n // #1005 — a period only governs records that resolve to ITS timeline. With no\n // resolver (the default `withPeriods()`), nothing resolves to a partition, so\n // every record sits on the vault-wide timeline exactly as before and a\n // partitioned period governs nothing.\n const partitionOf = (r: Record<string, unknown> | null): PeriodPartition | undefined => {\n if (!r || !scope?.resolve) return undefined\n return scope.resolve(scope.collection, r)\n }\n const existingRecord = existing?.record ?? null\n const existingPartition = partitionOf(existingRecord)\n const incomingPartition = partitionOf(incomingRecord)\n // One instant for the whole check, so a bounded reopen window cannot expire\n // between two periods in the same loop and seal a write half-way.\n const now = new Date().toISOString()\n\n for (const p of closedPeriods) {\n if (p.kind !== 'closed') continue\n // #1022 — a reopened period is writable again. This is the ONLY thing a\n // reopen does: it withdraws the period's veto. It cannot grant a write that\n // some other gate forbids, because the guard bus ANDs every handler and\n // record-level guards are registered ahead of this one.\n if (isEffectivelyReopened(p, now)) continue\n if (p.dateField) {\n const checkRecord = (\n label: string,\n r: Record<string, unknown> | null,\n recordPartition: PeriodPartition | undefined,\n ): void => {\n if (!r) return\n // Both sides are checked under their OWN partition, which is what stops\n // a write from sliding a record either INTO or OUT OF a sealed\n // timeline by rewriting the fields the subject mapping reads.\n if (!samePartition(recordPartition, p.partition)) return\n const v = r[p.dateField!]\n if (typeof v === 'string' && v <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, `${label}[${p.dateField}]=${v}`)\n }\n }\n checkRecord('existing', existingRecord, existingPartition)\n checkRecord('incoming', incomingRecord, incomingPartition)\n continue\n }\n // Fallback: write-time seal via envelope _ts. Scoped by the EXISTING\n // record's partition — `_ts` belongs to the stored envelope, so the\n // incoming side has no write-time of its own to compare.\n if (!samePartition(existingPartition, p.partition)) continue\n const existingTs = existing?.ts ?? null\n if (existingTs !== null && existingTs <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, existingTs)\n }\n }\n}\n\n/**\n * Sanity-check a proposed period name + endDate against existing\n * records. Shared by closePeriod / openPeriod so the two pathways\n * produce identical diagnostics.\n *\n * @internal\n */\nexport function validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): void {\n if (name.length === 0) {\n throw new ValidationError('Period name cannot be empty.')\n }\n // Validates the components as a side effect — an empty or non-finite\n // component must be rejected at the call, not encoded into a storage key.\n resolvePeriodKey(name, partition)\n // #1005 — uniqueness is per TIMELINE. `'2026-06'` in `['A','vat']` does not\n // collide with `'2026-06'` in `['B','vat']`.\n if (existing.some((p) => p.name === name && samePartition(p.partition, partition))) {\n const where = partition && partition.length > 0\n ? ` in partition [${partition.join(', ')}]`\n : ''\n throw new ValidationError(`Period \"${name}\" already exists${where}.`)\n }\n}\n\n/**\n * Wire a reserved-collection ledger append for a period record. The\n * period itself is stored via the adapter as an encrypted envelope;\n * the ledger entry is a normal `put` with the period's payloadHash,\n * so period closures inherit the chain's tamper-evidence.\n *\n * @internal\n */\nexport async function appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n name: string,\n collection: string = PERIODS_COLLECTION,\n): Promise<void> {\n if (!ledger) return\n const { envelopePayloadHash } = await import('../../with-commit/history/ledger/index.js')\n await ledger.append({\n op: 'put',\n collection,\n id: name,\n version: envelope._v,\n actor,\n payloadHash: await envelopePayloadHash(envelope),\n })\n}\n\n/**\n * @internal #615. Sweep delete markers with `_ts < before` off ANY store\n * (the vault's local adapter, or a push-only sync target). Returns the count\n * removed. Shared by `vault._purgeDeleteMarkers` (local) and\n * `vault._purgePeriodTargets` (push-only targets).\n */\nexport async function purgeMarkersOn(\n store: NoydbStore,\n vault: string,\n before: string,\n collections?: string[],\n): Promise<number> {\n const snapshot = await store.loadAll(vault)\n let removed = 0\n for (const [coll, records] of Object.entries(snapshot)) {\n if (collections && !collections.includes(coll)) continue\n for (const [id, env] of Object.entries(records)) {\n if (isDeleteMarker(env) && env._ts < before) {\n await store.delete(vault, coll, id)\n removed++\n }\n }\n }\n return removed\n}\n","/**\n * Active periods strategy factory. Only reachable through the\n * `@noy-db/hub/periods` subpath.\n */\n\nimport {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n} from './periods.js'\nimport type { PeriodPartition, PartitionResolver } from './periods.js'\nimport type { PeriodsStrategy } from './strategy.js'\n\n/** Options for {@link withPeriods}. */\nexport interface WithPeriodsOptions {\n /**\n * Maps a collection to the timeline each of its records belongs to (#1005) —\n * the answer to \"which close calendar governs THIS record\".\n *\n * ```ts\n * withPeriods({\n * subjects: { receipts: (r) => [r.clientId, layerOf(r)] },\n * })\n * ```\n *\n * Same shape as `withForget({ subjects })`, which answers the same question\n * for erasure. A collection with no entry — and every collection when\n * `subjects` is omitted entirely — stays on the vault-wide timeline, so an\n * existing vault behaves exactly as it did before partitions existed.\n *\n * Return `undefined` from a mapper to put an individual record back on the\n * vault-wide timeline (e.g. a record that predates the field the mapping\n * reads).\n */\n readonly subjects?: Readonly<\n Record<string, (record: Record<string, unknown>) => PeriodPartition | undefined>\n >\n}\n\n/**\n * Build the default periods strategy. Pass into\n * `createNoydb({ periodsStrategy: withPeriods() })` to enable\n * `vault.closePeriod()` / `vault.openPeriod()` / write-guards.\n *\n * Pass `subjects` to run more than one close calendar in a single vault — see\n * {@link WithPeriodsOptions.subjects}.\n */\nexport function withPeriods(options?: WithPeriodsOptions): PeriodsStrategy {\n const subjects = options?.subjects\n const partitionOf: PartitionResolver | undefined = subjects\n ? (collection, record) => subjects[collection]?.(record)\n : undefined\n\n return {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n ...(partitionOf !== undefined && { partitionOf }),\n }\n}\n","/**\n * Strategy seam for the optional accounting-periods service. Core\n * imports `PeriodsStrategy` type-only + `NO_PERIODS` stub; the real\n * `loadPeriods` / `chainAnchor` / `assertTsWritable` /\n * `validatePeriodName` / `appendPeriodLedgerEntry` functions are\n * only reachable via `withPeriods()` in `./active.ts`.\n *\n * Applications that never call `vault.closePeriod()` /\n * `vault.openPeriod()` ship none of the ~363 LOC.\n *\n * @internal\n */\n\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { PeriodRecord, PeriodPartition, PartitionResolver } from './periods.js'\n\n/**\n * @internal\n */\nexport interface PeriodsStrategy {\n loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n ): Promise<PeriodRecord[]>\n chainAnchor(records: readonly PeriodRecord[], partition?: PeriodPartition): Promise<{\n priorPeriodName?: string\n priorPeriodHash: string\n }>\n assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incoming: Record<string, unknown> | null,\n periods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n ): void\n validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n ): void\n /**\n * Record → timeline resolver built from `withPeriods({ subjects })` (#1005).\n * `undefined` when the caller configured no subjects, which keeps every\n * record on the vault-wide timeline.\n */\n readonly partitionOf?: PartitionResolver\n appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n periodName: string,\n collection?: string,\n ): Promise<void>\n}\n\n/**\n * No-periods stub. `loadPeriods` returns `[]`; the write-guards do\n * nothing (vaults without closed periods never reject writes);\n * `validatePeriodName` / `appendPeriodLedgerEntry` throw because\n * those paths are only reached when the user explicitly called\n * `closePeriod()` / `openPeriod()` — if they did that without the\n * strategy, they need to wire it.\n *\n * @internal\n */\nconst NOT_ENABLED = new Error(\n 'Accounting periods require the periods strategy. Import ' +\n '`{ withPeriods }` from \"@noy-db/hub/periods\" and pass it to ' +\n '`createNoydb({ periodsStrategy: withPeriods() })`.',\n)\n\nexport const NO_PERIODS: PeriodsStrategy = {\n async loadPeriods() { return [] },\n async chainAnchor() { return { priorPeriodHash: '' } },\n assertTsWritable() {},\n validatePeriodName() { throw NOT_ENABLED },\n async appendPeriodLedgerEntry() { throw NOT_ENABLED },\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2PO,SAAS,mBAAmB,QAOjC;AACA,MAAI;AACJ,MAAI;AACJ,MAAI,cAAc;AAClB,aAAW,KAAK,QAAQ;AACtB,QAAI,EAAE,OAAO,UAAU;AACrB,mBAAa;AACb,sBAAgB;AAChB;AAAA,IACF,WAAW,eAAe,QAAW;AACnC,sBAAgB,EAAE;AAAA,IACpB;AAAA,EACF;AACA,MAAI,CAAC,WAAY,QAAO,EAAE,YAAY;AACtC,SAAO;AAAA,IACL,YAAY,WAAW;AAAA,IACvB,YAAY,WAAW;AAAA,IACvB,GAAI,WAAW,UAAU,UAAa,EAAE,eAAe,WAAW,MAAM;AAAA,IACxE,GAAI,WAAW,WAAW,UAAa,EAAE,cAAc,WAAW,OAAO;AAAA,IACzE,GAAI,kBAAkB,UAAa,EAAE,YAAY,cAAc;AAAA,IAC/D;AAAA,E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AA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC7tBO,SAAS,YAAY,SAA+C;AACzE,QAAM,WAAW,SAAS;AAC1B,QAAM,cAA6C,WAC/C,CAAC,YAAY,WAAW,SAAS,UAAU,IAAI,MAAM,IACrD;AAEJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAI,gBAAgB,UAAa,EAAE,YAAY;AAAA,EACjD;AACF;;;ACGA,IAAM,cAAc,IAAI;AAAA,EACtB;AAGF;AAEO,IAAM,aAA8B;AAAA,EACzC,MAAM,cAAc;AAAE,WAAO,CAAC;AAAA,EAAE;AAAA,EAChC,MAAM,cAAc;AAAE,WAAO,EAAE,iBAAiB,GAAG;AAAA,EAAE;AAAA,EACrD,mBAAmB;AAAA,EAAC;AAAA,EACpB,qBAAqB;AAAE,UAAM;AAAA,EAAY;AAAA,EACzC,MAAM,0BAA0B;AAAE,UAAM;AAAA,EAAY;AACtD;","names":[]}
@@ -1,3 +1,10 @@
1
+ import {
2
+ SCHEMAS_COLLECTION
3
+ } from "./chunk-KM6ZXG7U.js";
4
+ import {
5
+ assemblePodContainer,
6
+ buildExtractedPartitionWrapper
7
+ } from "./chunk-GCU42IG7.js";
1
8
  import {
2
9
  BLOB_CHUNKS_COLLECTION,
3
10
  BLOB_COLLECTION,
@@ -5,17 +12,10 @@ import {
5
12
  BLOB_INTENT_COLLECTION,
6
13
  BLOB_SLOTS_PREFIX,
7
14
  BLOB_VERSIONS_PREFIX
8
- } from "./chunk-PL2GHSCM.js";
9
- import {
10
- SCHEMAS_COLLECTION
11
- } from "./chunk-CDB2HVQW.js";
12
- import {
13
- assembleBundleContainer,
14
- buildExtractedPartitionWrapper
15
- } from "./chunk-4VUPLMZ6.js";
15
+ } from "./chunk-JMJSCI7U.js";
16
16
  import {
17
17
  generateULID
18
- } from "./chunk-ZJADGNYF.js";
18
+ } from "./chunk-4AOERLTV.js";
19
19
  import {
20
20
  LEDGER_COLLECTION
21
21
  } from "./chunk-I7FD46FF.js";
@@ -23,11 +23,16 @@ import {
23
23
  canonicalJson,
24
24
  envelopePayloadHash,
25
25
  hashEntry
26
- } from "./chunk-6SAFL5YE.js";
26
+ } from "./chunk-BZ3WMOYX.js";
27
27
  import {
28
+ buildRecordAad,
28
29
  openEnvelopeJson,
30
+ recordAadFor,
29
31
  writeEnvelopeBody
30
- } from "./chunk-3URQC7EH.js";
32
+ } from "./chunk-CXPOG3ZY.js";
33
+ import {
34
+ buildRecordEnvelope
35
+ } from "./chunk-FX3UIDCS.js";
31
36
  import {
32
37
  bufferToBase64,
33
38
  decrypt,
@@ -37,14 +42,13 @@ import {
37
42
  generateDEK,
38
43
  unwrapCek,
39
44
  wrapCek
40
- } from "./chunk-VCETL77O.js";
45
+ } from "./chunk-ONPVHX2Y.js";
41
46
  import {
42
- NOYDB_BACKUP_VERSION,
43
- NOYDB_FORMAT_VERSION
44
- } from "./chunk-YPYHVOXP.js";
47
+ NOYDB_BACKUP_VERSION
48
+ } from "./chunk-UJ4Z67UQ.js";
45
49
  import {
46
50
  PartitionExtractionError
47
- } from "./chunk-HNGSV2YC.js";
51
+ } from "./chunk-Z3BZXPRO.js";
48
52
 
49
53
  // src/with-cargo/walk-closure.ts
50
54
  async function walkClosure(vault, opts) {
@@ -185,15 +189,16 @@ async function reKeyClosure(vault, closure, fieldProjection) {
185
189
  );
186
190
  }
187
191
  if (env._cek !== void 0) {
192
+ const aad = recordAadFor({ collection: collectionName, id }, env);
188
193
  const cek = await unwrapCek(env._cek, srcDek);
189
- const plaintext2 = await decrypt(env._iv, env._data, cek);
190
- const { iv: iv2, data: data2 } = await encrypt(project(plaintext2), cek);
194
+ const plaintext2 = await decrypt(env._iv, env._data, cek, aad);
195
+ const { iv: iv2, data: data2 } = await encrypt(project(plaintext2), cek, aad);
191
196
  const wrapped = await wrapCek(cek, destDek);
192
197
  out[id] = { ...env, _iv: iv2, _data: data2, _cek: wrapped };
193
198
  continue;
194
199
  }
195
- const plaintext = await openEnvelopeJson(env, srcDek);
196
- const { iv, data } = await encrypt(project(plaintext), destDek);
200
+ const plaintext = await openEnvelopeJson({ collection: collectionName, id }, env, srcDek);
201
+ const { iv, data } = await encrypt(project(plaintext), destDek, recordAadFor({ collection: collectionName, id }, env));
197
202
  out[id] = { ...env, _iv: iv, _data: data };
198
203
  }
199
204
  collections[collectionName] = out;
@@ -210,8 +215,8 @@ async function reKeySchemas(vault, closure, destDeks, fieldProjection) {
210
215
  const destDek = destDeks.get(collectionName);
211
216
  if (!destDek) continue;
212
217
  const srcDek = await getDEK(collectionName);
213
- const plaintext = await openEnvelopeJson(env, srcDek);
214
- const { iv, data } = await encrypt(plaintext, destDek);
218
+ const plaintext = await openEnvelopeJson({ collection: SCHEMAS_COLLECTION, id: collectionName }, env, srcDek);
219
+ const { iv, data } = await encrypt(plaintext, destDek, recordAadFor({ collection: SCHEMAS_COLLECTION, id: collectionName }, env));
215
220
  out[collectionName] = { ...env, _iv: iv, _data: data };
216
221
  }
217
222
  return out;
@@ -225,7 +230,7 @@ async function reKeyLedger(vault, closure, reKeyedCollections, ledgerDek) {
225
230
  for (const id of ids) {
226
231
  const env = await adapter.get(vaultName, LEDGER_COLLECTION, id);
227
232
  if (!env) continue;
228
- srcEntries.push(JSON.parse(await openEnvelopeJson(env, srcLedgerDek)));
233
+ srcEntries.push(JSON.parse(await openEnvelopeJson({ collection: LEDGER_COLLECTION, id }, env, srcLedgerDek)));
229
234
  }
230
235
  const kept = srcEntries.filter(
231
236
  (e) => (e.op === "put" || e.op === "delete") && (closure.get(e.collection)?.has(e.id) ?? false)
@@ -258,15 +263,12 @@ async function reKeyLedger(vault, closure, reKeyedCollections, ledgerDek) {
258
263
  payloadHash,
259
264
  ...src.reason !== void 0 ? { reason: src.reason } : {}
260
265
  };
261
- const { iv, data } = await encrypt(canonicalJson(entry), ledgerDek);
262
- entries[paddedIndex(i)] = {
263
- _noydb: NOYDB_FORMAT_VERSION,
264
- _v: i + 1,
265
- _ts: entry.ts,
266
- _iv: iv,
267
- _data: data,
268
- _by: entry.actor
269
- };
266
+ const ledgerIdentity = { collection: LEDGER_COLLECTION, id: paddedIndex(i), version: i + 1 };
267
+ const { iv, data } = await encrypt(canonicalJson(entry), ledgerDek, buildRecordAad(ledgerIdentity));
268
+ entries[paddedIndex(i)] = buildRecordEnvelope(
269
+ ledgerIdentity,
270
+ { ts: entry.ts, iv, data }
271
+ );
270
272
  prevHash = await hashEntry(entry);
271
273
  last = entry;
272
274
  }
@@ -305,8 +307,8 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
305
307
  const intentId = `${collectionName}::${id}`;
306
308
  const intentEnv = await adapter.get(vaultName, BLOB_INTENT_COLLECTION, intentId);
307
309
  if (intentEnv) {
308
- const intentPlain = await openEnvelopeJson(intentEnv, srcDek);
309
- const intentBody = await writeEnvelopeBody(intentPlain, destDek);
310
+ const intentPlain = await openEnvelopeJson({ collection: BLOB_INTENT_COLLECTION, id: intentId }, intentEnv, srcDek);
311
+ const intentBody = await writeEnvelopeBody({ collection: BLOB_INTENT_COLLECTION, id: intentId, version: intentEnv._v }, intentPlain, destDek);
310
312
  place(BLOB_INTENT_COLLECTION, intentId, { ...intentEnv, ...intentBody });
311
313
  }
312
314
  const env = await adapter.get(vaultName, slotsCollection, id);
@@ -316,7 +318,7 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
316
318
  `#748: reKeyBlobs fetched an elevated slot-map envelope (collection="${slotsCollection}" id="${id}" _tier=${env._tier}) \u2014 this is unreachable by construction. Refusing to carry it into a partition.`
317
319
  );
318
320
  }
319
- const slots = JSON.parse(await openEnvelopeJson(env, srcDek));
321
+ const slots = JSON.parse(await openEnvelopeJson({ collection: slotsCollection, id }, env, srcDek));
320
322
  const kept = {};
321
323
  for (const [slotName, slot] of Object.entries(slots)) {
322
324
  if (proj && !proj.has(slotName)) continue;
@@ -326,7 +328,7 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
326
328
  addRef(slot.eTag);
327
329
  }
328
330
  if (Object.keys(kept).length === 0) continue;
329
- const { iv, data } = await encrypt(JSON.stringify(kept), destDek);
331
+ const { iv, data } = await encrypt(JSON.stringify(kept), destDek, recordAadFor({ collection: slotsCollection, id }, env));
330
332
  place(slotsCollection, id, { ...env, _iv: iv, _data: data });
331
333
  }
332
334
  const versionsCollection = `${BLOB_VERSIONS_PREFIX}${collectionName}`;
@@ -342,9 +344,9 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
342
344
  `#748: reKeyBlobs fetched an elevated version-record envelope (collection="${versionsCollection}" key="${key}" _tier=${env._tier}) \u2014 this is unreachable by construction. Refusing to carry it into a partition.`
343
345
  );
344
346
  }
345
- const record = JSON.parse(await openEnvelopeJson(env, srcDek));
347
+ const record = JSON.parse(await openEnvelopeJson({ collection: versionsCollection, id: key }, env, srcDek));
346
348
  addRef(record.eTag);
347
- const { iv, data } = await encrypt(JSON.stringify(record), destDek);
349
+ const { iv, data } = await encrypt(JSON.stringify(record), destDek, recordAadFor({ collection: versionsCollection, id: key }, env));
348
350
  place(versionsCollection, key, { ...env, _iv: iv, _data: data });
349
351
  }
350
352
  }
@@ -354,7 +356,7 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
354
356
  for (const [eTag, refCount] of carriedRefs) {
355
357
  const idxEnv = await adapter.get(vaultName, BLOB_INDEX_COLLECTION, eTag);
356
358
  if (!idxEnv) continue;
357
- const blob = JSON.parse(await openEnvelopeJson(idxEnv, srcBlobDek));
359
+ const blob = JSON.parse(await openEnvelopeJson({ collection: BLOB_INDEX_COLLECTION, id: eTag }, idxEnv, srcBlobDek));
358
360
  let contentCek;
359
361
  let chunksPassthrough;
360
362
  if (blob._cek !== void 0) {
@@ -384,7 +386,7 @@ async function reKeyBlobs(vault, closure, destDeks, fieldProjection) {
384
386
  const { _cekPending, ...rest } = blob;
385
387
  void _cekPending;
386
388
  const carried = { ...rest, refCount, _cek: await wrapCek(contentCek, transferBlobDek) };
387
- const { iv, data } = await encrypt(JSON.stringify(carried), transferBlobDek);
389
+ const { iv, data } = await encrypt(JSON.stringify(carried), transferBlobDek, recordAadFor({ collection: BLOB_INDEX_COLLECTION, id: eTag }, idxEnv));
388
390
  place(BLOB_INDEX_COLLECTION, eTag, { ...idxEnv, _iv: iv, _data: data });
389
391
  }
390
392
  return { internal, blobDek: transferBlobDek };
@@ -469,7 +471,7 @@ async function extractPartitionCore(vault, opts) {
469
471
  };
470
472
  const bodyJsonStr = JSON.stringify(buildExtractedPartitionWrapper(JSON.stringify(backup), seal));
471
473
  const handle = generateULID();
472
- const bundleBytes = await assembleBundleContainer({
474
+ const bundleBytes = await assemblePodContainer({
473
475
  handle,
474
476
  bodyJsonStr,
475
477
  compression: opts.compression,
@@ -492,4 +494,4 @@ export {
492
494
  extractPartition,
493
495
  extractPartitionCore
494
496
  };
495
- //# sourceMappingURL=chunk-4GZ6XOVW.js.map
497
+ //# sourceMappingURL=chunk-5F7BZAGV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-cargo/walk-closure.ts","../src/with-cargo/extract-partition.ts"],"sourcesContent":["/**\n * Transitive-closure FK walker. Computes the set of\n * (collection, id) tuples reachable from seed predicates, so a\n * partition extraction ships a referentially-complete subset.\n *\n * Two-phase, plaintext, read-only (runs inside the unlocked vault\n * session — see foundation §13.4 / spec invariant 7):\n * 1. INBOUND expansion: from selected records, pull every record\n * that references them (children travel with parents), to a\n * fixed point.\n * 2. OUTBOUND completion: pull every VISIBLE parent the selected set\n * references, transitively, WITHOUT re-expanding inbound from those\n * parents (bounds the closure). A tier-elevated (or missing) parent is\n * excluded rather than admitted — see `danglingRefs` on the result.\n *\n * The FK graph is auto-derived from the vault's existing RefRegistry\n * (the `ref('target')` declarations on collections) — no hand-written\n * edge list.\n *\n * @module\n */\nimport type { Vault } from '../kernel/vault.js'\nimport { PartitionExtractionError } from '../kernel/errors.js'\n\n/** Seed predicate per collection. Records that return true become roots. */\nexport interface WalkClosureOptions {\n readonly seeds: Record<\n string,\n (record: Record<string, unknown>) => boolean | Promise<boolean>\n >\n /** Max fixed-point iterations before throwing. Default 16. */\n readonly maxDepth?: number\n}\n\n/**\n * #759: an outbound FK edge whose referenced parent was excluded from the\n * closure — either because it doesn't exist, or because it is tier-elevated\n * and therefore invisible (same \"elevated ≡ missing\" semantics as root\n * selection / inbound expansion). The child keeps its FK value; the parent\n * does not travel. Callers (extract-partition) surface this as a residue\n * notice rather than silently dropping it.\n */\nexport interface DanglingRefNotice {\n /** Collection of the child record that holds the dangling FK. */\n readonly collection: string\n /** Id of the child record. */\n readonly id: string\n /** FK field on the child that references the missing/elevated parent. */\n readonly field: string\n /** Target collection the FK points at. */\n readonly target: string\n /** Id of the missing/elevated parent. */\n readonly targetId: string\n /**\n * #772: distinguishes an intentional tier boundary (`'elevated'` — the\n * parent exists but is above the caller's readable tier) from a genuine\n * data-integrity gap (`'missing'` — no envelope for `targetId` at all).\n */\n readonly reason: 'missing' | 'elevated'\n}\n\nexport interface ClosureResult {\n /** collection → set of record ids that travel together. */\n readonly closure: Map<string, Set<string>>\n readonly graph: {\n /** Fixed-point iterations the walk needed to converge. */\n readonly depth: number\n /** True if an edge pointed back to an already-selected node. */\n readonly cyclesDetected: boolean\n }\n /** #759: outbound FK edges whose parent was excluded (missing or elevated). */\n readonly danglingRefs: ReadonlyArray<DanglingRefNotice>\n}\n\nexport async function walkClosure(\n vault: Vault,\n opts: WalkClosureOptions,\n): Promise<ClosureResult> {\n const closure = new Map<string, Set<string>>()\n\n // Records carry a string `id` by construction (Collection.put(id: string)).\n // A non-string id during the walk means a malformed record — fail loud\n // rather than silently dropping it from the closure (which would leave a\n // dangling FK or a missing child in the extracted bundle).\n const requireStringId = (collection: string, record: Record<string, unknown>): string => {\n const id = record['id']\n if (typeof id !== 'string') {\n throw new PartitionExtractionError(\n `walkClosure: record in collection \"${collection}\" has a non-string ` +\n `id (${typeof id}); cannot include it in the partition closure.`,\n )\n }\n return id\n }\n\n const add = (collection: string, id: string): boolean => {\n let set = closure.get(collection)\n if (!set) {\n set = new Set<string>()\n closure.set(collection, set)\n }\n if (set.has(id)) return false\n set.add(id)\n return true\n }\n\n // Phase 0: evaluate seed predicates.\n for (const [collectionName, predicate] of Object.entries(opts.seeds)) {\n const coll = vault.collection<Record<string, unknown>>(collectionName)\n const records = await coll.list()\n for (const record of records) {\n if (await predicate(record)) {\n add(collectionName, requireStringId(collectionName, record))\n }\n }\n }\n\n const { refRegistry, adapter, name: vaultName } = vault._introspectState()\n const maxDepth = opts.maxDepth ?? 16\n let cyclesDetected = false\n\n // `depth` counts PRODUCTIVE expansion generations (rounds that added at\n // least one new record), taken as the max over the two phases — i.e. the\n // FK hop-distance the closure needed, not the raw loop-iteration count.\n // The terminal draining pass that adds nothing does not count.\n let inboundDepth = 0\n let outboundDepth = 0\n\n // Phase 1 — INBOUND expansion. Worklist of newly-added (collection,id)\n // whose children we still need to pull.\n let frontier: Array<[string, string]> = []\n for (const [c, ids] of closure) for (const id of ids) frontier.push([c, id])\n\n while (frontier.length > 0) {\n const next: Array<[string, string]> = []\n for (const [collectionName, id] of frontier) {\n // Which collections reference THIS collection, and via which field?\n for (const inbound of refRegistry.getInbound(collectionName)) {\n const childColl = vault.collection<Record<string, unknown>>(inbound.collection)\n // TODO(perf): re-scans the full inbound collection on every frontier\n // element. O(frontier · inboundCollections · records) per depth. Fine\n // at consumer-firm scale (foundation §13.4); revisit with an index or\n // pagination if extraction over very large vaults gets slow.\n const childRecords = await childColl.list()\n for (const child of childRecords) {\n const fk = child[inbound.field]\n // Only scalar FK values can match an id; skip null/objects\n // (mirrors checkIntegrity's scalar guard, vault.ts).\n if (typeof fk !== 'string' && typeof fk !== 'number') continue\n if (String(fk) !== id) continue\n const childId = requireStringId(inbound.collection, child)\n if (add(inbound.collection, childId)) {\n next.push([inbound.collection, childId])\n } else {\n cyclesDetected = true\n }\n }\n }\n }\n if (next.length > 0 && ++inboundDepth > maxDepth) {\n throw new PartitionExtractionError(\n `walkClosure exceeded maxDepth=${maxDepth}; the FK graph may be ` +\n `unexpectedly deep or cyclic. Raise maxDepth or narrow the seeds.`,\n )\n }\n frontier = next\n }\n\n // Phase 2 — OUTBOUND completion. Pull referenced parents so no FK\n // dangles. Transitive over outbound edges only; parents are NOT\n // inbound-expanded (that would drag in unrelated siblings).\n let outboundFrontier: Array<[string, string]> = []\n for (const [c, ids] of closure) for (const id of ids) outboundFrontier.push([c, id])\n\n const danglingRefs: DanglingRefNotice[] = []\n\n while (outboundFrontier.length > 0) {\n const next: Array<[string, string]> = []\n for (const [collectionName, id] of outboundFrontier) {\n const outbound = refRegistry.getOutbound(collectionName)\n if (Object.keys(outbound).length === 0) continue\n const coll = vault.collection<Record<string, unknown>>(collectionName)\n const record = await coll.get(id)\n if (!record) continue\n for (const [field, descriptor] of Object.entries(outbound)) {\n const rawId = record[field]\n // Only scalar FK values reference a parent id; skip null/objects.\n if (typeof rawId !== 'string' && typeof rawId !== 'number') continue\n const parentId = String(rawId)\n // #759: verify the referenced parent is visible through the SAME\n // tier-gated primitive root selection / inbound expansion use\n // (`Collection.get()` → `#getRaw`, which returns null for both a\n // missing record and a tier-elevated one). An elevated parent must\n // be excluded exactly like an elevated root or inbound target —\n // \"elevated ≡ invisible\" — rather than admitted into the closure,\n // where `reKeyClosure`'s raw adapter read would later hit it and\n // fail loud (the #748 canary). Record the resulting dangling FK\n // instead of silently dropping it.\n const parentColl = vault.collection<Record<string, unknown>>(descriptor.target)\n const parentRecord = await parentColl.get(parentId)\n if (!parentRecord) {\n // #772: a raw (tier-unaware) read distinguishes the two cases the\n // tier-gated `Collection.get()` above collapses to the same null —\n // an envelope present with `_tier > 0` is an intentional tier\n // boundary; no envelope at all is a genuine data-integrity gap.\n const rawParentEnv = await adapter.get(vaultName, descriptor.target, parentId)\n const reason: 'missing' | 'elevated' =\n rawParentEnv && (rawParentEnv._tier ?? 0) > 0 ? 'elevated' : 'missing'\n danglingRefs.push({\n collection: collectionName, id, field, target: descriptor.target, targetId: parentId, reason,\n })\n continue\n }\n // Reaching an already-selected parent here is normal DAG\n // convergence (a child referencing its in-scope parent), not a\n // cycle — so do NOT flag cyclesDetected in the outbound phase.\n if (add(descriptor.target, parentId)) {\n next.push([descriptor.target, parentId])\n }\n }\n }\n if (next.length > 0 && ++outboundDepth > maxDepth) {\n throw new PartitionExtractionError(\n `walkClosure exceeded maxDepth=${maxDepth} during outbound completion.`,\n )\n }\n outboundFrontier = next\n }\n\n const depth = Math.max(inboundDepth, outboundDepth)\n\n return { closure, graph: { depth, cyclesDetected }, danglingRefs }\n}\n","/**\n * Partition extraction. Walks the FK closure, re-encrypts\n * the selected records under fresh per-collection DEKs, seals those DEKs\n * under a one-time transfer key, and serializes an unowned\n * `extracted-partition` bundle.\n *\n * @module\n */\nimport type { Vault } from '../kernel/vault.js'\nimport type { EncryptedEnvelope, BlobObject, SlotRecord, VersionRecord } from '../kernel/types.js'\nimport { NOYDB_BACKUP_VERSION } from '../kernel/types.js'\nimport { buildRecordAad, recordAadFor,\n decrypt,\n encrypt,\n openEnvelopeJson,\n writeEnvelopeBody,\n generateDEK,\n bufferToBase64,\n encryptBytesWithAAD,\n decryptBytesWithAAD,\n unwrapCek,\n wrapCek,\n type EnclaveKey,\n} from '../kernel/enclave/index.js'\nimport {\n BLOB_COLLECTION,\n BLOB_INDEX_COLLECTION,\n BLOB_CHUNKS_COLLECTION,\n BLOB_SLOTS_PREFIX,\n BLOB_VERSIONS_PREFIX,\n} from '../with-shape/blobs/blob-set.js'\nimport { BLOB_INTENT_COLLECTION } from '../with-shape/blobs/blob-intent.js'\nimport { PartitionExtractionError } from '../kernel/errors.js'\nimport { walkClosure, type WalkClosureOptions, type DanglingRefNotice } from './walk-closure.js'\nimport { generateULID } from '../with-pod/ulid.js'\nimport { SCHEMAS_COLLECTION } from '../with-shape/persisted-schemas/storage.js'\nimport { LEDGER_COLLECTION } from '../with-commit/history/ledger/constants.js'\nimport { canonicalJson, hashEntry } from '../with-commit/history/ledger/entry.js'\nimport type { LedgerEntry } from '../with-commit/history/ledger/entry.js'\nimport { envelopePayloadHash } from '../with-commit/history/ledger/hash.js'\nimport { buildRecordEnvelope } from '../kernel/enclave/index.js'\nimport {\n assemblePodContainer,\n buildExtractedPartitionWrapper,\n type TransferSealPayload,\n} from '../with-pod/pod.js'\n\n/** Re-keyed collections snapshot + the fresh DEKs used. */\nexport interface ReKeyResult {\n readonly collections: Record<string, Record<string, EncryptedEnvelope>>\n readonly deks: Map<string, EnclaveKey>\n}\n\n/**\n * Re-encrypt every record in `closure` under a fresh per-collection DEK.\n * Reads raw source envelopes, decrypts under the source DEK, re-encrypts\n * under the new DEK. Plaintext-pipeline: requires an unlocked vault.\n */\nexport async function reKeyClosure(\n vault: Vault,\n closure: Map<string, Set<string>>,\n fieldProjection?: Record<string, readonly string[]>,\n): Promise<ReKeyResult> {\n const { name: vaultName, adapter, getDEK } = vault._introspectState()\n const collections: Record<string, Record<string, EncryptedEnvelope>> = {}\n const deks = new Map<string, EnclaveKey>()\n\n for (const [collectionName, ids] of closure) {\n const srcDek = await getDEK(collectionName)\n const destDek = await generateDEK()\n deks.set(collectionName, destDek)\n const out: Record<string, EncryptedEnvelope> = {}\n // FR-7 structural field projection: when this collection has a projection,\n // narrow the plaintext body to `id` (always) + the listed fields BEFORE\n // re-encryption, so excluded fields never travel in the bundle. Applied\n // identically in both re-key branches; only the body changes — the `_cek`\n // re-wrap order is untouched. Absent/empty projection → byte-identical to\n // the un-projected path (`proj` is undefined and `project` is a no-op).\n const projList = fieldProjection?.[collectionName]\n const proj = projList ? new Set(projList) : undefined\n const project = (plaintext: string): string => {\n if (!proj) return plaintext\n const rec = JSON.parse(plaintext) as Record<string, unknown>\n const kept: Record<string, unknown> = {}\n if ('id' in rec) kept['id'] = rec['id'] // id ALWAYS preserved\n for (const f of proj) if (f in rec) kept[f] = rec[f]\n return JSON.stringify(kept)\n }\n\n for (const id of ids) {\n const env = await adapter.get(vaultName, collectionName, id)\n if (!env) continue\n // #748 defense-in-depth canary: `closure` is built exclusively through\n // tier-gated `Collection.list()`/`get()` (collection.ts `ensureHydrated`\n // / `#getRaw` both skip `_tier > 0` envelopes), so an elevated record\n // can never reach this raw `adapter.get` fetch — this should be\n // unreachable by construction. Not a user-facing guard; a cheap tripwire\n // in case that invariant ever regresses.\n if ((env._tier ?? 0) > 0) {\n throw new PartitionExtractionError(\n `#748: reKeyClosure fetched an elevated envelope (collection=\"${collectionName}\" id=\"${id}\" `\n + `_tier=${env._tier}) — this is unreachable by construction (walkClosure only ever adds ids `\n + `reachable through tier-gated Collection reads). Refusing to carry it into a partition.`,\n )\n }\n if (env._cek !== undefined) {\n // Per-record CEK: a naive `{ ...env }` spread would carry a\n // SOURCE-DEK-wrapped CEK into a bundle re-keyed under a different\n // destination DEK — silently undecryptable for the recipient.\n // Re-wrap: unwrap the CEK under the source DEK, re-encrypt the body\n // under the SAME CEK (decision 2 — CEK reused on re-key, preserving\n // the history-chain identity), then wrap the CEK under the fresh\n // destination DEK. The recipient gains access transitively once they\n // re-wrap the collection DEK under their KEK on adopt.\n // Identity is UNCHANGED by extraction — collection/id/_tier/_by all\n // travel with the record, and `vault` is deliberately unbound (the ADR's\n // constraint (c) exists precisely so adoption can re-home a partition).\n // So the same AAD opens the source and seals the destination (#1041).\n const aad = recordAadFor({ collection: collectionName, id }, env)\n const cek = await unwrapCek(env._cek, srcDek)\n const plaintext = await decrypt(env._iv, env._data, cek, aad)\n const { iv, data } = await encrypt(project(plaintext), cek, aad)\n const wrapped = await wrapCek(cek, destDek)\n out[id] = { ...env, _iv: iv, _data: data, _cek: wrapped }\n continue\n }\n const plaintext = await openEnvelopeJson({ collection: collectionName, id }, env, srcDek)\n const { iv, data } = await encrypt(project(plaintext), destDek, recordAadFor({ collection: collectionName, id }, env))\n out[id] = { ...env, _iv: iv, _data: data }\n }\n collections[collectionName] = out\n }\n\n return { collections, deks }\n}\n\n/**\n * Re-key the persisted JSON Schemas (`_schemas/<collection>`) for the\n * closure collections under the destination DEKs. Returns a\n * `{ collection: envelope }` map for the carried collections that actually\n * have a schema; collections without one are omitted.\n */\nexport async function reKeySchemas(\n vault: Vault,\n closure: Map<string, Set<string>>,\n destDeks: Map<string, EnclaveKey>,\n fieldProjection?: Record<string, readonly string[]>,\n): Promise<Record<string, EncryptedEnvelope>> {\n const { name: vaultName, adapter, getDEK } = vault._introspectState()\n const out: Record<string, EncryptedEnvelope> = {}\n\n for (const collectionName of closure.keys()) {\n // FR-7: skip a projected collection's schema — the narrowed shape no\n // longer matches the stored JSON Schema, so carrying it would assert a\n // contract the projected records violate (missing required fields).\n if (fieldProjection?.[collectionName]) continue\n const env = await adapter.get(vaultName, SCHEMAS_COLLECTION, collectionName)\n if (!env) continue // collection has no persisted schema — skip\n const destDek = destDeks.get(collectionName)\n if (!destDek) continue\n const srcDek = await getDEK(collectionName)\n const plaintext = await openEnvelopeJson({ collection: SCHEMAS_COLLECTION, id: collectionName }, env, srcDek)\n const { iv, data } = await encrypt(plaintext, destDek, recordAadFor({ collection: SCHEMAS_COLLECTION, id: collectionName }, env))\n out[collectionName] = { ...env, _iv: iv, _data: data }\n }\n return out\n}\n\nconst paddedIndex = (n: number): string => String(n).padStart(10, '0')\n\nexport interface ReKeyLedgerResult {\n /** { paddedIndex: re-encrypted entry envelope } for backup._internal._ledger. */\n readonly entries: Record<string, EncryptedEnvelope>\n /** Recomputed ledgerHead for the carried chain (index -1 when empty). */\n readonly head: { hash: string; index: number; ts: string }\n}\n\n/**\n * Build the carried `_ledger` chain for an extracted partition.\n * Filters source entries to the closure, RE-CHAINS them (fresh index + prevHash),\n * and re-encrypts under `ledgerDek`. The `payloadHash` is recomputed against the\n * re-keyed envelope ONLY for the latest `put` per (collection,id) — the entry\n * `verifyBackupIntegrity` cross-checks; earlier puts + deletes keep their source\n * `payloadHash` verbatim (recomputing an intermediate put would assert a false\n * hash for an older version). Amendments + out-of-closure entries are dropped;\n * `_ledger_deltas`/`_history` are deferred to slice 2.\n */\nexport async function reKeyLedger(\n vault: Vault,\n closure: Map<string, Set<string>>,\n reKeyedCollections: Record<string, Record<string, EncryptedEnvelope>>,\n ledgerDek: EnclaveKey,\n): Promise<ReKeyLedgerResult> {\n const { name: vaultName, adapter, getDEK } = vault._introspectState()\n const srcLedgerDek = await getDEK(LEDGER_COLLECTION)\n\n // 1. Load + decrypt source entries in index order.\n const ids = (await adapter.list(vaultName, LEDGER_COLLECTION)).sort()\n const srcEntries: LedgerEntry[] = []\n for (const id of ids) {\n const env = await adapter.get(vaultName, LEDGER_COLLECTION, id)\n if (!env) continue\n srcEntries.push(JSON.parse(await openEnvelopeJson({ collection: LEDGER_COLLECTION, id }, env, srcLedgerDek)) as LedgerEntry)\n }\n\n // 2. Keep closure put/delete entries (drop amendments + out-of-closure).\n const kept = srcEntries.filter(\n (e) => (e.op === 'put' || e.op === 'delete') && (closure.get(e.collection)?.has(e.id) ?? false),\n )\n\n // 3a. Reverse pass: index of the LATEST put per (collection,id).\n const latestPutIndex = new Map<string, number>()\n for (let i = kept.length - 1; i >= 0; i--) {\n const e = kept[i]!\n if (e.op !== 'put') continue\n const key = `${e.collection}/${e.id}`\n if (!latestPutIndex.has(key)) latestPutIndex.set(key, i)\n }\n\n // 3b. Forward re-chain + re-encrypt.\n const entries: Record<string, EncryptedEnvelope> = {}\n let prevHash = ''\n let last: LedgerEntry | undefined\n for (let i = 0; i < kept.length; i++) {\n const src = kept[i]!\n const key = `${src.collection}/${src.id}`\n const isLatestPut = src.op === 'put' && latestPutIndex.get(key) === i\n const reKeyedEnv = reKeyedCollections[src.collection]?.[src.id]\n const payloadHash = isLatestPut && reKeyedEnv\n ? await envelopePayloadHash(reKeyedEnv)\n : src.payloadHash\n const entry: LedgerEntry = {\n index: i,\n prevHash,\n op: src.op,\n collection: src.collection,\n id: src.id,\n version: src.version,\n ts: src.ts,\n actor: src.actor,\n payloadHash,\n ...(src.reason !== undefined ? { reason: src.reason } : {}),\n }\n const ledgerIdentity = { collection: LEDGER_COLLECTION, id: paddedIndex(i), version: i + 1 }\n const { iv, data } = await encrypt(canonicalJson(entry), ledgerDek, buildRecordAad(ledgerIdentity))\n entries[paddedIndex(i)] = buildRecordEnvelope(\n ledgerIdentity,\n { ts: entry.ts, iv, data},\n )\n prevHash = await hashEntry(entry)\n last = entry\n }\n\n return {\n entries,\n head: last ? { hash: prevHash, index: last.index, ts: last.ts } : { hash: '', index: -1, ts: '' },\n }\n}\n\n/** Build the AAD binding for chunk integrity: \"{eTag}:{chunkIndex}:{chunkCount}\".\n * Mirrors `chunkAAD` in blob-set.ts — the eTag is preserved verbatim across\n * the transfer (see `reKeyBlobs`), so the same AAD that bound a chunk in the\n * source keeps binding it in the bundle. */\nfunction chunkAAD(eTag: string, chunkIndex: number, chunkCount: number): Uint8Array {\n return new TextEncoder().encode(`${eTag}:${chunkIndex}:${chunkCount}`)\n}\n\n/** Carried blob internals + the fresh transfer `_blob` DEK (present only when\n * the closure references at least one chunk-based blob). */\nexport interface ReKeyBlobsResult {\n /** `_blob_slots_<C>` / `_blob_versions_<C>` / `_blob_index` / `_blob_chunks`\n * envelopes for the bundle's `_internal` map. */\n readonly internal: Record<string, Record<string, EncryptedEnvelope>>\n /** Fresh transfer `_blob` DEK — seal it so owner-creation wraps it under the\n * recipient KEK. Undefined when no blob travels (source keyring untouched). */\n readonly blobDek?: EnclaveKey\n}\n\n/**\n * Carry the FK-closed slice's blobs — HARDENED key handling (no master-key leak).\n *\n * The source vault's shared `_blob` DEK decrypts (or unwraps the content CEK of)\n * EVERY blob in the source. Sealing it into the transfer would hand the recipient\n * a key to blobs far outside their slice. Instead we mint a **fresh transfer\n * `_blob` DEK** and arrange every carried blob into per-blob-CEK mode under it:\n *\n * - **erasable blob** (`_cek` present): unwrap the per-blob content CEK under the\n * SOURCE `_blob` DEK, re-wrap it under the FRESH transfer DEK. Chunks travel\n * **verbatim** (still ciphertext under that same content CEK — passthrough).\n * - **legacy blob** (no `_cek`, chunks under the shared `_blob` DEK): promote it\n * IN-BUNDLE — mint a fresh content CEK, decrypt each chunk under the source\n * `_blob` DEK and re-encrypt under the content CEK (same AAD, so the eTag-bound\n * integrity holds), then wrap the content CEK under the transfer DEK. The\n * SOURCE is never mutated (non-destructive), and the bundle never holds\n * plaintext blob bytes (zero-knowledge preserved).\n *\n * **eTag identity is preserved** (not re-HMAC'd). eTags are HMAC-keyed off the\n * `_blob` DEK, but they are stored as OPAQUE keys (`_blob_index/<eTag>`,\n * `_blob_chunks/<eTag>_<i>`) and never recomputed on read — only on a `put()`\n * for dedup. Keeping them verbatim keeps every slot/version/index/chunk key and\n * the chunk AAD coherent with zero chunk-key churn. The only consequence: a\n * future `put()` of identical bytes in the adopted vault computes a different\n * eTag (HMAC under the fresh DEK) and will NOT dedup against the carried blob —\n * an accepted, documented trade for hardened key isolation.\n *\n * Slots/versions are re-keyed under their parent collection's destination DEK\n * (honoring `fieldProjection` — projected-out blob fields' slots never travel);\n * `BlobObject.refCount` is recomputed from carried references only.\n *\n * `external` slots reference an unencrypted shared-bucket object that is not in\n * the bundle — their slot metadata travels (so the catalog entry survives) but\n * the bytes do not (a documented v1 limitation; their eTag is `''`).\n */\nexport async function reKeyBlobs(\n vault: Vault,\n closure: Map<string, Set<string>>,\n destDeks: Map<string, EnclaveKey>,\n fieldProjection?: Record<string, readonly string[]>,\n): Promise<ReKeyBlobsResult> {\n const { name: vaultName, adapter, getDEK } = vault._introspectState()\n const internal: Record<string, Record<string, EncryptedEnvelope>> = {}\n\n // travel set: eTag → number of carried references (slots + versions) within\n // the closure. Recomputed refCount, NOT the source's (which may count\n // out-of-slice referrers, leaving the adopted blob un-GC-able).\n const carriedRefs = new Map<string, number>()\n const addRef = (eTag: string): void => {\n if (!eTag) return // external slot — no chunk-based blob to carry\n carriedRefs.set(eTag, (carriedRefs.get(eTag) ?? 0) + 1)\n }\n\n const place = (collection: string, id: string, env: EncryptedEnvelope): void => {\n let bucket = internal[collection]\n if (!bucket) { bucket = {}; internal[collection] = bucket }\n bucket[id] = env\n }\n\n // ── Slots + versions (parent-collection-DEK keyed) ─────────────────\n for (const [collectionName, ids] of closure) {\n const destDek = destDeks.get(collectionName)\n if (!destDek) continue\n const srcDek = await getDEK(collectionName)\n const projList = fieldProjection?.[collectionName]\n const proj = projList ? new Set(projList) : undefined\n\n // Slots: one envelope per record, a `{ slotName: SlotRecord }` map.\n const slotsCollection = `${BLOB_SLOTS_PREFIX}${collectionName}`\n for (const id of ids) {\n // #767: carry any in-flight `_blob_intent` marker for this record,\n // re-keyed under the SAME destination DEK as its owning collection\n // (mirrors `dumpVault`'s backup allowlist, which carries `_blob_intent`\n // for the identical crash-recovery reason — a partition extracted\n // mid-shred/mid-rehome must carry the marker so resume-on-touch heals\n // it post-restore). Checked independently of the slot-map fetch below:\n // a marker can be present even when the slot map has already been\n // touched or removed by the in-flight operation.\n const intentId = `${collectionName}::${id}`\n const intentEnv = await adapter.get(vaultName, BLOB_INTENT_COLLECTION, intentId)\n if (intentEnv) {\n const intentPlain = await openEnvelopeJson({ collection: BLOB_INTENT_COLLECTION, id: intentId }, intentEnv, srcDek)\n const intentBody = await writeEnvelopeBody({ collection: BLOB_INTENT_COLLECTION, id: intentId, version: intentEnv._v }, intentPlain, destDek)\n place(BLOB_INTENT_COLLECTION, intentId, { ...intentEnv, ...intentBody })\n }\n\n const env = await adapter.get(vaultName, slotsCollection, id)\n if (!env) continue\n // #748 defense-in-depth canary — see the matching one in `reKeyClosure`:\n // `ids` comes from the same tier-gated `closure`, so an elevated\n // record's slot map should never be reachable here. Unreachable by\n // construction; a cheap tripwire, not a user-facing guard.\n if ((env._tier ?? 0) > 0) {\n throw new PartitionExtractionError(\n `#748: reKeyBlobs fetched an elevated slot-map envelope (collection=\"${slotsCollection}\" `\n + `id=\"${id}\" _tier=${env._tier}) — this is unreachable by construction. Refusing to carry it into a partition.`,\n )\n }\n const slots = JSON.parse(await openEnvelopeJson({ collection: slotsCollection, id }, env, srcDek)) as Record<string, SlotRecord>\n // FR-7: drop projected-out blob fields' slots (slot names are blob field\n // names) — their eTags then never enter the travel set.\n const kept: Record<string, SlotRecord> = {}\n for (const [slotName, slot] of Object.entries(slots)) {\n if (proj && !proj.has(slotName)) continue\n // #769: strip the internal `pendingRelease` resume breadcrumb before\n // it travels. It is a SOURCE-VAULT-LOCAL rehome marker (see\n // `SlotRecord.pendingRelease`'s doc comment) pointing at an old eTag\n // awaiting release — meaningless, and potentially misleading, once\n // detached from the source vault (the eTag it names may be absent\n // from the destination). Unlike `_blob_intent` above (carried, so\n // resume-on-touch heals it post-restore), this breadcrumb must NOT\n // travel into a cross-vault partition.\n const { pendingRelease, ...strippedSlot } = slot\n void pendingRelease\n kept[slotName] = strippedSlot\n addRef(slot.eTag)\n }\n if (Object.keys(kept).length === 0) continue\n const { iv, data } = await encrypt(JSON.stringify(kept), destDek, recordAadFor({ collection: slotsCollection, id }, env))\n place(slotsCollection, id, { ...env, _iv: iv, _data: data })\n }\n\n // Versions: key = `${recordId}::${slotName}::${label}`; each an independent\n // refCount hold on its eTag.\n const versionsCollection = `${BLOB_VERSIONS_PREFIX}${collectionName}`\n const versionKeys = await adapter.list(vaultName, versionsCollection)\n for (const key of versionKeys) {\n const [recordId, slotName] = key.split('::')\n if (recordId === undefined || !ids.has(recordId)) continue\n if (proj && slotName !== undefined && !proj.has(slotName)) continue\n const env = await adapter.get(vaultName, versionsCollection, key)\n if (!env) continue\n // #748 defense-in-depth canary — see `reKeyClosure`'s. Unreachable by\n // construction; a cheap tripwire, not a user-facing guard.\n if ((env._tier ?? 0) > 0) {\n throw new PartitionExtractionError(\n `#748: reKeyBlobs fetched an elevated version-record envelope (collection=\"${versionsCollection}\" `\n + `key=\"${key}\" _tier=${env._tier}) — this is unreachable by construction. Refusing to carry it into a partition.`,\n )\n }\n const record = JSON.parse(await openEnvelopeJson({ collection: versionsCollection, id: key }, env, srcDek)) as VersionRecord\n addRef(record.eTag)\n const { iv, data } = await encrypt(JSON.stringify(record), destDek, recordAadFor({ collection: versionsCollection, id: key }, env))\n place(versionsCollection, key, { ...env, _iv: iv, _data: data })\n }\n }\n\n // No chunk-based blob in the closure → carry nothing, mint nothing. Guarded\n // so `getDEK('_blob')` does not auto-mint + persist a phantom DEK on the\n // source keyring (mirrors the carryLedger non-destructive guard).\n if (carriedRefs.size === 0) return { internal }\n\n // ── Index + chunks (re-keyed under a FRESH transfer `_blob` DEK) ────\n const srcBlobDek = await getDEK(BLOB_COLLECTION)\n const transferBlobDek = await generateDEK()\n\n for (const [eTag, refCount] of carriedRefs) {\n const idxEnv = await adapter.get(vaultName, BLOB_INDEX_COLLECTION, eTag)\n if (!idxEnv) continue // dangling slot reference — nothing to carry\n const blob = JSON.parse(await openEnvelopeJson({ collection: BLOB_INDEX_COLLECTION, id: eTag }, idxEnv, srcBlobDek)) as BlobObject\n\n // Resolve the per-blob content CEK; passthrough vs. in-bundle promotion.\n let contentCek: EnclaveKey\n let chunksPassthrough: boolean\n if (blob._cek !== undefined) {\n contentCek = await unwrapCek(blob._cek, srcBlobDek)\n chunksPassthrough = true\n } else {\n // Legacy: promote to per-blob-CEK for the bundle (source untouched).\n contentCek = await generateDEK()\n chunksPassthrough = false\n }\n\n // Chunks: verbatim for an already-erasable blob; decrypt-then-re-encrypt\n // under the fresh content CEK for a legacy blob (same eTag-bound AAD).\n for (let i = 0; i < blob.chunkCount; i++) {\n const chunkId = `${eTag}_${i}`\n const chunkEnv = await adapter.get(vaultName, BLOB_CHUNKS_COLLECTION, chunkId)\n if (!chunkEnv) {\n throw new PartitionExtractionError(\n `reKeyBlobs: blob chunk ${i}/${blob.chunkCount} missing for eTag \"${eTag}\"; `\n + `cannot carry an incomplete blob into the partition.`,\n )\n }\n if (chunksPassthrough) {\n place(BLOB_CHUNKS_COLLECTION, chunkId, chunkEnv)\n } else {\n const aad = chunkAAD(eTag, i, blob.chunkCount)\n const plain = await decryptBytesWithAAD(chunkEnv._iv, chunkEnv._data, srcBlobDek, aad)\n const { iv, data } = await encryptBytesWithAAD(plain, contentCek, aad)\n place(BLOB_CHUNKS_COLLECTION, chunkId, { ...chunkEnv, _iv: iv, _data: data })\n }\n }\n\n // Index: per-blob-CEK mode under the transfer DEK, refCount corrected.\n // Drop any transient `_cekPending` (never set on a settled blob — possible\n // only if the source is mid-migration; we set a fresh settled `_cek`).\n const { _cekPending, ...rest } = blob\n void _cekPending\n const carried: BlobObject = { ...rest, refCount, _cek: await wrapCek(contentCek, transferBlobDek) }\n const { iv, data } = await encrypt(JSON.stringify(carried), transferBlobDek, recordAadFor({ collection: BLOB_INDEX_COLLECTION, id: eTag }, idxEnv))\n place(BLOB_INDEX_COLLECTION, eTag, { ...idxEnv, _iv: iv, _data: data })\n }\n\n return { internal, blobDek: transferBlobDek }\n}\n\n/** A minted transfer key (raw 32 bytes) + the seal carrying the DEK set. */\nexport interface SealResult {\n readonly seal: TransferSealPayload\n readonly transferKey: Uint8Array\n}\n\n/**\n * Mint a random 32-byte transfer key, export each DEK to raw bytes, and\n * AES-256-GCM-seal the `{ collection: base64(rawDEK) }` map under the\n * transfer key. The transfer key is returned to the caller out-of-band;\n * only the sealed bytes travel in the bundle. Layout: iv(12) ‖ ct ‖ tag.\n */\nexport async function sealDeks(deks: Map<string, EnclaveKey>): Promise<SealResult> {\n const dekMap: Record<string, string> = {}\n for (const [collection, dek] of deks) {\n const raw = await crypto.subtle.exportKey('raw', dek)\n dekMap[collection] = bufferToBase64(raw)\n }\n\n const transferKey = crypto.getRandomValues(new Uint8Array(32))\n const key = await crypto.subtle.importKey('raw', transferKey, 'AES-GCM', false, ['encrypt'])\n const iv = crypto.getRandomValues(new Uint8Array(12))\n const plaintext = new TextEncoder().encode(JSON.stringify(dekMap))\n const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext)\n\n const combined = new Uint8Array(iv.byteLength + ct.byteLength)\n combined.set(iv, 0)\n combined.set(new Uint8Array(ct), iv.byteLength)\n\n const sealId = bufferToBase64(crypto.getRandomValues(new Uint8Array(12)))\n return {\n seal: { v: 1, alg: 'aes-256-gcm-pre-shared', sealId, payload: bufferToBase64(combined) },\n transferKey,\n }\n}\n\nexport interface ExtractPartitionResult {\n readonly bundleBytes: Uint8Array\n /** Raw 32-byte transfer key — deliver out-of-band; required to adopt. */\n readonly transferKey: Uint8Array\n readonly sealId: string\n /**\n * #759: outbound FK edges whose referenced parent was excluded from the\n * partition (missing, or tier-elevated and therefore invisible). The\n * child record still carries its FK value; the parent did not travel —\n * callers should surface this to the operator rather than assume\n * referential completeness.\n */\n readonly danglingRefs: ReadonlyArray<DanglingRefNotice>\n}\n\n/**\n * Extract a re-keyed, transfer-sealed partition. Owner-only\n * (invariant 5): producing a standalone re-keyed vault is an\n * ownership operation. Non-destructive on the source.\n */\nexport type ExtractPartitionOptions = WalkClosureOptions & {\n readonly compression?: 'auto' | 'brotli' | 'gzip' | 'none'\n readonly carrySchemas?: boolean\n readonly carryLedger?: boolean\n /**\n * FR-7 structural field projection: per-collection allow-list of fields\n * to keep. Non-listed fields are dropped from each record BEFORE\n * re-encryption (so they never travel in the bundle); `id` is always\n * preserved. A projected collection's persisted schema is NOT carried.\n * Absent/empty → un-projected behavior (byte-identical to today).\n */\n readonly fieldProjection?: Record<string, readonly string[]>\n}\n\n/**\n * Public extract-partition entry — gated behind `cargoStrategy: withCargo()`\n * (S4). Routes through the source vault's cargo strategy so an un-opted-in\n * caller hits `NO_CARGO`'s throw; `withCargo()` dynamically imports and runs\n * {@link extractPartitionCore} (the crypto engine, kept out of the floor).\n */\nexport async function extractPartition(\n vault: Vault,\n opts: ExtractPartitionOptions,\n): Promise<ExtractPartitionResult> {\n return vault.cargoStrategy.extractPartition(vault, opts)\n}\n\n/**\n * The extract-partition crypto engine — reached only when `withCargo()` is\n * opted in (via the lazy `with-cargo/active.ts` chunk). Body unchanged from the\n * hardened implementation; only the public gate wraps it.\n */\nexport async function extractPartitionCore(\n vault: Vault,\n opts: ExtractPartitionOptions,\n): Promise<ExtractPartitionResult> {\n // FR-6: extract-and-sever is the inalienability-floor half — owner-only. A\n // custodian operates fully but must NEVER produce a standalone re-keyed\n // partition (that would let it sever a copy out from under the sealed owner).\n // Explicit assertion so the security boundary is auditable at this site.\n if (vault.role === 'custodian') {\n throw new PartitionExtractionError(\n 'extractPartition is owner-only; a custodian cannot extract-and-sever '\n + '(FR-6: producing a re-keyed standalone partition is an ownership operation; use the Deed owner).',\n )\n }\n if (vault.role !== 'owner') {\n throw new PartitionExtractionError(\n `extractPartition requires the 'owner' role on the source vault; caller is '${vault.role}'. `\n + `Producing a re-keyed standalone partition is an ownership operation.`,\n )\n }\n\n // Persisted-schema writes (collection({ persistJsonSchema: true })) are fire-\n // and-forget queued onto vault._pendingSchemaWrites — a caller that does\n // `collection() → put() → extractPartition({ carrySchemas: true })` in quick\n // succession can hit a window where _schemas/<col> is not yet on disk and\n // reKeySchemas silently drops the row. Drain BEFORE reKeySchemas reads.\n if (opts.carrySchemas) await vault._drainPendingSchemaWrites()\n\n const { closure, danglingRefs } = await walkClosure(vault, opts)\n const { collections, deks } = await reKeyClosure(vault, closure, opts.fieldProjection)\n\n // carryLedger: mint a fresh _ledger DEK, build the carried chain, and\n // SEAL the ledger DEK alongside the data DEKs so owner-creation wraps it into the\n // recipient keyring (lets them decrypt + verify the chain). Must run BEFORE\n // sealDeks.\n let ledgerHead: { hash: string; index: number; ts: string } | undefined\n let ledgerEntries: Record<string, EncryptedEnvelope> | undefined\n if (opts.carryLedger && vault._getLedgerOrNull() !== null) {\n // Skip when the source vault has no history strategy: reKeyLedger's first\n // `getDEK(LEDGER_COLLECTION)` would auto-mint and persist a phantom\n // _ledger DEK on the source keyring (contradicting \"non-destructive on\n // the source\"), and there's nothing to carry anyway. Mirrors the same\n // null-guard the source audit-append uses below.\n const ledgerDek = await generateDEK()\n const built = await reKeyLedger(vault, closure, collections, ledgerDek)\n if (built.head.index >= 0) {\n ledgerEntries = built.entries\n ledgerHead = built.head\n deks.set(LEDGER_COLLECTION, ledgerDek)\n }\n }\n\n // Carry the slice's blobs — re-keyed under a FRESH transfer `_blob` DEK\n // (HARDENED: never carries the source's shared blob DEK). Runs BEFORE\n // sealDeks so the fresh DEK is sealed alongside the data DEKs; non-destructive\n // on the source (mints + reads `_blob` only when the closure has blobs).\n const blobs = await reKeyBlobs(vault, closure, deks, opts.fieldProjection)\n if (blobs.blobDek) deks.set(BLOB_COLLECTION, blobs.blobDek)\n\n // Build _internal (schemas + ledger + blobs). reKeySchemas reads data-\n // collection DEKs only, so it is unaffected by the _ledger DEK added above.\n const internalSchemas = opts.carrySchemas ? await reKeySchemas(vault, closure, deks, opts.fieldProjection) : {}\n const internal: Record<string, Record<string, EncryptedEnvelope>> = {}\n if (Object.keys(internalSchemas).length > 0) internal[SCHEMAS_COLLECTION] = internalSchemas\n if (ledgerEntries) internal[LEDGER_COLLECTION] = ledgerEntries\n for (const [collection, records] of Object.entries(blobs.internal)) internal[collection] = records\n const hasInternal = Object.keys(internal).length > 0\n\n const { seal, transferKey } = await sealDeks(deks)\n\n // Source-side audit: record that a partition\n // was handed over. Non-destructive — an audit append, no record touched.\n // No-op when the source vault has no history strategy. append() fills\n // index/prevHash/ts and (since actor is '') the ledger's configured actor.\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle',\n collection: '',\n id: '',\n version: 0,\n actor: '',\n payloadHash: '',\n reason: `partition-handed-over:${seal.sealId}`,\n })\n\n // Build the dump JSON: unowned (empty keyrings), empty ledger (default),\n // re-keyed collections only.\n const { name: vaultName } = vault._introspectState()\n const backup = {\n _noydb_backup: NOYDB_BACKUP_VERSION,\n _compartment: vaultName,\n _exported_at: new Date().toISOString(),\n _exported_by: '', // unowned — no source user travels\n keyrings: {},\n collections,\n ...(hasInternal ? { _internal: internal } : {}),\n ...(ledgerHead ? { ledgerHead: { hash: ledgerHead.hash, index: ledgerHead.index, ts: ledgerHead.ts } } : {}),\n }\n const bodyJsonStr = JSON.stringify(buildExtractedPartitionWrapper(JSON.stringify(backup), seal))\n\n // An extracted partition is a NEW vault, not a re-export of the source —\n // mint a fresh handle rather than reusing the source's stable ULID\n // (which would collide if a recipient imports both source + partition).\n const handle = generateULID()\n const bundleBytes = await assemblePodContainer({\n handle,\n bodyJsonStr,\n compression: opts.compression,\n headerExtras: {\n bundleKind: 'extracted-partition',\n transferSeal: { v: seal.v, alg: seal.alg, sealId: seal.sealId }, // indicator only\n },\n })\n\n return { bundleBytes, transferKey, sealId: seal.sealId, danglingRefs }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,eAAsB,YACpB,OACA,MACwB;AACxB,QAAM,UAAU,oBAAI,IAAyB;AAM7C,QAAM,kBAAkB,CAAC,YAAoB,WAA4C;AACvF,UAAM,KAAK,OAAO,IAAI;AACtB,QAAI,OAAO,OAAO,UAAU;AAC1B,YAAM,IAAI;AAAA,QACR,sCAAsC,UAAU,0BACvC,OAAO,EAAE;AAAA,MACpB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,CAAC,YAAoB,OAAwB;AACvD,QAAI,MAAM,QAAQ,IAAI,UAAU;AAChC,QAAI,CAAC,KAAK;AACR,YAAM,oBAAI,IAAY;AACtB,cAAQ,IAAI,YAAY,GAAG;AAAA,IAC7B;AACA,QAAI,IAAI,IAAI,EAAE,EAAG,QAAO;AACxB,QAAI,IAAI,EAAE;AACV,WAAO;AAAA,EACT;AAGA,aAAW,CAAC,gBAAgB,SAAS,KAAK,OAAO,QAAQ,KAAK,KAAK,GAAG;AACpE,UAAM,OAAO,MAAM,WAAoC,cAAc;AACrE,UAAM,UAAU,MAAM,KAAK,KAAK;AAChC,eAAW,UAAU,SAAS;AAC5B,UAAI,MAAM,UAAU,MAAM,GAAG;AAC3B,YAAI,gBAAgB,gBAAgB,gBAAgB,MAAM,CAAC;AAAA,MAC7D;AAAA,IACF;AAAA,EACF;AAEA,QAAM,EAAE,aAAa,SAAS,MAAM,UAAU,IAAI,MAAM,iBAAiB;AACzE,QAAM,WAAW,KAAK,YAAY;AA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AO,KAAK,QAAQ,EAAE,SAAS;AAEnD,QAAM,EAAE,MAAM,YAAY,IAAI,MAAM,SAAS,IAAI;AAMjD,QAAM,MAAM,iBAAiB,GAAG,OAAO;AAAA,IACrC,IAAI;AAAA,IACJ,YAAY;AAAA,IACZ,IAAI;AAAA,IACJ,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa;AAAA,IACb,QAAQ,yBAAyB,KAAK,MAAM;AAAA,EAC9C,CAAC;AAID,QAAM,EAAE,MAAM,UAAU,IAAI,MAAM,iBAAiB;AACnD,QAAM,SAAS;AAAA,IACb,eAAe;AAAA,IACf,cAAc;AAAA,IACd,eAAc,oBAAI,KAAK,GAAE,YAAY;AAAA,IACrC,cAAc;AAAA;AAAA,IACd,UAAU,CAAC;AAAA,IACX;AAAA,IACA,GAAI,cAAc,EAAE,WAAW,SAAS,IAAI,CAAC;AAAA,IAC7C,GAAI,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,MAAM,OAAO,WAAW,OAAO,IAAI,WAAW,GAAG,EAAE,IAAI,CAAC;AAAA,EAC5G;AACA,QAAM,cAAc,KAAK,UAAU,+BAA+B,KAAK,UAAU,MAAM,GAAG,IAAI,CAAC;AAK/F,QAAM,SAAS,aAAa;AAC5B,QAAM,cAAc,MAAM,qBAAqB;AAAA,IAC7C;AAAA,IACA;AAAA,IACA,aAAa,KAAK;AAAA,IAClB,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,cAAc,EAAE,GAAG,KAAK,GAAG,KAAK,KAAK,KAAK,QAAQ,KAAK,OAAO;AAAA;AAAA,IAChE;AAAA,EACF,CAAC;AAED,SAAO,EAAE,aAAa,aAAa,QAAQ,KAAK,QAAQ,aAAa;AACvE;","names":["plaintext","iv","data"]}
@@ -2,7 +2,7 @@ import {
2
2
  OverlayBaseIsVirtualError,
3
3
  OverlayCollectionUnavailableError,
4
4
  OverlayNameCollisionError
5
- } from "./chunk-HNGSV2YC.js";
5
+ } from "./chunk-Z3BZXPRO.js";
6
6
 
7
7
  // src/with-formula/overlay-views/registry.ts
8
8
  var OverlayedViewRegistry = class {
@@ -68,4 +68,4 @@ var OverlayedViewRegistry = class {
68
68
  export {
69
69
  OverlayedViewRegistry
70
70
  };
71
- //# sourceMappingURL=chunk-FNSMZQS4.js.map
71
+ //# sourceMappingURL=chunk-5IHGJHWC.js.map
@@ -1,17 +1,17 @@
1
1
  import {
2
2
  freezeAndDeleteClosure,
3
3
  randomId
4
- } from "./chunk-FZ6NYJ7L.js";
4
+ } from "./chunk-QQRRKO7W.js";
5
5
  import {
6
6
  buildAccessibleBundle,
7
7
  resolveAccessibleCollections
8
- } from "./chunk-FFDNKRCY.js";
8
+ } from "./chunk-S6PJ6ZKE.js";
9
9
  import {
10
- NOYDB_FORMAT_VERSION
11
- } from "./chunk-YPYHVOXP.js";
10
+ buildRecordEnvelope
11
+ } from "./chunk-FX3UIDCS.js";
12
12
  import {
13
13
  NoydbError
14
- } from "./chunk-HNGSV2YC.js";
14
+ } from "./chunk-Z3BZXPRO.js";
15
15
 
16
16
  // src/with-audit/portability/request-withdrawal.ts
17
17
  var WITHDRAWAL_REQUESTS_COLLECTION = "_user_withdrawal_requests";
@@ -24,14 +24,11 @@ var WithdrawalRequestError = class extends NoydbError {
24
24
  function writeRequest(vault, req, expectedVersion) {
25
25
  const { name: vaultName, adapter } = vault._introspectState();
26
26
  const body = JSON.stringify(req);
27
- const env = {
28
- _noydb: NOYDB_FORMAT_VERSION,
29
- _v: expectedVersion + 1,
30
- _ts: req.decidedAt ?? req.requestedAt,
31
- _iv: "",
32
- _data: body,
33
- _by: req.decidedBy ?? req.requester
34
- };
27
+ const actor = req.decidedBy ?? req.requester;
28
+ const env = buildRecordEnvelope(
29
+ { collection: WITHDRAWAL_REQUESTS_COLLECTION, id: req.requestId, by: actor, version: expectedVersion + 1 },
30
+ { ts: req.decidedAt ?? req.requestedAt, iv: "", data: body }
31
+ );
35
32
  return adapter.put(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, req.requestId, env, expectedVersion);
36
33
  }
37
34
  async function readRequest(vault, requestId) {
@@ -161,4 +158,4 @@ export {
161
158
  approveWithdrawal,
162
159
  rejectWithdrawal
163
160
  };
164
- //# sourceMappingURL=chunk-4I72F5DF.js.map
161
+ //# sourceMappingURL=chunk-5LZZQMIC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/portability/request-withdrawal.ts"],"sourcesContent":["/**\n * Two-party withdrawal ceremony.\n *\n * The conservative counterpart to `unilateralWithdrawal`: a non-owner —\n * including a read-only `client`/`viewer` who cannot self-serve a deletion —\n * files a durable REQUEST; an owner/admin reviews it and either APPROVES\n * (extract-and-dispose under firm authority) or REJECTS it. Every step is\n * audited in the tamper-evident ledger.\n *\n * requester: vault.user.requestWithdrawal({ scope, disposition?, legalBasis? })\n * owner: vault.user.listWithdrawalRequests()\n * vault.user.approveWithdrawal(requestId, { reKey }) → { bundle, snapshot? }\n * vault.user.rejectWithdrawal(requestId, { reason })\n *\n * Requests live in the reserved `_user_withdrawal_requests` namespace. The\n * record body is plaintext metadata (collection names + disposition + legal\n * basis — none secret in this trust model; the owner sees the data anyway) and\n * carries NO secret: the re-key secret is supplied by the approver at\n * approval time and conveyed to the requester out-of-band, so no secret is\n * stored at rest.\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport { NoydbError } from '../../kernel/errors.js'\nimport { resolveAccessibleCollections, buildAccessibleBundle } from './export-accessible.js'\nimport { freezeAndDeleteClosure, randomId, type FrozenSnapshotRef, type WithdrawResult } from './withdraw-accessible.js'\n\nexport const WITHDRAWAL_REQUESTS_COLLECTION = '_user_withdrawal_requests'\n\n/** Raised when a request is missing, already decided, or expired. */\nexport class WithdrawalRequestError extends NoydbError {\n constructor(message: string) {\n super('WITHDRAWAL_REQUEST', message)\n this.name = 'WithdrawalRequestError'\n }\n}\n\nexport type WithdrawalRequestStatus = 'pending' | 'approved' | 'rejected'\n\nexport interface WithdrawalRequest {\n readonly requestId: string\n readonly requester: string\n readonly collections: readonly string[]\n readonly disposition: 'delete' | 'freeze'\n readonly legalBasis?: string\n readonly status: WithdrawalRequestStatus\n readonly requestedAt: string\n readonly expiresAt?: string\n readonly decidedAt?: string\n readonly decidedBy?: string\n readonly rejectReason?: string\n readonly snapshotSha256?: string\n}\n\nexport interface RequestWithdrawalOptions {\n readonly scope?: { readonly collections?: readonly string[] }\n readonly disposition?: 'delete' | 'freeze'\n readonly legalBasis?: string\n /** Time-to-live in ms; after this the request can no longer be approved. */\n readonly expiresInMs?: number\n}\n\nexport interface RequestWithdrawalResult {\n readonly requestId: string\n readonly status: WithdrawalRequestStatus\n readonly expiresAt?: string\n}\n\nfunction writeRequest(vault: Vault, req: WithdrawalRequest, expectedVersion: number): Promise<void> {\n const { name: vaultName, adapter } = vault._introspectState()\n const body = JSON.stringify(req)\n const actor = req.decidedBy ?? req.requester\n const env = buildRecordEnvelope(\n { collection: WITHDRAWAL_REQUESTS_COLLECTION, id: req.requestId, by: actor, version: expectedVersion + 1 },\n { ts: req.decidedAt ?? req.requestedAt, iv: '', data: body},\n )\n return adapter.put(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, req.requestId, env, expectedVersion)\n}\n\nasync function readRequest(vault: Vault, requestId: string): Promise<{ req: WithdrawalRequest; version: number }> {\n const { name: vaultName, adapter } = vault._introspectState()\n const env = await adapter.get(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, requestId)\n if (!env) throw new WithdrawalRequestError(`withdrawal request \"${requestId}\" not found`)\n return { req: JSON.parse(env._data) as WithdrawalRequest, version: env._v }\n}\n\n/**\n * Requester side. Files a durable request for the caller's accessible scope.\n * Gated by `user-request-withdrawal` (checked in the UserApi wrapper).\n */\nexport async function requestWithdrawal(\n vault: Vault,\n opts: RequestWithdrawalOptions = {},\n): Promise<RequestWithdrawalResult> {\n const { keyring } = vault._introspectState()\n // Resolve the requester's accessible collections (read access defines \"theirs\";\n // the owner — who can delete anything — executes the disposition on approval).\n const collections = resolveAccessibleCollections(keyring, opts.scope, false)\n if (!collections || collections.length === 0) {\n throw new WithdrawalRequestError(\n 'requestWithdrawal needs a concrete scope.collections (the caller has all-collection access — name the collections to withdraw)',\n )\n }\n const requestId = `wr-${randomId()}`\n const requestedAt = new Date().toISOString()\n const req: WithdrawalRequest = {\n requestId, requester: keyring.userId, collections, disposition: opts.disposition ?? 'delete',\n status: 'pending', requestedAt,\n ...(opts.legalBasis ? { legalBasis: opts.legalBasis } : {}),\n ...(opts.expiresInMs ? { expiresAt: new Date(Date.parse(requestedAt) + opts.expiresInMs).toISOString() } : {}),\n }\n await writeRequest(vault, req, 0) // create-only\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: keyring.userId, payloadHash: '',\n reason: `user-withdrawal-request:${requestId}:${keyring.userId}`,\n })\n return { requestId, status: 'pending', ...(req.expiresAt ? { expiresAt: req.expiresAt } : {}) }\n}\n\n/** Owner side. List filed requests (optionally by status). */\nexport async function listWithdrawalRequests(\n vault: Vault,\n opts: { status?: WithdrawalRequestStatus } = {},\n): Promise<WithdrawalRequest[]> {\n const { name: vaultName, adapter } = vault._introspectState()\n const ids = await adapter.list(vaultName, WITHDRAWAL_REQUESTS_COLLECTION)\n const out: WithdrawalRequest[] = []\n for (const id of ids) {\n const env = await adapter.get(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, id)\n if (!env) continue\n const req = JSON.parse(env._data) as WithdrawalRequest\n if (!opts.status || req.status === opts.status) out.push(req)\n }\n return out\n}\n\nfunction assertApprover(vault: Vault): string {\n const { keyring } = vault._introspectState()\n // FR-6: custodian is INTENTIONALLY excluded (SAFER default — review flag).\n // Approving a two-party withdrawal is a destructive extract-and-dispose\n // exercised under FIRM authority — a governance act adjacent to grant/revoke,\n // which a non-owning custodian cannot do. It stays owner/admin-only.\n if (keyring.role !== 'owner' && keyring.role !== 'admin') {\n throw new WithdrawalRequestError('approveWithdrawal / rejectWithdrawal require an owner or admin')\n }\n return keyring.userId\n}\n\nfunction assertPending(req: WithdrawalRequest): void {\n if (req.status !== 'pending') {\n throw new WithdrawalRequestError(`withdrawal request \"${req.requestId}\" is already ${req.status}`)\n }\n if (req.expiresAt && Date.now() > Date.parse(req.expiresAt)) {\n throw new WithdrawalRequestError(`withdrawal request \"${req.requestId}\" expired at ${req.expiresAt}`)\n }\n}\n\nexport interface ApproveWithdrawalOptions {\n /** Re-key the handed-back bundle to a secret the requester will use. */\n readonly reKey?: { readonly secret: string }\n}\n\n/**\n * Owner side. Extract the requester's recorded scope under firm authority,\n * dispose of the source per the request's disposition, mark the request\n * approved, and return the re-keyed bundle to hand back. Gated by\n * `approve-user-withdrawal` (checked in the UserApi wrapper) + owner/admin role.\n */\nexport async function approveWithdrawal(\n vault: Vault,\n requestId: string,\n opts: ApproveWithdrawalOptions = {},\n): Promise<WithdrawResult> {\n const approver = assertApprover(vault)\n const { req, version } = await readRequest(vault, requestId)\n assertPending(req)\n\n // 1. Produce the requester's re-keyed portable copy FIRST (owner authority\n // holds every DEK, so the recorded collections are all readable).\n const bundle = await buildAccessibleBundle(vault, [...req.collections], opts.reKey)\n\n // 2. + 3. dispose of the source (freeze snapshot, optional → delete-closure).\n const snapshot: FrozenSnapshotRef | undefined = await freezeAndDeleteClosure(vault, req.collections, {\n disposition: req.disposition, actorUserId: approver, withdrawalId: `wd-${requestId}`,\n })\n\n // 4. mark approved + audit (OCC against the version we read).\n const decidedAt = new Date().toISOString()\n await writeRequest(vault, {\n ...req, status: 'approved', decidedAt, decidedBy: approver,\n ...(snapshot ? { snapshotSha256: snapshot.sha256 } : {}),\n }, version)\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: approver, payloadHash: '',\n reason: `user-withdrawal-approved:${requestId}:${req.requester}:${req.disposition}`,\n })\n\n return snapshot ? { bundle, snapshot } : { bundle }\n}\n\nexport interface RejectWithdrawalOptions {\n readonly reason?: string\n}\n\n/** Owner side. Decline a pending request (no data is touched). */\nexport async function rejectWithdrawal(\n vault: Vault,\n requestId: string,\n opts: RejectWithdrawalOptions = {},\n): Promise<WithdrawalRequest> {\n const approver = assertApprover(vault)\n const { req, version } = await readRequest(vault, requestId)\n assertPending(req)\n const decidedAt = new Date().toISOString()\n const updated: WithdrawalRequest = {\n ...req, status: 'rejected', decidedAt, decidedBy: approver,\n ...(opts.reason ? { rejectReason: opts.reason } : {}),\n }\n await writeRequest(vault, updated, version)\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: approver, payloadHash: '',\n reason: `user-withdrawal-rejected:${requestId}:${req.requester}`,\n })\n return updated\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BO,IAAM,iCAAiC;AAGvC,IAAM,yBAAN,cAAqC,WAAW;AAAA,EACrD,YAAY,SAAiB;AAC3B,UAAM,sBAAsB,OAAO;AACnC,SAAK,OAAO;AAAA,EACd;AACF;AAiCA,SAAS,aAAa,OAAc,KAAwB,iBAAwC;AAClG,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAC5D,QAAM,OAAO,KAAK,UAAU,GAAG;AAC/B,QAAM,QAAQ,IAAI,aAAa,IAAI;AACnC,QAAM,MAAM;AAAA,IACV,EAAE,YAAY,gCAAgC,IAAI,IAAI,WAAW,IAAI,OAAO,SAAS,kBAAkB,EAAE;AAAA,IACzG,EAAE,IAAI,IAAI,aAAa,IAAI,aAAa,IAAI,IAAI,MAAM,KAAI;AAAA,EAC5D;AACA,SAAO,QAAQ,IAAI,WAAW,gCAAgC,IAAI,WAAW,KAAK,eAAe;AACnG;AAEA,eAAe,YAAY,OAAc,WAAyE;AAChH,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAC5D,QAAM,MAAM,MAAM,QAAQ,IAAI,WAAW,gCAAgC,SAAS;AAClF,MAAI,CAAC,IAAK,OAAM,IAAI,uBAAuB,uBAAuB,SAAS,aAAa;AAC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ts
6
6
  var PERIODS_COLLECTION = "_periods";
7
7
  var PERIOD_FREEZES_COLLECTION = "_period_freezes";
8
8
  var PERIOD_ARCHIVES_COLLECTION = "_period_archives";
9
9
  var PERIOD_TARGET_PURGES_COLLECTION = "_period_target_purges";
10
+ var PERIOD_REOPENS_COLLECTION = "_period_reopens";
10
11
  function periodExclusiveUpperBound(endDate) {
11
12
  const ms = Date.parse(endDate);
12
13
  if (Number.isNaN(ms)) throw new ValidationError(`freezePeriod: unparseable period endDate "${endDate}".`);
@@ -19,6 +20,7 @@ export {
19
20
  PERIOD_FREEZES_COLLECTION,
20
21
  PERIOD_ARCHIVES_COLLECTION,
21
22
  PERIOD_TARGET_PURGES_COLLECTION,
23
+ PERIOD_REOPENS_COLLECTION,
22
24
  periodExclusiveUpperBound
23
25
  };
24
- //# sourceMappingURL=chunk-JXIDGFKS.js.map
26
+ //# sourceMappingURL=chunk-5O5ZSW7N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/periods/window.ts"],"sourcesContent":["/**\n * Pure period-window primitives — the reserved collection names and the\n * exclusive-upper-bound computation shared by freeze (#604), archive (#613),\n * target-purge (#615) and the period-scoped sync pull (#807).\n *\n * Deliberately dependency-light (kernel errors only): the sync engine\n * (`with-sync/period-scope.ts`) imports THIS module, not\n * `periods.ts`, so a period-scoped pull never drags the ledger hash-chain\n * machinery (`sha256Hex`/`canonicalJson`) into a bundle that opted out of\n * the periods service.\n */\nimport { ValidationError } from '../../kernel/errors.js'\n\n/** The reserved collection name holding closed-period metadata. */\nexport const PERIODS_COLLECTION = '_periods'\n\n/** Sibling of {@link PERIODS_COLLECTION} holding freeze companions (#604). */\nexport const PERIOD_FREEZES_COLLECTION = '_period_freezes'\n\n/** Sibling of {@link PERIODS_COLLECTION} holding archive companions (#613). */\nexport const PERIOD_ARCHIVES_COLLECTION = '_period_archives'\n\n/** Sibling of {@link PERIODS_COLLECTION} holding target-purge companions (#615). */\nexport const PERIOD_TARGET_PURGES_COLLECTION = '_period_target_purges'\n\n/**\n * Sibling of {@link PERIODS_COLLECTION} holding reopen/reclose companions (#1022).\n *\n * Unlike the freeze / archive / target-purge companions — each a single,\n * idempotent, once-only record — this one holds an APPEND-ONLY EVENT LIST,\n * because reopening is a repeating cycle: a month can be closed, reopened,\n * reclosed, and reopened again. The audit value is the sequence, not the\n * latest state.\n */\nexport const PERIOD_REOPENS_COLLECTION = '_period_reopens'\n\n/**\n * Exclusive upper bound for a period's delete-marker purge window (#604).\n * Markers carry no business date (empty body), only write-time `_ts`, so freeze\n * purges markers with `_ts < bound`, `bound` being the instant just after the\n * period's inclusive `endDate`: a date-only `endDate` seals through end-of-day\n * → next midnight; a full-timestamp `endDate` seals through that instant → +1ms.\n */\nexport function periodExclusiveUpperBound(endDate: string): string {\n const ms = Date.parse(endDate)\n if (Number.isNaN(ms)) throw new ValidationError(`freezePeriod: unparseable period endDate \"${endDate}\".`)\n const dateOnly = /^\\d{4}-\\d{2}-\\d{2}$/.test(endDate)\n return new Date(ms + (dateOnly ? 86_400_000 : 1)).toISOString()\n}\n"],"mappings":";;;;;AAcO,IAAM,qBAAqB;AAG3B,IAAM,4BAA4B;AAGlC,IAAM,6BAA6B;AAGnC,IAAM,kCAAkC;AAWxC,IAAM,4BAA4B;AASlC,SAAS,0BAA0B,SAAyB;AACjE,QAAM,KAAK,KAAK,MAAM,OAAO;AAC7B,MAAI,OAAO,MAAM,EAAE,EAAG,OAAM,IAAI,gBAAgB,6CAA6C,OAAO,IAAI;AACxG,QAAM,WAAW,sBAAsB,KAAK,OAAO;AACnD,SAAO,IAAI,KAAK,MAAM,WAAW,QAAa,EAAE,EAAE,YAAY;AAChE;","names":[]}
@@ -1,7 +1,10 @@
1
+ import {
2
+ validateProjectionLegs
3
+ } from "./chunk-GANFIM2M.js";
1
4
  import {
2
5
  MaterializedViewConfigError,
3
6
  ValidationError
4
- } from "./chunk-HNGSV2YC.js";
7
+ } from "./chunk-Z3BZXPRO.js";
5
8
 
6
9
  // src/with-formula/materialized-views/with-materialized-view.ts
7
10
  function withMaterializedView(spec) {
@@ -134,6 +137,7 @@ function withMaterializedView(spec) {
134
137
  }
135
138
  seenAs.add(l.as);
136
139
  }
140
+ validateProjectionLegs(spec.name, spec.projection);
137
141
  if (Array.isArray(spec.groupBy) && spec.groupBy.length === 0) {
138
142
  throw new MaterializedViewConfigError(
139
143
  `withMaterializedView "${spec.name}": groupBy must not be an empty array \u2014 omit it or provide at least one field name`
@@ -177,4 +181,4 @@ function withMaterializedView(spec) {
177
181
  export {
178
182
  withMaterializedView
179
183
  };
180
- //# sourceMappingURL=chunk-CEJWMBXO.js.map
184
+ //# sourceMappingURL=chunk-5OT4G5N5.js.map