@noy-db/hub 0.8.0-pre.0 → 0.9.0-pre.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 (706) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +8 -8
  3. package/codemods/0.4.0-pre.json +1 -1
  4. package/codemods/0.8.0-pre.json +1 -1
  5. package/dist/api-MSJXVYQG.js +18 -0
  6. package/dist/as/index.js +34 -25
  7. package/dist/as/index.js.map +1 -1
  8. package/dist/at/index.js +9 -10
  9. package/dist/attestation/index.js +39 -28
  10. package/dist/attestation/index.js.map +1 -1
  11. package/dist/{backup-7TFRVFLH.js → backup-7RKNZMQO.js} +15 -16
  12. package/dist/backup-7RKNZMQO.js.map +1 -0
  13. package/dist/blobs/index.js +13 -14
  14. package/dist/blobs/index.js.map +1 -1
  15. package/dist/broker/index.js +20 -13
  16. package/dist/broker/index.js.map +1 -1
  17. package/dist/by/index.js +2 -2
  18. package/dist/capsule/contract.d.ts +159 -0
  19. package/dist/capsule/contract.js +95 -0
  20. package/dist/capsule/enclave-aes/bound.d.ts +52 -0
  21. package/dist/{kernel/enclave → capsule/enclave-aes}/broker/proof.d.ts +12 -3
  22. package/dist/capsule/enclave-aes/capabilities.d.ts +2 -0
  23. package/dist/capsule/enclave-aes/classify/compare.d.ts +20 -0
  24. package/dist/{kernel/enclave → capsule/enclave-aes}/classify/find.d.ts +1 -1
  25. package/dist/{kernel/enclave → capsule/enclave-aes}/classify/reveal.d.ts +1 -1
  26. package/dist/{kernel/enclave → capsule/enclave-aes}/classify/verify.d.ts +2 -2
  27. package/dist/{kernel/enclave → capsule/enclave-aes}/classify/write.d.ts +1 -1
  28. package/dist/{kernel/enclave → capsule/enclave-aes}/crypto.d.ts +33 -129
  29. package/dist/capsule/enclave-aes/index.d.ts +113 -0
  30. package/dist/capsule/enclave-aes/index.js +361 -0
  31. package/dist/capsule/enclave-aes/index.js.map +1 -0
  32. package/dist/capsule/enclave-aes/primitives.d.ts +29 -0
  33. package/dist/capsule/index.d.ts +27 -0
  34. package/dist/capsule/plumbing/ct-equal.d.ts +11 -0
  35. package/dist/{kernel/enclave/record-keys → capsule/plumbing}/deterministic.d.ts +8 -21
  36. package/dist/capsule/plumbing/digest.d.ts +122 -0
  37. package/dist/{kernel/enclave/record-keys → capsule/plumbing}/envelope-body.d.ts +44 -48
  38. package/dist/capsule/plumbing/index.d.ts +100 -0
  39. package/dist/capsule/plumbing/lifecycle.d.ts +50 -0
  40. package/dist/{kernel/enclave/record-keys → capsule/plumbing}/record-codec.d.ts +62 -20
  41. package/dist/{kernel/enclave → capsule/plumbing}/record-envelope.d.ts +1 -1
  42. package/dist/capsule/plumbing/rekey-blob.d.ts +33 -0
  43. package/dist/capsule/plumbing/rekey.d.ts +44 -0
  44. package/dist/capsule/plumbing/sealed-slot.d.ts +22 -0
  45. package/dist/capsule/plumbing/sealed-slots.d.ts +37 -0
  46. package/dist/capsule/plumbing/sealing.d.ts +29 -0
  47. package/dist/capsule/plumbing/sign.d.ts +9 -0
  48. package/dist/{kernel/enclave/record-keys → capsule/plumbing}/tombstone.d.ts +2 -2
  49. package/dist/capsule-57BDK7LG.js +209 -0
  50. package/dist/cargo/index.js +36 -36
  51. package/dist/{chunk-BUDAGWL5.js → chunk-226V6XXJ.js} +41 -6
  52. package/dist/chunk-226V6XXJ.js.map +1 -0
  53. package/dist/{chunk-QWGU66MP.js → chunk-2A56DSRI.js} +5 -7
  54. package/dist/chunk-2A56DSRI.js.map +1 -0
  55. package/dist/chunk-2DX4JCRI.js +1 -0
  56. package/dist/{chunk-ODVPTDPK.js → chunk-2ELOCEXE.js} +1 -1
  57. package/dist/chunk-2ELOCEXE.js.map +1 -0
  58. package/dist/{chunk-CKNGS5MH.js → chunk-2WJKJZSO.js} +3 -5
  59. package/dist/chunk-2WJKJZSO.js.map +1 -0
  60. package/dist/{chunk-ZSX4S5XB.js → chunk-2ZFD2UJC.js} +9 -9
  61. package/dist/{chunk-YSK2CU2Q.js → chunk-3V6LZHUO.js} +3 -3
  62. package/dist/chunk-3V6LZHUO.js.map +1 -0
  63. package/dist/{chunk-HT2AHGQI.js → chunk-3Y5JLSXS.js} +2 -2
  64. package/dist/{chunk-M7NI3IWE.js → chunk-45VHWE4C.js} +67 -60
  65. package/dist/chunk-45VHWE4C.js.map +1 -0
  66. package/dist/{chunk-LGNDFRYC.js → chunk-4CFHL5RY.js} +1 -1
  67. package/dist/chunk-4CFHL5RY.js.map +1 -0
  68. package/dist/{enclave-27SMF6GF.js → chunk-4J3MNVVX.js} +83 -56
  69. package/dist/chunk-4J3MNVVX.js.map +1 -0
  70. package/dist/{chunk-SI3V7D4G.js → chunk-4UIP3QNW.js} +2 -2
  71. package/dist/{chunk-WNJ4AVGE.js → chunk-55P6OBB7.js} +2 -2
  72. package/dist/{chunk-6LNL42F5.js → chunk-5HNW4ZTA.js} +12 -15
  73. package/dist/chunk-5HNW4ZTA.js.map +1 -0
  74. package/dist/{chunk-SYVZW77S.js → chunk-5LMCVBMY.js} +6 -8
  75. package/dist/chunk-5LMCVBMY.js.map +1 -0
  76. package/dist/{chunk-MKXXMNJH.js → chunk-5UUJE4FP.js} +3 -3
  77. package/dist/chunk-5XONHAFD.js +12 -0
  78. package/dist/chunk-5XONHAFD.js.map +1 -0
  79. package/dist/{chunk-X4773RBR.js → chunk-6QLCS7ET.js} +2 -2
  80. package/dist/chunk-6QLCS7ET.js.map +1 -0
  81. package/dist/{chunk-FW22ZCXT.js → chunk-6WS35E6X.js} +2 -2
  82. package/dist/{chunk-FCKWQE2H.js → chunk-6Y5E4SJU.js} +7 -8
  83. package/dist/chunk-6Y5E4SJU.js.map +1 -0
  84. package/dist/{chunk-4AF3TUMP.js → chunk-72XBVN4J.js} +8 -2
  85. package/dist/{chunk-4AF3TUMP.js.map → chunk-72XBVN4J.js.map} +1 -1
  86. package/dist/{chunk-QBBUZ3I3.js → chunk-7BMOS4JQ.js} +11 -11
  87. package/dist/chunk-7BMOS4JQ.js.map +1 -0
  88. package/dist/{chunk-5FDLC6G7.js → chunk-7CT6SX4M.js} +3 -3
  89. package/dist/chunk-7CT6SX4M.js.map +1 -0
  90. package/dist/{chunk-LQ4ZHOKP.js → chunk-ABU6A4Z5.js} +36 -27
  91. package/dist/chunk-ABU6A4Z5.js.map +1 -0
  92. package/dist/{chunk-WX5ADGTZ.js → chunk-AJFPAHMW.js} +3 -3
  93. package/dist/chunk-AJFPAHMW.js.map +1 -0
  94. package/dist/{chunk-ZE4CHIED.js → chunk-APFFJN5T.js} +39 -37
  95. package/dist/chunk-APFFJN5T.js.map +1 -0
  96. package/dist/{chunk-6OWXYZK2.js → chunk-B65CC6Z6.js} +2 -2
  97. package/dist/{chunk-F2TDU7MQ.js → chunk-BJH77UY2.js} +2 -2
  98. package/dist/{chunk-L7DOS3TE.js → chunk-BMHQHH7Q.js} +3 -3
  99. package/dist/chunk-BMHQHH7Q.js.map +1 -0
  100. package/dist/{chunk-BJ2IXQ5Q.js → chunk-BNFNQNEP.js} +2 -2
  101. package/dist/chunk-BU2ABHFW.js +74 -0
  102. package/dist/chunk-BU2ABHFW.js.map +1 -0
  103. package/dist/{chunk-HLEK5VAN.js → chunk-BUE7R3B5.js} +2 -2
  104. package/dist/{chunk-ISZQJBML.js → chunk-BVF3SXD7.js} +6 -6
  105. package/dist/chunk-BVF3SXD7.js.map +1 -0
  106. package/dist/{chunk-M522UYZ2.js → chunk-BYHCKX73.js} +6 -10
  107. package/dist/chunk-BYHCKX73.js.map +1 -0
  108. package/dist/{chunk-EOVMT6TB.js → chunk-C53ER7AG.js} +2 -2
  109. package/dist/{chunk-K6W7BVZ6.js → chunk-CAD7N6HQ.js} +3 -3
  110. package/dist/chunk-CB4467G3.js +565 -0
  111. package/dist/chunk-CB4467G3.js.map +1 -0
  112. package/dist/{chunk-NWHBJQAL.js → chunk-D4V5JJAK.js} +4 -4
  113. package/dist/chunk-D4V5JJAK.js.map +1 -0
  114. package/dist/{chunk-QWFHIOD2.js → chunk-D5A3GCZ4.js} +11 -12
  115. package/dist/chunk-D5A3GCZ4.js.map +1 -0
  116. package/dist/{chunk-5O7D6ZTW.js → chunk-DHU2AQ6T.js} +2 -2
  117. package/dist/{chunk-DC5QVPV7.js → chunk-DL6BZKP3.js} +3 -3
  118. package/dist/chunk-DL6BZKP3.js.map +1 -0
  119. package/dist/{chunk-FQ54DWUQ.js → chunk-EA4VDI5D.js} +4 -4
  120. package/dist/chunk-EA4VDI5D.js.map +1 -0
  121. package/dist/{chunk-IT22PWKV.js → chunk-ECGXA4LT.js} +2 -2
  122. package/dist/{chunk-BP6DARYA.js → chunk-EMAWOGVH.js} +4 -4
  123. package/dist/chunk-EMAWOGVH.js.map +1 -0
  124. package/dist/{chunk-3F7GLNAE.js → chunk-EUD3HQM4.js} +7 -11
  125. package/dist/chunk-EUD3HQM4.js.map +1 -0
  126. package/dist/{chunk-T2LBQ5DV.js → chunk-FSQNGPHH.js} +335 -250
  127. package/dist/chunk-FSQNGPHH.js.map +1 -0
  128. package/dist/{chunk-7VCXZDA4.js → chunk-FZXRLNJO.js} +7 -11
  129. package/dist/chunk-FZXRLNJO.js.map +1 -0
  130. package/dist/{chunk-6LMQ5R26.js → chunk-G46JSSVX.js} +7 -7
  131. package/dist/{chunk-6LMQ5R26.js.map → chunk-G46JSSVX.js.map} +1 -1
  132. package/dist/{chunk-GF5BZ7D4.js → chunk-G5EDYVSE.js} +11 -13
  133. package/dist/chunk-G5EDYVSE.js.map +1 -0
  134. package/dist/chunk-G66YXUTY.js +60 -0
  135. package/dist/chunk-G66YXUTY.js.map +1 -0
  136. package/dist/{chunk-FFWI7UH7.js → chunk-GAGT3YZN.js} +1 -1
  137. package/dist/chunk-GAGT3YZN.js.map +1 -0
  138. package/dist/{chunk-4MXI3ODD.js → chunk-GCUMOKTN.js} +3 -3
  139. package/dist/{chunk-FH2L2E34.js → chunk-GETUTTZU.js} +4 -4
  140. package/dist/{chunk-FH2L2E34.js.map → chunk-GETUTTZU.js.map} +1 -1
  141. package/dist/chunk-GMKGGY7V.js +234 -0
  142. package/dist/chunk-GMKGGY7V.js.map +1 -0
  143. package/dist/{chunk-B6SJIBQK.js → chunk-GOJQ5DZA.js} +4 -4
  144. package/dist/{chunk-EIPVYUEP.js → chunk-GQ4MF3CM.js} +3 -3
  145. package/dist/chunk-GQ4MF3CM.js.map +1 -0
  146. package/dist/{chunk-PDCG6PR5.js → chunk-GRS2HIV6.js} +2 -2
  147. package/dist/chunk-GRS2HIV6.js.map +1 -0
  148. package/dist/{chunk-PEOZ34EM.js → chunk-GSAK56VF.js} +1 -1
  149. package/dist/chunk-GSAK56VF.js.map +1 -0
  150. package/dist/{chunk-3H5KLDZN.js → chunk-H3YM66EI.js} +4 -8
  151. package/dist/chunk-H3YM66EI.js.map +1 -0
  152. package/dist/{chunk-NRT6QZQB.js → chunk-IVMFIKNA.js} +6 -6
  153. package/dist/chunk-IVMFIKNA.js.map +1 -0
  154. package/dist/{chunk-PSIV7CJV.js → chunk-J4KAPKBJ.js} +2 -2
  155. package/dist/chunk-J4KAPKBJ.js.map +1 -0
  156. package/dist/{chunk-N5DNADLQ.js → chunk-JA25QG5M.js} +224 -34
  157. package/dist/chunk-JA25QG5M.js.map +1 -0
  158. package/dist/{chunk-T7IR4N2S.js → chunk-JBMMWYOH.js} +3 -1
  159. package/dist/{chunk-T7IR4N2S.js.map → chunk-JBMMWYOH.js.map} +1 -1
  160. package/dist/{chunk-YNIUIERI.js → chunk-JPSL5GIZ.js} +18 -59
  161. package/dist/chunk-JPSL5GIZ.js.map +1 -0
  162. package/dist/{chunk-TKUOEU2F.js → chunk-JSWKVZCR.js} +2 -2
  163. package/dist/chunk-JZ4EDEIP.js +22 -0
  164. package/dist/chunk-JZ4EDEIP.js.map +1 -0
  165. package/dist/{chunk-QOOUUR4A.js → chunk-K673OO6B.js} +10 -4
  166. package/dist/chunk-K673OO6B.js.map +1 -0
  167. package/dist/{chunk-NNARWO72.js → chunk-K7RW7FI4.js} +13 -12
  168. package/dist/chunk-K7RW7FI4.js.map +1 -0
  169. package/dist/{chunk-ZXABPVM6.js → chunk-L2F3CFCH.js} +9 -13
  170. package/dist/chunk-L2F3CFCH.js.map +1 -0
  171. package/dist/{chunk-X25NWUZB.js → chunk-L5A3KR7R.js} +3 -3
  172. package/dist/{chunk-T52GX4SA.js → chunk-LGGIFKJP.js} +4 -4
  173. package/dist/{chunk-ID6Z6E66.js → chunk-MQ7YWBQ5.js} +2 -2
  174. package/dist/{chunk-FXQBGFOX.js → chunk-MRJDLXI3.js} +14 -8
  175. package/dist/{chunk-FXQBGFOX.js.map → chunk-MRJDLXI3.js.map} +1 -1
  176. package/dist/chunk-NH2UOV3B.js +18 -0
  177. package/dist/chunk-NH2UOV3B.js.map +1 -0
  178. package/dist/{chunk-FN5EBVTQ.js → chunk-NIXRB5BP.js} +2 -2
  179. package/dist/{chunk-RHVMZSUU.js → chunk-NV4OESHC.js} +1 -1
  180. package/dist/chunk-NV4OESHC.js.map +1 -0
  181. package/dist/{chunk-HBRLNOHL.js → chunk-NYJBYVBG.js} +4 -4
  182. package/dist/{chunk-DF73H4UN.js → chunk-NZULV7LK.js} +5 -5
  183. package/dist/chunk-NZULV7LK.js.map +1 -0
  184. package/dist/{chunk-HK67PX4J.js → chunk-OFD2HD6F.js} +1 -1
  185. package/dist/chunk-OFD2HD6F.js.map +1 -0
  186. package/dist/{chunk-WY2XXTET.js → chunk-OJU67C23.js} +4 -4
  187. package/dist/{chunk-WY2XXTET.js.map → chunk-OJU67C23.js.map} +1 -1
  188. package/dist/{chunk-ZUVBC32X.js → chunk-OK57EATL.js} +2 -2
  189. package/dist/{chunk-KJFW62P4.js → chunk-OM3SEDI4.js} +652 -662
  190. package/dist/chunk-OM3SEDI4.js.map +1 -0
  191. package/dist/{chunk-TOPYQ6GA.js → chunk-PCYPXLEX.js} +6 -6
  192. package/dist/{chunk-GYGLAVCX.js → chunk-PFCTSXHU.js} +6 -2
  193. package/dist/chunk-PFCTSXHU.js.map +1 -0
  194. package/dist/{chunk-VNNRUGMM.js → chunk-PGC35KXE.js} +2 -2
  195. package/dist/{chunk-4I522ERM.js → chunk-PT2YCQVK.js} +4 -4
  196. package/dist/{chunk-Z5HTYMMQ.js → chunk-PTJY5R3O.js} +2 -2
  197. package/dist/chunk-PUBI455O.js +157 -0
  198. package/dist/chunk-PUBI455O.js.map +1 -0
  199. package/dist/{chunk-MTL7MXGR.js → chunk-QDHHHI5Q.js} +16 -17
  200. package/dist/chunk-QDHHHI5Q.js.map +1 -0
  201. package/dist/{chunk-F24ZZTHQ.js → chunk-QGFEBNHO.js} +4 -4
  202. package/dist/{chunk-A6IJU4TK.js → chunk-QGSNJD3B.js} +2 -2
  203. package/dist/chunk-QJNAHPVT.js +91 -0
  204. package/dist/chunk-QJNAHPVT.js.map +1 -0
  205. package/dist/{chunk-BK2HHQGN.js → chunk-QSHATAXJ.js} +2 -2
  206. package/dist/{chunk-ANWPSTZU.js → chunk-QXJXG7DN.js} +57 -30
  207. package/dist/chunk-QXJXG7DN.js.map +1 -0
  208. package/dist/{chunk-HBPPGWUM.js → chunk-RDOEOPOI.js} +14 -9
  209. package/dist/chunk-RDOEOPOI.js.map +1 -0
  210. package/dist/{chunk-JCN44NCY.js → chunk-RIZTZJX6.js} +2 -2
  211. package/dist/{chunk-MVZ2TPVP.js → chunk-RNACRT5H.js} +2 -2
  212. package/dist/chunk-RWFQVNXR.js +24 -0
  213. package/dist/chunk-RWFQVNXR.js.map +1 -0
  214. package/dist/{chunk-TROR3ALR.js → chunk-SFCD6OU7.js} +2 -2
  215. package/dist/{chunk-S57HTZ6X.js → chunk-SNM7LSYG.js} +5 -8
  216. package/dist/chunk-SNM7LSYG.js.map +1 -0
  217. package/dist/chunk-SPPOUJLN.js +40 -0
  218. package/dist/chunk-SPPOUJLN.js.map +1 -0
  219. package/dist/{chunk-3ELRMVJK.js → chunk-SWXLZ4HX.js} +31 -35
  220. package/dist/chunk-SWXLZ4HX.js.map +1 -0
  221. package/dist/{chunk-6B3VNR4P.js → chunk-TFWFPZRU.js} +26 -35
  222. package/dist/chunk-TFWFPZRU.js.map +1 -0
  223. package/dist/{chunk-F7XGHL5O.js → chunk-TMIJAR2X.js} +3 -3
  224. package/dist/{chunk-F7XGHL5O.js.map → chunk-TMIJAR2X.js.map} +1 -1
  225. package/dist/{chunk-I3JDRCMW.js → chunk-TZYTMZZY.js} +10 -10
  226. package/dist/{chunk-AOWGXU6D.js → chunk-UAKY6E4N.js} +2 -2
  227. package/dist/chunk-UHFGK6YA.js +40 -0
  228. package/dist/chunk-UHFGK6YA.js.map +1 -0
  229. package/dist/{chunk-3JWHAR6E.js → chunk-UNSQZSZP.js} +2 -2
  230. package/dist/{chunk-FQ5VRHIB.js → chunk-UOZOWN73.js} +5 -9
  231. package/dist/chunk-UOZOWN73.js.map +1 -0
  232. package/dist/{chunk-GHLTDZRS.js → chunk-V55JASXO.js} +25 -4
  233. package/dist/chunk-V55JASXO.js.map +1 -0
  234. package/dist/{chunk-244VXYPG.js → chunk-VSUQI5Q6.js} +45 -4
  235. package/dist/chunk-VSUQI5Q6.js.map +1 -0
  236. package/dist/{chunk-6K7DPM7D.js → chunk-WFWFXDNS.js} +2 -2
  237. package/dist/{chunk-CF5UU4S7.js → chunk-WHOKGHJ3.js} +7 -7
  238. package/dist/{chunk-LGRLME4M.js → chunk-X2RP4TO5.js} +16 -16
  239. package/dist/chunk-X2RP4TO5.js.map +1 -0
  240. package/dist/{chunk-VNPEWFPD.js → chunk-XA34THLF.js} +8 -6
  241. package/dist/chunk-XA34THLF.js.map +1 -0
  242. package/dist/{chunk-HVSCEIYL.js → chunk-XITHENBI.js} +12 -14
  243. package/dist/chunk-XITHENBI.js.map +1 -0
  244. package/dist/{chunk-ENAG3IY7.js → chunk-XKBTJGFP.js} +26 -28
  245. package/dist/chunk-XKBTJGFP.js.map +1 -0
  246. package/dist/{chunk-32YV3TJT.js → chunk-XXNWU5QZ.js} +2 -2
  247. package/dist/{chunk-B57AFBY2.js → chunk-XXQ5XIYY.js} +2 -2
  248. package/dist/{chunk-ORDURZBU.js → chunk-YFFMPZPY.js} +2 -2
  249. package/dist/{chunk-MDWKM2XC.js → chunk-YKGJ44Z7.js} +3 -3
  250. package/dist/{chunk-IUWCVHQ7.js → chunk-YQFBH5ZJ.js} +4 -4
  251. package/dist/{chunk-IUWCVHQ7.js.map → chunk-YQFBH5ZJ.js.map} +1 -1
  252. package/dist/{chunk-UPD5NWI5.js → chunk-Z3ZXVB2Y.js} +29 -16
  253. package/dist/chunk-Z3ZXVB2Y.js.map +1 -0
  254. package/dist/chunk-ZBUAX4EF.js +27 -0
  255. package/dist/chunk-ZBUAX4EF.js.map +1 -0
  256. package/dist/{chunk-MLPHLJIQ.js → chunk-ZHQJAV6D.js} +2 -2
  257. package/dist/{chunk-UD5EVGZ7.js → chunk-ZMVSKYTJ.js} +56 -96
  258. package/dist/chunk-ZMVSKYTJ.js.map +1 -0
  259. package/dist/{chunk-7JE7BDYJ.js → chunk-ZVSKSUGI.js} +5 -5
  260. package/dist/{chunk-J6UOHJY5.js → chunk-ZWF3EWZA.js} +4 -8
  261. package/dist/chunk-ZWF3EWZA.js.map +1 -0
  262. package/dist/classified/index.js +5 -5
  263. package/dist/{classified-marker-W3USLL5M.js → classified-marker-KHDOYIJB.js} +3 -3
  264. package/dist/classified-marker-KHDOYIJB.js.map +1 -0
  265. package/dist/collection-facade-LZIF7GWD.js +41 -0
  266. package/dist/{computed-TPFBX7U4.js → computed-XMFTHAXV.js} +3 -3
  267. package/dist/consent/index.js +10 -11
  268. package/dist/consent/index.js.map +1 -1
  269. package/dist/cover/index.js +9 -10
  270. package/dist/coverage/index.js +1 -1
  271. package/dist/custody/index.js +13 -13
  272. package/dist/{dead-filter-U2UYKSZL.js → dead-filter-CXV5NS67.js} +11 -3
  273. package/dist/dead-filter-CXV5NS67.js.map +1 -0
  274. package/dist/debug/index.js +11 -2
  275. package/dist/debug/index.js.map +1 -1
  276. package/dist/{delegation-S3AEPW2T.js → delegation-ONLM4JFI.js} +52 -31
  277. package/dist/delegation-ONLM4JFI.js.map +1 -0
  278. package/dist/derivations/index.js +25 -25
  279. package/dist/derive-3YSIS36W.js +20 -0
  280. package/dist/directory/index.js +10 -11
  281. package/dist/{dispatch-RH4LHKBH.js → dispatch-2MQFMEGY.js} +22 -23
  282. package/dist/dispatch-2MQFMEGY.js.map +1 -0
  283. package/dist/{dispatch-3CQDJV5Q.js → dispatch-OFDA4WQV.js} +5 -5
  284. package/dist/executor-E6YDJ7YA.js +8 -0
  285. package/dist/executor-NJX3YQQ4.js +35 -0
  286. package/dist/executor-WWM3DD4P.js +8 -0
  287. package/dist/export-accessible-RLHU5G4W.js +22 -0
  288. package/dist/extract-partition-QII2EDCS.js +35 -0
  289. package/dist/{fanout-sidecar-OT6RYLOL.js → fanout-sidecar-BO67PCPO.js} +13 -15
  290. package/dist/fanout-sidecar-BO67PCPO.js.map +1 -0
  291. package/dist/find-6M7GYDUZ.js +10 -0
  292. package/dist/forget/index.js +26 -10
  293. package/dist/forget/index.js.map +1 -1
  294. package/dist/guards/index.js +4 -4
  295. package/dist/history/index.js +13 -14
  296. package/dist/history/index.js.map +1 -1
  297. package/dist/i18n/index.js +14 -15
  298. package/dist/i18n/index.js.map +1 -1
  299. package/dist/index.d.ts +15 -13
  300. package/dist/index.js +198 -187
  301. package/dist/index.js.map +1 -1
  302. package/dist/indexing/index.js +6 -6
  303. package/dist/introspection/index.js +16 -13
  304. package/dist/issue-LPEEEMPP.js +19 -0
  305. package/dist/kernel/attestation-types.d.ts +62 -0
  306. package/dist/kernel/cache/index.d.ts +1 -1
  307. package/dist/kernel/collection-config.d.ts +1 -48
  308. package/dist/kernel/collection.d.ts +2 -1
  309. package/dist/kernel/cutover-transform.d.ts +1 -1
  310. package/dist/kernel/errors.d.ts +63 -6
  311. package/dist/kernel/export-scope.d.ts +40 -0
  312. package/dist/kernel/merge-authority.d.ts +1 -1
  313. package/dist/kernel/noydb.d.ts +3 -1
  314. package/dist/kernel/paths.d.ts +29 -5
  315. package/dist/kernel/prepared-write.d.ts +1 -1
  316. package/dist/kernel/put-many-atomic.d.ts +1 -1
  317. package/dist/kernel/query/live/live.d.ts +2 -1
  318. package/dist/kernel/query/sort-key.d.ts +0 -2
  319. package/dist/kernel/secret-mode.d.ts +1 -1
  320. package/dist/kernel/tx-write-gate.d.ts +2 -4
  321. package/dist/kernel/types.d.ts +135 -11
  322. package/dist/kernel/validation.d.ts +0 -10
  323. package/dist/kernel/vault.d.ts +6 -2
  324. package/dist/kernel/via/reconcile.d.ts +1 -42
  325. package/dist/kernel/write-queue.d.ts +17 -0
  326. package/dist/{ledger-KZPCMVZY.js → ledger-MSJGWKGW.js} +11 -12
  327. package/dist/liberate-LEKDYKTC.js +25 -0
  328. package/dist/link-set-QXXSPPHL.js +29 -0
  329. package/dist/{managed-secret-S3MQ6SH6.js → managed-secret-VSK7ANQI.js} +10 -11
  330. package/dist/materialized-views/index.js +27 -28
  331. package/dist/{migrate-cek-V7GKJZ7O.js → migrate-cek-GEBFYBDC.js} +2 -2
  332. package/dist/money/index.js +5 -5
  333. package/dist/noydb-F2AUF6KL.js +98 -0
  334. package/dist/on/index.js +25 -0
  335. package/dist/overlay-views/index.js +4 -4
  336. package/dist/periods/index.js +12 -13
  337. package/dist/pod/index.js +76 -74
  338. package/dist/{pod-handle-WGDFB4C2.js → pod-handle-YE7CT66T.js} +10 -11
  339. package/dist/pod-handle-YE7CT66T.js.map +1 -0
  340. package/dist/policy/index.js +10 -11
  341. package/dist/port/as/active.d.ts +4 -0
  342. package/dist/port/as/index.d.ts +1 -0
  343. package/dist/port/by/index.d.ts +14 -5
  344. package/dist/port/on/index.d.ts +27 -1
  345. package/dist/port/to/index.d.ts +1 -1
  346. package/dist/port/with/blob-strategy.d.ts +1 -1
  347. package/dist/port/with/broker-strategy.d.ts +14 -0
  348. package/dist/port/with/classified-strategy.d.ts +1 -1
  349. package/dist/port/with/collection-options.d.ts +1 -1
  350. package/dist/port/with/collection-registries.d.ts +1 -1
  351. package/dist/port/with/coverage-strategy.d.ts +17 -1
  352. package/dist/port/with/formats-strategy.d.ts +34 -1
  353. package/dist/port/with/lookup-strategy.d.ts +87 -6
  354. package/dist/port/with/service-bus.d.ts +2 -1
  355. package/dist/portability/index.js +8 -8
  356. package/dist/{post-register-SLSXIPBV.js → post-register-QC5TEAW3.js} +6 -6
  357. package/dist/post-register-QC5TEAW3.js.map +1 -0
  358. package/dist/query/all/index.js +16 -16
  359. package/dist/query/index.js +8 -8
  360. package/dist/query/live/index.js +7 -7
  361. package/dist/query/reduce/index.js +10 -10
  362. package/dist/query/relate/index.js +10 -10
  363. package/dist/reduce/index.js +8 -8
  364. package/dist/register-SN72QALV.js +30 -0
  365. package/dist/registry-253FF7C6.js +35 -0
  366. package/dist/registry-3AZWQTDT.js +23 -0
  367. package/dist/registry-7UEBTHWG.js +8 -0
  368. package/dist/registry-IVJ67NFQ.js +8 -0
  369. package/dist/request-withdrawal-UKVJZKX2.js +28 -0
  370. package/dist/{reveal-4BCKPEC2.js → reveal-YQTRNQFH.js} +10 -9
  371. package/dist/reveal-YQTRNQFH.js.map +1 -0
  372. package/dist/revoke-G2KXJQA5.js +24 -0
  373. package/dist/satellites/index.js +1 -1
  374. package/dist/schema-update/index.js +2 -2
  375. package/dist/sealed-record/index.js +16 -18
  376. package/dist/sealed-record/index.js.map +1 -1
  377. package/dist/search/index.js +4 -4
  378. package/dist/{seed-4JS2RJ4A.js → seed-JMQTRKRE.js} +125 -34
  379. package/dist/seed-JMQTRKRE.js.map +1 -0
  380. package/dist/sequence/index.js +9 -10
  381. package/dist/session/index.js +9 -10
  382. package/dist/session/index.js.map +1 -1
  383. package/dist/shadow/index.js +2 -2
  384. package/dist/signer-IUIYR3CX.js +23 -0
  385. package/dist/snapshots/index.js +11 -11
  386. package/dist/stale-SKV33PBU.js +28 -0
  387. package/dist/storage-NPBYP2SM.js +21 -0
  388. package/dist/store/index.js +1 -1
  389. package/dist/{store-coordination-provider-2O2VUHKW.js → store-coordination-provider-Z6HKPOGM.js} +11 -12
  390. package/dist/store-coordination-provider-Z6HKPOGM.js.map +1 -0
  391. package/dist/sync/index.js +18 -13
  392. package/dist/sync/index.js.map +1 -1
  393. package/dist/team/index.js +18 -17
  394. package/dist/tiers/index.js +11 -12
  395. package/dist/to/index.js +2 -2
  396. package/dist/transactions/index.js +3 -3
  397. package/dist/util/index.js +1 -1
  398. package/dist/vault-head/index.js +11 -14
  399. package/dist/vault-head/index.js.map +1 -1
  400. package/dist/{verify-RVT67IMH.js → verify-KWQIWLGH.js} +14 -12
  401. package/dist/verify-KWQIWLGH.js.map +1 -0
  402. package/dist/via/classified/binding.d.ts +2 -2
  403. package/dist/via/classified/config-drift.d.ts +2 -2
  404. package/dist/via/classified/errors.d.ts +1 -1
  405. package/dist/via/classified/presets.d.ts +29 -0
  406. package/dist/via/classified/resolve.d.ts +7 -0
  407. package/dist/via/geo/binding.d.ts +0 -4
  408. package/dist/via/lookup/handle.d.ts +4 -4
  409. package/dist/via/lookup/index.d.ts +32 -0
  410. package/dist/via/money/binding.d.ts +0 -9
  411. package/dist/walk-F4OLXI5H.js +20 -0
  412. package/dist/with-audit/attestation/index.d.ts +2 -1
  413. package/dist/with-audit/attestation/issue.d.ts +2 -2
  414. package/dist/with-audit/attestation/revoke.d.ts +2 -2
  415. package/dist/with-audit/attestation/scheme.d.ts +7 -0
  416. package/dist/with-audit/attestation/signer.d.ts +1 -1
  417. package/dist/with-audit/attestation/strategy.d.ts +4 -3
  418. package/dist/with-audit/attestation/types.d.ts +10 -0
  419. package/dist/with-audit/attestation/vault-facade.d.ts +9 -2
  420. package/dist/with-audit/attestation/verifier.d.ts +6 -0
  421. package/dist/with-audit/consent/consent.d.ts +1 -1
  422. package/dist/with-audit/consent/strategy.d.ts +1 -1
  423. package/dist/with-audit/forget/completeness.d.ts +66 -0
  424. package/dist/with-audit/forget/index.d.ts +2 -0
  425. package/dist/with-audit/forget/strategy.d.ts +65 -0
  426. package/dist/with-audit/forget/subject-index.d.ts +1 -1
  427. package/dist/with-audit/periods/periods.d.ts +0 -9
  428. package/dist/with-audit/periods/reserved-collections.d.ts +7 -0
  429. package/dist/with-audit/periods/vault-facade.d.ts +1 -1
  430. package/dist/with-audit/portability/request-withdrawal.d.ts +0 -1
  431. package/dist/with-audit/portability/withdraw-accessible.d.ts +0 -1
  432. package/dist/with-audit/sealed-record/index.d.ts +2 -2
  433. package/dist/with-audit/sealed-record/strategy.d.ts +1 -1
  434. package/dist/with-audit/tiers/index.d.ts +3 -3
  435. package/dist/with-audit/tiers/strategy.d.ts +19 -0
  436. package/dist/with-cargo/adopt-partition.d.ts +1 -1
  437. package/dist/with-cargo/extract-partition.d.ts +1 -47
  438. package/dist/with-cargo/floor.d.ts +1 -1
  439. package/dist/with-commit/history/history.d.ts +2 -2
  440. package/dist/with-commit/history/index.d.ts +1 -1
  441. package/dist/with-commit/history/ledger/store.d.ts +1 -1
  442. package/dist/with-commit/history/strategy.d.ts +1 -1
  443. package/dist/with-commit/history/time-machine.d.ts +1 -1
  444. package/dist/with-commit/numbering/index.d.ts +1 -3
  445. package/dist/with-commit/sequence/index.d.ts +1 -1
  446. package/dist/with-commit/tx/transaction.d.ts +2 -24
  447. package/dist/with-commit/vault-head/head.d.ts +1 -1
  448. package/dist/with-commit/vault-head/index.d.ts +1 -1
  449. package/dist/with-commit/vault-head/strategy.d.ts +8 -1
  450. package/dist/with-commit/vault-head/verify.d.ts +1 -1
  451. package/dist/with-fork/snapshots/noydb-facade.d.ts +7 -0
  452. package/dist/with-formula/derivations/dispatch.d.ts +1 -1
  453. package/dist/with-formula/derivations/fanout-sidecar.d.ts +1 -1
  454. package/dist/with-formula/derivations/trigger-match.d.ts +8 -5
  455. package/dist/with-formula/materialized-views/emit-memo.d.ts +0 -2
  456. package/dist/with-lookup/embeddings/index.d.ts +1 -2
  457. package/dist/with-lookup/indexing/collection-facade.d.ts +2 -16
  458. package/dist/with-lookup/indexing/eager-indexes.d.ts +2 -1
  459. package/dist/with-lookup/search/collection-facade.d.ts +1 -13
  460. package/dist/with-party/broker/index.d.ts +4 -4
  461. package/dist/with-party/broker/seed.d.ts +25 -10
  462. package/dist/with-party/directory/user-envelope/storage.d.ts +1 -1
  463. package/dist/with-party/policy/noydb-facade.d.ts +1 -31
  464. package/dist/with-party/team/delegation.d.ts +59 -3
  465. package/dist/with-party/team/echo-secret.d.ts +2 -4
  466. package/dist/with-party/team/index.d.ts +1 -1
  467. package/dist/with-party/team/keyring.d.ts +2 -22
  468. package/dist/with-party/team/magic-link-grant.d.ts +12 -2
  469. package/dist/with-party/team/noydb-facade.d.ts +5 -0
  470. package/dist/with-party/team/recovery.d.ts +1 -1
  471. package/dist/with-party/team/reserved-secret-collections.d.ts +10 -8
  472. package/dist/with-party/team/roster-tag.d.ts +43 -2
  473. package/dist/with-party/team/rotate-recover.d.ts +1 -1
  474. package/dist/with-party/team/tiers.d.ts +36 -5
  475. package/dist/with-party/team/wrapped-deks.d.ts +1 -1
  476. package/dist/with-pod/index.d.ts +1 -1
  477. package/dist/with-shape/blobs/blob-compaction.d.ts +1 -1
  478. package/dist/with-shape/blobs/blob-intent.d.ts +1 -1
  479. package/dist/with-shape/blobs/blob-set.d.ts +25 -2
  480. package/dist/with-shape/blobs/legacy-sweep.d.ts +17 -1
  481. package/dist/with-shape/introspection/describe.d.ts +2 -3
  482. package/dist/with-shape/introspection/index.d.ts +1 -0
  483. package/dist/with-shape/introspection/types.d.ts +2 -1
  484. package/dist/with-shape/introspection/walk.d.ts +1 -1
  485. package/dist/with-shape/links/lazy-handle.d.ts +1 -1
  486. package/dist/with-shape/links/link-set.d.ts +1 -1
  487. package/dist/with-shape/manifest/derive.d.ts +1 -1
  488. package/dist/with-shape/manifest/storage.d.ts +1 -1
  489. package/dist/with-shape/persisted-schemas/register.d.ts +1 -1
  490. package/dist/with-shape/persisted-schemas/storage.d.ts +1 -1
  491. package/dist/with-shape/satellites/dead-filter.d.ts +1 -1
  492. package/dist/with-shape/satellites/declare.d.ts +1 -1
  493. package/dist/with-shape/satellites/marker.d.ts +1 -1
  494. package/dist/with-shape/satellites/post-register.d.ts +1 -1
  495. package/dist/with-shape/schema-update/fence.d.ts +7 -0
  496. package/dist/with-sync/engine.d.ts +30 -1
  497. package/dist/with-sync/presence.d.ts +5 -10
  498. package/dist/with-sync/reserved-mirror.d.ts +89 -0
  499. package/dist/with-sync/strategy.d.ts +7 -0
  500. package/dist/with-sync/tab-write-relay.d.ts +0 -10
  501. package/dist/withdraw-accessible-ZKPLZ66E.js +25 -0
  502. package/dist/withdraw-accessible-ZKPLZ66E.js.map +1 -0
  503. package/package.json +14 -5
  504. package/dist/api-GVYEKSJE.js +0 -19
  505. package/dist/backup-7TFRVFLH.js.map +0 -1
  506. package/dist/chunk-244VXYPG.js.map +0 -1
  507. package/dist/chunk-3ELRMVJK.js.map +0 -1
  508. package/dist/chunk-3F7GLNAE.js.map +0 -1
  509. package/dist/chunk-3H5KLDZN.js.map +0 -1
  510. package/dist/chunk-5FDLC6G7.js.map +0 -1
  511. package/dist/chunk-6B3VNR4P.js.map +0 -1
  512. package/dist/chunk-6LNL42F5.js.map +0 -1
  513. package/dist/chunk-6QSQQLSE.js +0 -95
  514. package/dist/chunk-6QSQQLSE.js.map +0 -1
  515. package/dist/chunk-7VCXZDA4.js.map +0 -1
  516. package/dist/chunk-ANWPSTZU.js.map +0 -1
  517. package/dist/chunk-BP6DARYA.js.map +0 -1
  518. package/dist/chunk-BUDAGWL5.js.map +0 -1
  519. package/dist/chunk-CKNGS5MH.js.map +0 -1
  520. package/dist/chunk-DC5QVPV7.js.map +0 -1
  521. package/dist/chunk-DE4DH2RZ.js +0 -29
  522. package/dist/chunk-DE4DH2RZ.js.map +0 -1
  523. package/dist/chunk-DF73H4UN.js.map +0 -1
  524. package/dist/chunk-EIPVYUEP.js.map +0 -1
  525. package/dist/chunk-ENAG3IY7.js.map +0 -1
  526. package/dist/chunk-FCKWQE2H.js.map +0 -1
  527. package/dist/chunk-FFWI7UH7.js.map +0 -1
  528. package/dist/chunk-FQ54DWUQ.js.map +0 -1
  529. package/dist/chunk-FQ5VRHIB.js.map +0 -1
  530. package/dist/chunk-GF5BZ7D4.js.map +0 -1
  531. package/dist/chunk-GHLTDZRS.js.map +0 -1
  532. package/dist/chunk-GYGLAVCX.js.map +0 -1
  533. package/dist/chunk-HBPPGWUM.js.map +0 -1
  534. package/dist/chunk-HK67PX4J.js.map +0 -1
  535. package/dist/chunk-HVSCEIYL.js.map +0 -1
  536. package/dist/chunk-IEX7NK2K.js +0 -125
  537. package/dist/chunk-IEX7NK2K.js.map +0 -1
  538. package/dist/chunk-ISZQJBML.js.map +0 -1
  539. package/dist/chunk-J6UOHJY5.js.map +0 -1
  540. package/dist/chunk-KJFW62P4.js.map +0 -1
  541. package/dist/chunk-L7DOS3TE.js.map +0 -1
  542. package/dist/chunk-LGNDFRYC.js.map +0 -1
  543. package/dist/chunk-LGRLME4M.js.map +0 -1
  544. package/dist/chunk-LP7BEXCT.js +0 -32
  545. package/dist/chunk-LP7BEXCT.js.map +0 -1
  546. package/dist/chunk-LQ4ZHOKP.js.map +0 -1
  547. package/dist/chunk-M522UYZ2.js.map +0 -1
  548. package/dist/chunk-M7NI3IWE.js.map +0 -1
  549. package/dist/chunk-MTL7MXGR.js.map +0 -1
  550. package/dist/chunk-N5DNADLQ.js.map +0 -1
  551. package/dist/chunk-NNARWO72.js.map +0 -1
  552. package/dist/chunk-NRT6QZQB.js.map +0 -1
  553. package/dist/chunk-NWHBJQAL.js.map +0 -1
  554. package/dist/chunk-ODVPTDPK.js.map +0 -1
  555. package/dist/chunk-PDCG6PR5.js.map +0 -1
  556. package/dist/chunk-PEOZ34EM.js.map +0 -1
  557. package/dist/chunk-PSIV7CJV.js.map +0 -1
  558. package/dist/chunk-QBBUZ3I3.js.map +0 -1
  559. package/dist/chunk-QOOUUR4A.js.map +0 -1
  560. package/dist/chunk-QWFHIOD2.js.map +0 -1
  561. package/dist/chunk-QWGU66MP.js.map +0 -1
  562. package/dist/chunk-RHVMZSUU.js.map +0 -1
  563. package/dist/chunk-S57HTZ6X.js.map +0 -1
  564. package/dist/chunk-SEE332EV.js +0 -66
  565. package/dist/chunk-SEE332EV.js.map +0 -1
  566. package/dist/chunk-SOIQ4MM4.js +0 -20
  567. package/dist/chunk-SOIQ4MM4.js.map +0 -1
  568. package/dist/chunk-SYVZW77S.js.map +0 -1
  569. package/dist/chunk-T2LBQ5DV.js.map +0 -1
  570. package/dist/chunk-UBSFPGVJ.js +0 -1
  571. package/dist/chunk-UD5EVGZ7.js.map +0 -1
  572. package/dist/chunk-UPD5NWI5.js.map +0 -1
  573. package/dist/chunk-UYB234ZR.js +0 -479
  574. package/dist/chunk-UYB234ZR.js.map +0 -1
  575. package/dist/chunk-VNPEWFPD.js.map +0 -1
  576. package/dist/chunk-WX5ADGTZ.js.map +0 -1
  577. package/dist/chunk-X4773RBR.js.map +0 -1
  578. package/dist/chunk-YNIUIERI.js.map +0 -1
  579. package/dist/chunk-YSK2CU2Q.js.map +0 -1
  580. package/dist/chunk-ZE4CHIED.js.map +0 -1
  581. package/dist/chunk-ZXABPVM6.js.map +0 -1
  582. package/dist/classified-marker-W3USLL5M.js.map +0 -1
  583. package/dist/collection-facade-QU6IJBN3.js +0 -48
  584. package/dist/dead-filter-U2UYKSZL.js.map +0 -1
  585. package/dist/delegation-S3AEPW2T.js.map +0 -1
  586. package/dist/derive-OX7F6TGG.js +0 -21
  587. package/dist/dispatch-RH4LHKBH.js.map +0 -1
  588. package/dist/executor-B6SRO2QS.js +0 -36
  589. package/dist/executor-BI5CHWRY.js +0 -8
  590. package/dist/executor-RBKM5W5K.js +0 -8
  591. package/dist/export-accessible-VMA3YM5V.js +0 -22
  592. package/dist/extract-partition-NF7PXGPP.js +0 -37
  593. package/dist/fanout-sidecar-OT6RYLOL.js.map +0 -1
  594. package/dist/find-LZMP26KF.js +0 -10
  595. package/dist/issue-IHARXWW5.js +0 -18
  596. package/dist/kernel/enclave/classify/compare.d.ts +0 -10
  597. package/dist/kernel/enclave/index.d.ts +0 -87
  598. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +0 -124
  599. package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +0 -88
  600. package/dist/kernel/enclave/record-keys/rekey.d.ts +0 -91
  601. package/dist/kernel/enclave/record-keys/sealed-slot.d.ts +0 -14
  602. package/dist/kernel/enclave/record-keys/sealed-slots.d.ts +0 -123
  603. package/dist/kernel/enclave/record-keys/sealing.d.ts +0 -70
  604. package/dist/liberate-GRLCZMW4.js +0 -24
  605. package/dist/link-set-JCMJ7ULP.js +0 -30
  606. package/dist/noydb-SWQJ3MZS.js +0 -97
  607. package/dist/pod-handle-WGDFB4C2.js.map +0 -1
  608. package/dist/post-register-SLSXIPBV.js.map +0 -1
  609. package/dist/register-F3OYE7MJ.js +0 -31
  610. package/dist/registry-CILQFXFK.js +0 -8
  611. package/dist/registry-XNNYQVKV.js +0 -8
  612. package/dist/registry-YCDZV3VW.js +0 -35
  613. package/dist/registry-ZGYS33TE.js +0 -24
  614. package/dist/request-withdrawal-Z5NC6TXT.js +0 -30
  615. package/dist/reveal-4BCKPEC2.js.map +0 -1
  616. package/dist/revoke-ZL62WC2D.js +0 -23
  617. package/dist/seed-4JS2RJ4A.js.map +0 -1
  618. package/dist/signer-MBZZMXTC.js +0 -24
  619. package/dist/stale-TJ3DYZMQ.js +0 -29
  620. package/dist/storage-SVMKRGCW.js +0 -22
  621. package/dist/store-coordination-provider-2O2VUHKW.js.map +0 -1
  622. package/dist/verify-RVT67IMH.js.map +0 -1
  623. package/dist/walk-HJ42EISE.js +0 -21
  624. package/dist/withdraw-accessible-5NZUPAVA.js +0 -27
  625. /package/dist/{api-GVYEKSJE.js.map → api-MSJXVYQG.js.map} +0 -0
  626. /package/dist/{collection-facade-QU6IJBN3.js.map → capsule/contract.js.map} +0 -0
  627. /package/dist/{kernel/enclave → capsule/enclave-aes}/classify/bidx.d.ts +0 -0
  628. /package/dist/{kernel/enclave → capsule/enclave-aes}/classify/digest.d.ts +0 -0
  629. /package/dist/{kernel/enclave → capsule/enclave-aes}/classify/vdig.d.ts +0 -0
  630. /package/dist/{kernel/enclave/classify → capsule/plumbing}/kofn.d.ts +0 -0
  631. /package/dist/{kernel/enclave/classify → capsule/plumbing}/normalize.d.ts +0 -0
  632. /package/dist/{kernel/enclave → capsule/plumbing}/record-aad.d.ts +0 -0
  633. /package/dist/{chunk-UBSFPGVJ.js.map → capsule-57BDK7LG.js.map} +0 -0
  634. /package/dist/{computed-TPFBX7U4.js.map → chunk-2DX4JCRI.js.map} +0 -0
  635. /package/dist/{chunk-ZSX4S5XB.js.map → chunk-2ZFD2UJC.js.map} +0 -0
  636. /package/dist/{chunk-HT2AHGQI.js.map → chunk-3Y5JLSXS.js.map} +0 -0
  637. /package/dist/{chunk-SI3V7D4G.js.map → chunk-4UIP3QNW.js.map} +0 -0
  638. /package/dist/{chunk-WNJ4AVGE.js.map → chunk-55P6OBB7.js.map} +0 -0
  639. /package/dist/{chunk-MKXXMNJH.js.map → chunk-5UUJE4FP.js.map} +0 -0
  640. /package/dist/{chunk-FW22ZCXT.js.map → chunk-6WS35E6X.js.map} +0 -0
  641. /package/dist/{chunk-6OWXYZK2.js.map → chunk-B65CC6Z6.js.map} +0 -0
  642. /package/dist/{chunk-F2TDU7MQ.js.map → chunk-BJH77UY2.js.map} +0 -0
  643. /package/dist/{chunk-BJ2IXQ5Q.js.map → chunk-BNFNQNEP.js.map} +0 -0
  644. /package/dist/{chunk-HLEK5VAN.js.map → chunk-BUE7R3B5.js.map} +0 -0
  645. /package/dist/{chunk-EOVMT6TB.js.map → chunk-C53ER7AG.js.map} +0 -0
  646. /package/dist/{chunk-K6W7BVZ6.js.map → chunk-CAD7N6HQ.js.map} +0 -0
  647. /package/dist/{chunk-5O7D6ZTW.js.map → chunk-DHU2AQ6T.js.map} +0 -0
  648. /package/dist/{chunk-IT22PWKV.js.map → chunk-ECGXA4LT.js.map} +0 -0
  649. /package/dist/{chunk-4MXI3ODD.js.map → chunk-GCUMOKTN.js.map} +0 -0
  650. /package/dist/{chunk-B6SJIBQK.js.map → chunk-GOJQ5DZA.js.map} +0 -0
  651. /package/dist/{chunk-TKUOEU2F.js.map → chunk-JSWKVZCR.js.map} +0 -0
  652. /package/dist/{chunk-X25NWUZB.js.map → chunk-L5A3KR7R.js.map} +0 -0
  653. /package/dist/{chunk-T52GX4SA.js.map → chunk-LGGIFKJP.js.map} +0 -0
  654. /package/dist/{chunk-ID6Z6E66.js.map → chunk-MQ7YWBQ5.js.map} +0 -0
  655. /package/dist/{chunk-FN5EBVTQ.js.map → chunk-NIXRB5BP.js.map} +0 -0
  656. /package/dist/{chunk-HBRLNOHL.js.map → chunk-NYJBYVBG.js.map} +0 -0
  657. /package/dist/{chunk-ZUVBC32X.js.map → chunk-OK57EATL.js.map} +0 -0
  658. /package/dist/{chunk-TOPYQ6GA.js.map → chunk-PCYPXLEX.js.map} +0 -0
  659. /package/dist/{chunk-VNNRUGMM.js.map → chunk-PGC35KXE.js.map} +0 -0
  660. /package/dist/{chunk-4I522ERM.js.map → chunk-PT2YCQVK.js.map} +0 -0
  661. /package/dist/{chunk-Z5HTYMMQ.js.map → chunk-PTJY5R3O.js.map} +0 -0
  662. /package/dist/{chunk-F24ZZTHQ.js.map → chunk-QGFEBNHO.js.map} +0 -0
  663. /package/dist/{chunk-A6IJU4TK.js.map → chunk-QGSNJD3B.js.map} +0 -0
  664. /package/dist/{chunk-BK2HHQGN.js.map → chunk-QSHATAXJ.js.map} +0 -0
  665. /package/dist/{chunk-JCN44NCY.js.map → chunk-RIZTZJX6.js.map} +0 -0
  666. /package/dist/{chunk-MVZ2TPVP.js.map → chunk-RNACRT5H.js.map} +0 -0
  667. /package/dist/{chunk-TROR3ALR.js.map → chunk-SFCD6OU7.js.map} +0 -0
  668. /package/dist/{chunk-I3JDRCMW.js.map → chunk-TZYTMZZY.js.map} +0 -0
  669. /package/dist/{chunk-AOWGXU6D.js.map → chunk-UAKY6E4N.js.map} +0 -0
  670. /package/dist/{chunk-3JWHAR6E.js.map → chunk-UNSQZSZP.js.map} +0 -0
  671. /package/dist/{chunk-6K7DPM7D.js.map → chunk-WFWFXDNS.js.map} +0 -0
  672. /package/dist/{chunk-CF5UU4S7.js.map → chunk-WHOKGHJ3.js.map} +0 -0
  673. /package/dist/{chunk-32YV3TJT.js.map → chunk-XXNWU5QZ.js.map} +0 -0
  674. /package/dist/{chunk-B57AFBY2.js.map → chunk-XXQ5XIYY.js.map} +0 -0
  675. /package/dist/{chunk-ORDURZBU.js.map → chunk-YFFMPZPY.js.map} +0 -0
  676. /package/dist/{chunk-MDWKM2XC.js.map → chunk-YKGJ44Z7.js.map} +0 -0
  677. /package/dist/{chunk-MLPHLJIQ.js.map → chunk-ZHQJAV6D.js.map} +0 -0
  678. /package/dist/{chunk-7JE7BDYJ.js.map → chunk-ZVSKSUGI.js.map} +0 -0
  679. /package/dist/{derive-OX7F6TGG.js.map → collection-facade-LZIF7GWD.js.map} +0 -0
  680. /package/dist/{enclave-27SMF6GF.js.map → computed-XMFTHAXV.js.map} +0 -0
  681. /package/dist/{executor-B6SRO2QS.js.map → derive-3YSIS36W.js.map} +0 -0
  682. /package/dist/{dispatch-3CQDJV5Q.js.map → dispatch-OFDA4WQV.js.map} +0 -0
  683. /package/dist/{executor-BI5CHWRY.js.map → executor-E6YDJ7YA.js.map} +0 -0
  684. /package/dist/{executor-RBKM5W5K.js.map → executor-NJX3YQQ4.js.map} +0 -0
  685. /package/dist/{export-accessible-VMA3YM5V.js.map → executor-WWM3DD4P.js.map} +0 -0
  686. /package/dist/{extract-partition-NF7PXGPP.js.map → export-accessible-RLHU5G4W.js.map} +0 -0
  687. /package/dist/{find-LZMP26KF.js.map → extract-partition-QII2EDCS.js.map} +0 -0
  688. /package/dist/{issue-IHARXWW5.js.map → find-6M7GYDUZ.js.map} +0 -0
  689. /package/dist/{ledger-KZPCMVZY.js.map → issue-LPEEEMPP.js.map} +0 -0
  690. /package/dist/{liberate-GRLCZMW4.js.map → ledger-MSJGWKGW.js.map} +0 -0
  691. /package/dist/{link-set-JCMJ7ULP.js.map → liberate-LEKDYKTC.js.map} +0 -0
  692. /package/dist/{managed-secret-S3MQ6SH6.js.map → link-set-QXXSPPHL.js.map} +0 -0
  693. /package/dist/{noydb-SWQJ3MZS.js.map → managed-secret-VSK7ANQI.js.map} +0 -0
  694. /package/dist/{migrate-cek-V7GKJZ7O.js.map → migrate-cek-GEBFYBDC.js.map} +0 -0
  695. /package/dist/{register-F3OYE7MJ.js.map → noydb-F2AUF6KL.js.map} +0 -0
  696. /package/dist/{registry-CILQFXFK.js.map → register-SN72QALV.js.map} +0 -0
  697. /package/dist/{registry-XNNYQVKV.js.map → registry-253FF7C6.js.map} +0 -0
  698. /package/dist/{registry-YCDZV3VW.js.map → registry-3AZWQTDT.js.map} +0 -0
  699. /package/dist/{registry-ZGYS33TE.js.map → registry-7UEBTHWG.js.map} +0 -0
  700. /package/dist/{request-withdrawal-Z5NC6TXT.js.map → registry-IVJ67NFQ.js.map} +0 -0
  701. /package/dist/{revoke-ZL62WC2D.js.map → request-withdrawal-UKVJZKX2.js.map} +0 -0
  702. /package/dist/{signer-MBZZMXTC.js.map → revoke-G2KXJQA5.js.map} +0 -0
  703. /package/dist/{stale-TJ3DYZMQ.js.map → signer-IUIYR3CX.js.map} +0 -0
  704. /package/dist/{storage-SVMKRGCW.js.map → stale-SKV33PBU.js.map} +0 -0
  705. /package/dist/{walk-HJ42EISE.js.map → storage-NPBYP2SM.js.map} +0 -0
  706. /package/dist/{withdraw-accessible-5NZUPAVA.js.map → walk-F4OLXI5H.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-formula/materialized-views/window-stage.ts","../src/with-formula/materialized-views/emit-memo.ts","../src/with-formula/materialized-views/executor.ts"],"sourcesContent":["/**\n * #1411 — the declared window stage of a materialized view.\n *\n * `unionSources` → `map` → `groupBy` → `aggregate` → **`window`** → `derive`.\n *\n * ## Why a window is safe here when `derive` is deliberately single-row\n *\n * `derive`'s contract is *pure, single-row, no cross-row access* — a window is\n * the opposite of all three. The difference is not caution, it is that\n * materialization is a FULL RECOMPUTE: the executor holds every row the view\n * will store, in one array, before it writes any of them. So an\n * order-dependent, cross-row pass runs exactly once over exactly the rows that\n * get stored, and its output is then an ordinary column. A per-row recompute\n * could not do this — inserting a row early in a partition moves every later\n * row's running total.\n *\n * ## Why this does not simply call `applyWindow`\n *\n * ⚠️ `applyWindow` does no Via rewriting. On the ad-hoc builder,\n * `Query.window().select()` rewrites reducer slots through the COLLECTION's\n * Via pipeline first, which is what makes `runningMoneySum` exact. A UNION-mode\n * MV has no collection — its rows are MAPPED — so it has the same answer\n * `aggregate` already uses: the MV's own `moneyFields` descriptors, bound\n * through the kernel's Via port. This mirrors `groupAndReduce`'s money block\n * line for line, deliberately: two places that must agree about what a money\n * reducer is, doing it the same way.\n *\n * Without that rewrite the failure is silent and specific — a running total\n * over decimal strings accumulates in float and returns\n * `0.6000000000000001` where the aggregate on the same rows returns `'0.60'`.\n */\nimport { applyWindow } from '../../with-lookup/reduce/window.js'\nimport type { WindowSelectSpec, WindowSpec } from '../../with-lookup/reduce/window.js'\nimport { bindDistinctReducers } from '../../with-lookup/reduce/reducers.js'\nimport type { Reducer } from '../../with-lookup/reduce/reducers.js'\nimport type { ReduceSpec } from '../../with-lookup/reduce/reduction.js'\nimport { viaBinder } from '../../kernel/via/index.js'\nimport type { MaterializedViewWindow, MoneyDescriptorMap } from './types.js'\n\n/** Is this slot a window function rather than a reducer? */\nfunction isWindowFn(v: unknown): boolean {\n return typeof v === 'object' && v !== null && (v as { __window?: unknown }).__window === true\n}\n\n/**\n * Apply a declared window to the finished row set.\n *\n * `moneyFields` is the MV's own descriptor map; when present, every REDUCER\n * slot is rewritten exactly as `aggregate`'s are. Window functions\n * (`rowNumber`, `rank`, `lag`, `lead`) are passed through untouched — they\n * navigate rows rather than accumulate values, so there is nothing to make\n * exact.\n */\nexport function applyDeclaredWindow(\n rows: readonly Record<string, unknown>[],\n window: MaterializedViewWindow,\n moneyFields?: MoneyDescriptorMap,\n): ReadonlyArray<Record<string, unknown>> {\n if (rows.length === 0) return rows\n\n let select: WindowSelectSpec = window.select\n if (moneyFields) {\n const reducersOnly: Record<string, Reducer<unknown, unknown>> = {}\n for (const [k, v] of Object.entries(select)) {\n if (!isWindowFn(v)) reducersOnly[k] = v as Reducer<unknown, unknown>\n }\n if (Object.keys(reducersOnly).length > 0) {\n const binding = viaBinder('money')({ moneyFields })\n let wrapped = binding.wrapReducers!(reducersOnly as ReduceSpec) as Record<\n string,\n Reducer<unknown, unknown>\n >\n wrapped = bindDistinctReducers(wrapped as ReduceSpec, {\n canonicalizeIndexKey: (f, v) => binding.canonicalizeIndexKey?.(f, v),\n }) as Record<string, Reducer<unknown, unknown>>\n select = { ...select, ...wrapped }\n }\n }\n\n // `applyWindow` takes the partition/order spec and the select list\n // separately, so strip `select` off rather than pass it twice. Built by\n // spreading absent keys away rather than assigning `undefined` — the package\n // compiles under `exactOptionalPropertyTypes`, where the two differ.\n const spec: WindowSpec = {\n ...(window.partitionBy !== undefined && { partitionBy: window.partitionBy }),\n ...(window.orderBy !== undefined && { orderBy: window.orderBy }),\n }\n return applyWindow<Record<string, unknown>>(rows, spec, select)\n}\n","/**\n * Skip re-writing materialized-view output rows whose content has not changed\n * (#1418).\n *\n * `MaterializedViewExecutor.refresh()` recomputes the whole view and then\n * writes EVERY output row, on every source write. Measured on one MV with a\n * single union arm, writing rows the MV's own `map` drops:\n *\n * 250 receipts / 250 bills → 23.0 ms per source write\n * 450 receipts / 450 bills → 41.6 ms per source write\n *\n * 1.8x the sources, 1.8x the cost — because the thing that grew was the OUTPUT\n * ROW COUNT, and each row is an encrypt-and-store round trip. The query and the\n * aggregation are not where the time goes.\n *\n * ## Why this, and not \"skip the refresh when the row maps to nothing\"\n *\n * The issue proposed short-circuiting the refresh when the written row's `map`\n * returns null. That cannot be built as stated, and the reason is worth\n * recording so nobody re-attempts it:\n *\n * 1. `materializeUnionResult` feeds `map` rows from `coll.query().toArray()`,\n * which applies `decodeVia` — money arrives as a canonical decimal string,\n * not the stored scaled integer. Probing `arm.map(writtenRecord)` at\n * dispatch time hands `map` a DIFFERENTLY SHAPED row, so any `map` that\n * filters on a money field can answer `null` where the real pipeline would\n * not. The view then silently stops updating, which is far worse than the\n * latency it was meant to fix.\n * 2. Skipping also requires that the row contributed nothing BEFORE, or an\n * update that removes a row from the view is dropped. The prior record is\n * not passed to the dispatcher, and is a stored record, so it hits (1)\n * twice over.\n * 3. An arm with `join` legs has the right side attached before `map` runs, so\n * a probe would have to resolve the legs too.\n *\n * Comparing the row we are ABOUT to write against the row we LAST wrote sides\n * steps all three. It needs no prior record, it is form-agnostic (query, union\n * and projection all benefit), and it degrades to the right thing: a write that\n * changes one group rewrites one row instead of all of them.\n *\n * ## Why the entries are canonical strings and not short hashes\n *\n * A hash collision here means a row that is never rewritten — a silently stale\n * view with no symptom. At the 20k-row cap below, an 8-byte hash carries a\n * couple of percent chance of one collision somewhere, which is not a trade\n * worth making for memory. So entries hold the full canonical string, and\n * memory is bounded by refusing to memoize a view larger than the cap.\n *\n * ## Why a mutation stamp, and what it does NOT cover\n *\n * The memo is only sound while nothing else writes the output collection —\n * tombstoning, `invalidateMVAtRest`, forget/erase and sync cut-over all can. So\n * a refresh records the output collection's mutation stamp AFTER its writes,\n * and the next refresh discards the whole set unless the stamp is still where\n * it left it. That is a \"nobody else touched this\" test rather than an\n * enumeration of writers — the same reasoning that made #1417's keyset memo and\n * #1426's slot guard safe, and it does not rot when a new writer is added.\n *\n * ⚠️ It covers writers that go THROUGH the output `Collection`. A writer that\n * bypasses it and edits the store directly moves neither the stamp nor the\n * collection's own cache — but such a writer already makes `list()` on that\n * collection wrong, so it is a broader defect than this memo.\n *\n * ## ⛔ The memo stands down when a REDUNDANT write is still observable\n *\n * `Collection._cacheStamp` returns `null` — no memo — whenever writing the same\n * bytes again would have an effect beyond the stored bytes. This is the half\n * that is easy to get wrong, and it was found by a failing test rather than by\n * reasoning, so the cases are recorded:\n *\n * - **A `beforePut` gate handler.** Measured: with `withPeriods()` and a\n * closed period, an unchanged MV row previously produced a\n * `PeriodClosedError` from `put`, which `putDerivedOutput` converts into a\n * `derivation:skipped-frozen` event and an audit record. Skipping the write\n * silences that — `written=0 skipped=2 events=0` where the suite expects one\n * event. A performance change must not quietly narrow a compliance signal.\n * - **Explicit history.** A put records a version, so skipping changes what\n * `history()` returns. (Arguably an improvement — 450 identical versions per\n * source write is not useful — but that is a product call, not this one.)\n * - **Sync (`onDirty`) and the search index.** Both mark state from the fact\n * that a write happened, independently of what was written.\n * - **Lazy mode**, which has no eager cache to stamp.\n *\n * The asymmetry is what makes this the right default: opting out costs the old\n * write path, opting in wrongly changes behaviour with no symptom at all.\n *\n * ⭐ So an MV whose OUTPUT collection carries periods, history, sync or search\n * gets no speedup. That is deliberate, and it is the first thing to check when\n * this fix appears not to help a real workload — the answer is per output\n * collection, not per vault.\n *\n * ⛔ A row is recorded ONLY when the write actually landed. A `putDerivedOutput`\n * that declines (the frozen-period skip) or throws leaves no entry, so the next\n * refresh writes it again rather than believing a row exists that does not.\n *\n * @module\n */\nimport { canonicalizeQueryPlan } from './query-hash.js'\n\n/**\n * Views larger than this are not memoized at all. The memo would otherwise\n * hold a canonical string per row for the process's life, and a view this size\n * is dominated by its write cost in ways one skip cannot rescue.\n */\nconst MAX_MEMOIZED_ROWS = 20_000\n\ninterface EmitMemo {\n /** The output collection's mutation stamp when this set was written. */\n readonly stamp: number\n /** `outputId -> canonical content string` for rows this MV actually wrote. */\n readonly rows: Map<string, string>\n}\n\nconst memos = new Map<string, EmitMemo>()\n\n/**\n * Identity of one MV's output, per vault — MV names are not globally unique.\n *\n * ⚠️ `\\0` written as the ESCAPE, not as a raw byte. A raw NUL in the source\n * makes git classify the whole file as binary, so it stops diffing and stops\n * being reviewable — caught here by a `Bin 0 -> 8811 bytes` line in a diffstat.\n * The separator itself is right: no vault or collection name can contain one.\n */\nexport function emitMemoKey(vault: string, mvName: string, outputCollection: string): string {\n return `${vault}\\0${mvName}\\0${outputCollection}`\n}\n\n/**\n * The rows this MV last wrote, or `null` when the memo cannot be trusted —\n * nothing recorded yet, or the output collection moved under us.\n *\n * `stamp` of `null` means the collection cannot supply one (lazy mode), which\n * is treated as \"no memo\" rather than \"unchanged\".\n */\nexport function readEmitMemo(key: string, stamp: number | null): ReadonlyMap<string, string> | null {\n if (stamp === null) return null\n const hit = memos.get(key)\n if (!hit || hit.stamp !== stamp) {\n // Someone else wrote the output collection. Everything we believed about\n // its contents is now a guess, so drop all of it rather than reconcile.\n if (hit) memos.delete(key)\n return null\n }\n return hit.rows\n}\n\n/** Record what this refresh actually left on disk. A `null` stamp records nothing. */\nexport function writeEmitMemo(key: string, stamp: number | null, rows: Map<string, string>): void {\n if (stamp === null || rows.size > MAX_MEMOIZED_ROWS) {\n memos.delete(key)\n return\n }\n memos.set(key, { stamp, rows })\n}\n\n/** Forget one MV's output entirely. Used when a refresh could not complete cleanly. */\nexport function dropEmitMemo(key: string): void {\n memos.delete(key)\n}\n\n/**\n * A canonical string for the row a refresh is about to write, or `null` when no\n * safe one exists.\n *\n * The MV's `queryHash` is folded in so a strategy change rewrites every row\n * even where the projected content happens to match — a row carrying a stale\n * `_materializedFrom.queryHash` is stale by definition (`stale.ts`).\n *\n * `_materializedFrom` itself is excluded: its `materializedAt` moves on every\n * refresh, so including it would make every comparison differ and the memo a\n * pure cost.\n *\n * ⛔ Returns `null` rather than throwing on anything `JSON.stringify` refuses\n * (a `BigInt`, a cycle). Declining to memoize costs the old write; guessing\n * costs a stale view.\n */\nexport function rowContentKey(row: Record<string, unknown>, queryHash: string): string | null {\n try {\n // `_materializedFrom` is excluded by rebuilding without it rather than by\n // destructuring into an unused binding — same result, no dead name.\n const content: Record<string, unknown> = {}\n for (const k of Object.keys(row)) {\n if (k !== '_materializedFrom') content[k] = row[k]\n }\n return `${queryHash}\\0${canonicalizeQueryPlan(content)}`\n } catch {\n return null\n }\n}\n\n/** Test seam — the process-wide memo must not leak between test cases. */\nexport function _clearEmitMemos(): void {\n memos.clear()\n}\n","import { groupKeyName, isDateTruncKey, projectDateTruncKeys, type GroupKey } from '../../kernel/query/reduce/date-trunc.js'\nimport type { Collection } from '../../kernel/collection.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport { MaterializedViewTooLargeError, MaterializedViewConfigError, LocaleNotSpecifiedError, JoinTooLargeError } from '../../kernel/errors.js'\nimport { DEFAULT_JOIN_MAX_ROWS } from '../../kernel/query/relate/join.js'\nimport type { MaterializedFromMeta, MVQueryContext, MaterializedViewSpec, ProjectionJoinLeg } from './types.js'\nimport type { RegisteredMV } from './registry.js'\nimport { wrapDbWithPredicates, ungatedMvContext } from './registry.js'\nimport { groupAndReduce } from '../../with-lookup/reduce/groupby.js'\nimport { applyDeclaredWindow } from './window-stage.js'\nimport { canonicalGroupKey } from '../../with-lookup/reduce/canonical-key.js'\nimport { applyI18nLocale, type I18nTextDescriptor } from '../../via/i18n/core.js'\nimport { canonicalizeMoneyFieldsAsDecimal, decodeMoneyFields } from '../../via/money/normalize.js'\nimport { exactMath } from '../../via/money/exact.js'\nimport { putDerivedOutput, type PutDerivedOutputCtx } from '../../kernel/via/dispatch.js'\nimport { isCollectLeg, resolveLegOwner, type RefLookup } from './projection-legs.js' // #1140\nimport { emitMemoKey, readEmitMemo, writeEmitMemo, rowContentKey } from './emit-memo.js' // #1418\n\n/**\n * Accessor shape passed in from the owning Vault. Mirrors v1's\n * `DerivationStaleAccessor` — provides the per-collection resolver\n * and the active TxContext so refresh writes/tombstones register on\n * `_executed` for rollback symmetry.\n */\nexport interface MVExecutorAccessor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n getActiveTxContext(): TxContext | null\n /**\n * Vault-shaped accessor passed to the MV's `query()` callback at\n * each refresh. Same instance the registry used at registration\n * time; threading through the executor lets the refresh path\n * re-evaluate the closure against the live vault state.\n */\n getQueryContext(): MVQueryContext\n /**\n * #638 Task 5 — ctx for `putDerivedOutput`'s frozen-period skip+audit. #641: the lazy\n * resolve-on-read caller (`stale.ts#resolveStaleMVOnRead`) now supplies one too — built at\n * the `Collection.get()`/`list()` entry point with a `'resolve-on-read'` sentinel id (no\n * real \"reacting write\" for a read-triggered materialize, mirroring `refreshView()`'s\n * `'refreshView'` sentinel). Still declared optional here since `MVExecutorAccessor` is a\n * general shape and a future caller could reasonably omit it.\n */\n dispatchCtx?: PutDerivedOutputCtx\n}\n\nexport interface RefreshResult {\n /** Rows newly written / overwritten. */\n written: number\n /**\n * #1418 — rows whose content was byte-identical to what this MV last wrote,\n * so the encrypt-and-store round trip was skipped. Counted separately from\n * `written` on purpose: `written` means \"a row was persisted\", and reporting\n * a skip as a write would make the two indistinguishable to anyone\n * diagnosing whether a refresh actually did anything.\n */\n skipped: number\n /** Rows tombstoned via `_internalDelete` (only when `onEmpty: 'delete'`). */\n deleted: number\n /** Failed row writes (non-strict mode). */\n failed: number\n /** #782/#785 — `outputCollection:id` entries from the tombstone pass whose ownership stamp\n * couldn't be decoded under the collection's default DEK (undecodable, mirroring\n * `invalidateMVAtRest`'s #776 posture) — ownership UNCONFIRMED. Only populated when\n * `onEmpty: 'delete'`. */\n residueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` entries that decoded, stamp-matched this MV, but\n * `_internalDelete` declined (the #718 tier-elevation gate) — ownership CONFIRMED, a real\n * silent survival, surfaced rather than dropped. Only populated when `onEmpty: 'delete'`. */\n residueDeclined: string[]\n}\n\n/** Default cost ceiling — overridable per-MV via `spec.maxRows`. */\nconst DEFAULT_MAX_ROWS = 100_000\n\n/**\n * Materialize a query terminal that may be a `Query<T>` (call\n * `.toArray()`), an `Reduction<R>` (call `.run()` returning a\n * single object — wrap as a one-row array), or a `GroupedReduction<R>`\n * (call `.run()` returning an array of grouped rows). Branches on\n * available terminal at runtime — no type-discrimination at registration.\n */\nasync function materializeQueryResult(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n q: any,\n mvName: string,\n i18nLocale?: string,\n i18nFields?: Record<string, I18nTextDescriptor>,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n if (typeof q?.toArray === 'function') {\n // Query<T> — non-aggregate path. `.toArray()` returns Promise<T[]>.\n return await q.toArray()\n }\n if (typeof q?.run === 'function') {\n // Reduction<R> or GroupedReduction<R>. `.run()` is synchronous\n // and returns either a single object (Reduction) or an array of\n // rows (GroupedReduction). Promise.resolve() normalizes both\n // sync and async (future) variants.\n // Query-form MV grouping: when the MV declares i18nLocale, pass it +\n // i18nFields so a GroupedReduction resolves i18n group keys before\n // bucketing (the Reduction path ignores the extra arg).\n const runOpts = i18nLocale !== undefined ? { locale: i18nLocale, i18nFields } : undefined\n const result: unknown = await Promise.resolve(q.run(runOpts))\n if (Array.isArray(result)) {\n return result as ReadonlyArray<Record<string, unknown>>\n }\n // Single-aggregate result — wrap as one-row array. The consumer's\n // `rowKey()` should return a stable identity (often a literal\n // constant like `'total'`) since there's only one row.\n return [result as Record<string, unknown>]\n }\n throw new Error(\n `MV \"${mvName}\": query() must return a Query<T>, Reduction, or GroupedReduction. ` +\n `Got something without a .toArray() or .run() terminal.`,\n )\n}\n\n/**\n * Materialize a UNION-form MV: read every arm's source\n * collection, apply each arm's `map` to project rows into the unified\n * MV row shape, concatenate the mapped streams, then optionally run\n * `groupBy` + `aggregate` over the result.\n *\n * Modes (driven by `spec.groupBy` / `spec.aggregate`):\n *\n * - No `groupBy` → return the concatenated mapped rows unchanged.\n * - `groupBy` without `aggregate` → dedupe by composite group key,\n * keep the first row seen per key (later arms don't overwrite\n * earlier arms — Map insertion order rules).\n * - `groupBy` + `aggregate` → delegate to the shared `groupAndReduce`\n * pipeline used by `Query.groupBy().aggregate()`.\n *\n * Per-arm `map` is the schema-unification boundary; the strategy's\n * `TRow` type parameter enforces that every arm projects into the\n * same shape at compile time.\n *\n * @internal\n */\nasync function materializeUnionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const unified: TRow[] = []\n for (const arm of spec.unionSources!) {\n const coll = db.collection<Record<string, unknown>>(arm.collection)\n // Optional per-arm FK joins: chain `.join(field, { as, ... })` for\n // each declared leg before terminating. The aliased right-side\n // record lands at `sourceRow[leg.as]`, where the arm's `map` reads\n // it. Cast to `any` because the chained join widens the row type but\n // the executor treats every row as `Record<string, unknown>` — same\n // pattern the query-form join path uses.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n if (arm.join?.length) {\n for (const leg of arm.join) {\n // #1411 — a declared leg is `Query.joinOn()`; a ref leg is `Query.join()`.\n q = 'on' in leg\n ? q.joinOn(leg.target, { as: leg.as, on: leg.on, mode: leg.mode, maxRows: leg.maxRows })\n : q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n }\n const sourceRows = q.toArray() as ReadonlyArray<Record<string, unknown>>\n for (const r of sourceRows) {\n const mapped = arm.map(r)\n // null / undefined means \"omit this source row\" — skip without\n // pushing so groupBy/aggregate never see a null entry.\n if (mapped == null) continue\n unified.push(mapped)\n }\n }\n\n return finalizeMappedRows(spec, unified)\n}\n\n\n/**\n * #1411 — the window stage, applied at every exit from the grouping tail.\n *\n * A no-op without `spec.window`, so the ungrouped and grouped paths can both\n * call it unconditionally rather than each remembering to.\n */\nfunction applyWindowStage<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n rows: ReadonlyArray<Record<string, unknown>>,\n): ReadonlyArray<Record<string, unknown>> {\n if (!spec.window) return rows\n return applyDeclaredWindow(rows, spec.window, spec.moneyFields)\n}\n\n/**\n * Shared post-map tail for the UNION and projection (#810) forms:\n * optional `groupBy` (+ `aggregate`) over the mapped-row stream.\n * Extracted verbatim from `materializeUnionResult` so both forms feed\n * the identical grouping pipeline — i18n group-key resolution, the\n * object-group-key guard, dedup-without-aggregate, and the shared\n * `groupAndReduce` delegate.\n *\n * @internal\n */\nfunction finalizeMappedRows<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n unified: TRow[],\n): ReadonlyArray<Record<string, unknown>> {\n // #1411 — a window with no grouping is a legitimate shape: the pilot's\n // running total is per-row, not per-bucket. Both exits go through the same\n // stage so the two cannot drift on whether a window ran.\n if (!spec.groupBy) return applyWindowStage(spec, unified)\n\n const groupKeys: readonly GroupKey[] = Array.isArray(spec.groupBy)\n ? (spec.groupBy as readonly GroupKey[])\n : [spec.groupBy as GroupKey]\n const groupFields: readonly string[] = groupKeys.map(groupKeyName)\n\n // Derived calendar keys (#1350) are bucketed onto the mapped row first, so\n // every rule below — the i18n resolution, the object-key refusal, the dedup\n // path and `groupAndReduce` — sees an ordinary stored field.\n const derivedKeys = groupKeys.filter(isDateTruncKey)\n if (derivedKeys.length > 0) {\n unified = projectDateTruncKeys(unified, derivedKeys)\n }\n\n // i18n-aware group keys. An `i18nText` group field carries a raw\n // `{ locale: string }` map, an unstable object key. When `i18nLocale` is\n // declared (with `i18nFields` describing those fields), resolve the declared\n // group-key i18n fields to it at the `mv` layer FIRST — the same unified-rows\n // boundary where money is threaded — so buckets are stable strings and the\n // `mv`-layer `onMissing` policy fires here.\n if (spec.i18nLocale !== undefined && spec.i18nFields !== undefined) {\n const groupI18n: Record<string, I18nTextDescriptor> = {}\n for (const f of groupFields) {\n const d = spec.i18nFields[f]\n if (d !== undefined) groupI18n[f] = d\n }\n if (Object.keys(groupI18n).length > 0) {\n for (let i = 0; i < unified.length; i++) {\n unified[i] = applyI18nLocale(unified[i] as Record<string, unknown>, groupI18n, spec.i18nLocale, undefined, 'mv') as TRow\n }\n }\n }\n // Guard (always): a remaining object-valued group key — an undeclared i18n\n // field or a locale-less MV — would bucket on a map. Refuse, don't bucket wrong.\n for (const f of groupFields) {\n for (const row of unified) {\n const v = (row as Record<string, unknown>)[f]\n if (v !== null && typeof v === 'object') {\n throw new LocaleNotSpecifiedError(\n f,\n `Materialized view \"${spec.name}\" groups by \"${f}\", whose value is a raw i18n locale map — ` +\n `an unstable object group key. Declare { i18nLocale, i18nFields } on the MV to resolve it at ` +\n `the 'mv' layer, or group by a dictKey/staticDict code (the stable key) and resolve the label at read time.`,\n )\n }\n }\n }\n\n // groupBy without aggregate — dedupe by composite key, keep first\n // seen row per key. Useful for cross-arm uniqueness (e.g. unify two\n // sibling collections, keeping one row per natural key).\n if (!spec.aggregate) {\n const seen = new Map<string, TRow>()\n for (const row of unified) {\n const k = canonicalGroupKey(groupFields, row as Record<string, unknown>)\n if (!seen.has(k)) seen.set(k, row)\n }\n return [...seen.values()]\n }\n\n // groupBy + aggregate — delegate to the shared pipeline used by\n // `Query.groupBy().aggregate()`. Result rows carry each grouped\n // field in declaration order followed by the spec's reducer outputs.\n return applyWindowStage(\n spec,\n groupAndReduce<Record<string, unknown>>(unified, groupFields, spec.aggregate, spec.moneyFields),\n )\n}\n\n/**\n * Apply the spec's `derive` to each finished row (#1007).\n *\n * Three rules, all of them about keeping the hook narrow enough that the\n * engine never has to reason about the function:\n *\n * - a `null` / `undefined` return leaves the row untouched;\n * - a returned key that collides with a `groupBy` field is refused — group\n * keys are the row's identity and feed `rowKey`, so letting `derive`\n * rewrite one would silently re-home the row into a different bucket than\n * the one it was aggregated for;\n * - a derived field declared in `moneyFields` is quantised through its\n * descriptor, so the stored value is exact at the declared scale instead of\n * whatever the user's arithmetic produced.\n *\n * @internal\n */\nfunction applyDerive<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n rows: ReadonlyArray<Record<string, unknown>>,\n): ReadonlyArray<Record<string, unknown>> {\n const groupFields = new Set<string>(\n spec.groupBy === undefined\n ? []\n : (Array.isArray(spec.groupBy) ? spec.groupBy : [spec.groupBy]).map(groupKeyName),\n )\n return rows.map((row) => {\n // `derive` sees the row the way a READER would: money decoded to its\n // canonical decimal form, not the scaled integer the reducer left behind.\n // Handing over `1005` where the schema says `10.05` would make every\n // derived money expression quietly wrong by a factor of the scale.\n // `'raw'` keeps it at the exact decimal rather than a locale-formatted\n // string, which is what `exact.*` consumes.\n const view = spec.moneyFields ? decodeMoneyFields(row, spec.moneyFields, 'raw') : row\n const patch = spec.derive!(view as TRow, exactMath)\n if (patch === null || patch === undefined) return row\n for (const key of Object.keys(patch)) {\n if (groupFields.has(key)) {\n throw new MaterializedViewConfigError(\n `Materialized view \"${spec.name}\": derive() returned the group key \"${key}\". ` +\n 'A group key is the row\\'s identity and feeds rowKey — rewriting it would re-home the ' +\n 'row into a bucket it was not aggregated for. Emit a differently-named field instead.',\n )\n }\n }\n // Canonicalize the PATCH only, into the DECIMAL form the money-aware\n // reducers emit — not the scaled-integer storage form a collection uses.\n // An MV row's money fields are decimal strings, so a derived field\n // quantised into storage form reads back as the scaled integer beside\n // correctly-decoded siblings: `\"1000000\"` next to `\"10000.00\"` (#1018).\n // Precision is still enforced; only the output shape differs.\n const canonical = spec.moneyFields\n ? canonicalizeMoneyFieldsAsDecimal(patch, spec.moneyFields)\n : patch\n return { ...row, ...canonical }\n })\n}\n\n/**\n * Materialize a projection-form MV (#810): hydrate the primary source\n * rows, resolve forward FK legs through the same `.join()` machinery\n * the UNION arms use, attach reverse \"collect\" legs via one\n * hash-grouped snapshot pass per leg, then run the projection `map`\n * (null / undefined omits the primary row) and the shared post-map\n * grouping tail.\n *\n * @internal\n */\nasync function materializeProjectionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const projection = spec.projection!\n const coll = db.collection<Record<string, unknown>>(projection.source)\n // ROOT forward legs chain through the query builder exactly like UNION arm\n // joins — ref() resolution, dangling-mode semantics, presentation dressing,\n // and ceilings all ride the existing `.join()` path. Cast to `any` for the\n // same reason `materializeUnionResult` does.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n for (const leg of projection.joins) {\n if (isCollectLeg(leg) || leg.from !== undefined) continue\n q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n let rows = q.toArray() as Array<Record<string, unknown>>\n // Remaining legs in DECLARATION order — which is what makes `from` work: a leg\n // may only name an alias declared earlier, so by the time it runs, the rows it\n // attaches to are already on the row. Root collect legs are in this loop too;\n // they were never part of the query chain.\n for (const leg of projection.joins) {\n if (isCollectLeg(leg)) {\n rows = applyCollectLeg(rows, leg, spec.name, projection.source, projection.joins, db)\n } else if (leg.from !== undefined) {\n rows = applyLegRelativeForwardLeg(rows, leg, spec.name, projection.source, projection.joins, db)\n }\n }\n const mapped: TRow[] = []\n for (const r of rows) {\n const m = projection.map(r)\n // null / undefined means \"omit this primary row\" — same contract\n // as the UNION arm `map`.\n if (m == null) continue\n mapped.push(m)\n }\n return finalizeMappedRows(spec, mapped)\n}\n\n/**\n * A `RefLookup` backed by the live join contexts — the executor's answer to the\n * same question the registry answers from the ref registry. Reads through, so a\n * ref declared after `openVault()` (the only place refs CAN be declared) is\n * visible here.\n *\n * @internal\n */\nfunction legOwnerLookup(db: MVQueryContext): RefLookup {\n return (collection, field) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const q = db.collection<Record<string, unknown>>(collection).query() as any\n return (q._joinContext?.()?.resolveRef(field) as { target: string } | null | undefined) ?? null\n }\n}\n\n/**\n * Attach one FORWARD leg that hangs off another leg's alias (#1140).\n *\n * Root forward legs ride `Query.join()` and are resolved before this runs; a\n * leg-relative one cannot, because the FK it follows lives on an already-attached\n * record rather than on a column of the primary query. It is therefore resolved\n * the same way a collect leg is — one snapshot of the target collection, indexed\n * by id — which keeps it O(N+M) rather than one `get()` per row.\n *\n * Attaches `null` when the `from` alias is null (a dangling ref upstream), when\n * the FK is nullish, or when the target row is missing. That is deliberately\n * outer-by-nature and matches the collect leg's empty array: a projection MV\n * must not drop a primary row because something two hops away is absent.\n *\n * @internal\n */\nfunction applyLegRelativeForwardLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: Extract<ProjectionJoinLeg, { field: string }>,\n mvName: string,\n source: string,\n joins: ReadonlyArray<ProjectionJoinLeg>,\n db: MVQueryContext,\n): Array<Record<string, unknown>> {\n const lookup = legOwnerLookup(db)\n const owner = resolveLegOwner(leg, joins, source, lookup)\n const refDesc = owner === null ? null : lookup(owner, leg.field)\n if (owner === null || refDesc === null) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection leg \"${leg.as}\" requires a ref() on field \"${leg.field}\" of `\n + `collection \"${owner ?? `(behind from: \"${leg.from}\")`}\" — declare it on that collection, `\n + `then retry`,\n )\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetQ = db.collection<Record<string, unknown>>(refDesc.target).query() as any\n const byId = new Map<string, Record<string, unknown>>()\n for (const row of targetQ.toArray() as Array<Record<string, unknown>>) {\n const id = coerceCollectKey(row.id)\n if (id !== null) byId.set(id, row)\n }\n return primaryRows.map((row) => {\n const anchor = leg.from === undefined\n ? row\n : (row[leg.from] as Record<string, unknown> | null | undefined)\n const key = anchor == null ? null : coerceCollectKey(anchor[leg.field])\n return { ...row, [leg.as]: key === null ? null : byId.get(key) ?? null }\n })\n}\n\n/**\n * Attach one reverse \"collect\" leg (#810): every row of `leg.collect`\n * whose `leg.on` field references the ATTACH POINT's id lands in a\n * possibly-empty ARRAY under `leg.as` on that primary row. One\n * snapshot pass over the collect collection, hash-grouped by the `on`\n * FK — O(N+M), mirroring the forward hash-join fallback.\n *\n * The attach point is the primary record, or — with `from` (#1140) — the record\n * already attached under that alias. Matching then keys off `row[from].id`\n * instead of `row.id`, and `leg.on` must ref THAT leg's collection. A row whose\n * `from` alias is null (a dangling forward ref) gets `[]`, which is the same\n * outer-by-nature semantics a root collect leg already has for a primary record\n * with no children.\n *\n * Semantic check (first materialization, not factory time — parity\n * with join-time ref errors): `leg.on` must carry a `ref()` declared\n * on the collect collection targeting the attach point's collection.\n *\n * @internal\n */\nfunction applyCollectLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: { readonly collect: string; readonly on: string; readonly as: string; readonly from?: string; readonly maxRows?: number },\n mvName: string,\n source: string,\n joins: ReadonlyArray<ProjectionJoinLeg>,\n db: MVQueryContext,\n): Array<Record<string, unknown>> {\n const childColl = db.collection<Record<string, unknown>>(leg.collect)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const childQ = childColl.query() as any\n const refDesc = childQ._joinContext?.()?.resolveRef(leg.on) as { target: string } | null | undefined\n // The collection this leg matches AGAINST: the projection source for a root\n // leg, the `from` leg's own target otherwise (#1140).\n const expected = resolveLegOwner(leg, joins, source, legOwnerLookup(db))\n const expectedName = expected ?? source\n if (refDesc == null) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" requires a ref() on field \"${leg.on}\" of `\n + `collection \"${leg.collect}\" targeting \"${expectedName}\" — declare `\n + `refs: { ${leg.on}: ref('${expectedName}') } on collection \"${leg.collect}\", then retry`,\n )\n }\n if (refDesc.target !== expectedName) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" expects field \"${leg.on}\" of collection `\n + `\"${leg.collect}\" to reference ${leg.from === undefined\n ? `the projection source \"${expectedName}\"`\n : `\"${expectedName}\" (the collection behind from: \"${leg.from}\")`}`\n + `, but its ref() targets \"${refDesc.target}\"`,\n )\n }\n const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS\n const groups = new Map<string, Array<Record<string, unknown>>>()\n for (const child of childQ.toArray() as Array<Record<string, unknown>>) {\n const key = coerceCollectKey(child[leg.on])\n // Nullish / non-scalar FK values mean \"no reference\" — same\n // narrowing as the forward join path's key coercion.\n if (key === null) continue\n const bucket = groups.get(key)\n if (bucket) bucket.push(child)\n else groups.set(key, [child])\n }\n const out: Array<Record<string, unknown>> = []\n for (const row of primaryRows) {\n // `from` matches against the attached record's id, not the primary row's.\n const anchor = leg.from === undefined\n ? row\n : (row[leg.from] as Record<string, unknown> | null | undefined)\n const key = anchor == null ? null : coerceCollectKey(anchor.id)\n const children = key === null ? [] : groups.get(key) ?? []\n if (children.length > maxRows) {\n throw new JoinTooLargeError({\n leftRows: primaryRows.length,\n rightRows: children.length,\n maxRows,\n side: 'right',\n message:\n `projection MV \"${mvName}\": collect leg \"${leg.as}\" gathered ${children.length} ` +\n `\"${leg.collect}\" rows for one \"${source}\" record, exceeding the ${maxRows}-row ` +\n `per-primary-row ceiling. Raise the ceiling via { maxRows } on the leg if the ` +\n `fan-out genuinely fits in memory, or restructure the child collection.`,\n })\n }\n out.push({ ...row, [leg.as]: children })\n }\n return out\n}\n\n/**\n * Coerce an unknown FK value into a collect-grouping key. Same\n * narrowing as the join path's `coerceRefKey` (not exported from\n * there): strings and numbers are legitimate ref values; anything\n * else is \"no reference\" and returns `null`.\n *\n * @internal\n */\nfunction coerceCollectKey(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'bigint') return String(value)\n return null\n}\n\n/**\n * Run an MV's `query()` and write the result rows to the output\n * collection. Same-DEK encryption: routes through the standard\n * `Collection.put` pipeline, so the output collection's DEK is what\n * gets used (matches the v2 spec's \"same DEK as the left-most source\"\n * invariant — `Collection.put` looks up the DEK by collection name,\n * and the output collection IS the MV's owned collection).\n *\n * Stamps `_materializedFrom` onto every emitted row.\n *\n * **Tombstoning:** when `spec.onEmpty: 'delete'` (default), rows\n * that existed in a prior refresh but no longer appear in the new\n * materialized result are deleted via `Collection._internalDelete` —\n * the housekeeping bypass primitive prevents user\n * `onDelete` guards on the output collection from firing on these\n * system-internal deletes. `onEmpty: 'keep'` opts out (rows from\n * prior refreshes linger even when the new result lacks them).\n *\n * **Cost ceiling:** if the materialized row count exceeds\n * `spec.maxRows` (default 100k), throws `MaterializedViewTooLargeError`\n * before any writes hit the store — so strict-mode rollback is\n * clean.\n *\n * **Strict mode:** `spec.strict === true` re-throws on any\n * row-write failure; the active TxContext registration means the\n * source-write rolls back atomically via `revertExecuted`.\n *\n * @internal\n */\nexport const MaterializedViewExecutor = {\n async refresh(\n reg: RegisteredMV,\n accessor: MVExecutorAccessor,\n ): Promise<RefreshResult> {\n const spec = reg.spec\n const outputColl = accessor.getCollection(reg.outputCollection)\n const maxRows = spec.maxRows ?? DEFAULT_MAX_ROWS\n const onEmpty = spec.onEmpty ?? 'delete'\n const strict = spec.strict ?? false\n\n // 1. Materialize the query (branches on terminal shape). If the\n // MV declared predicates, wrap the query context the same way\n // the registry did at registration time so `.wherePredicate()`\n // calls resolve to the registered functions.\n // #1414 — `ungatedMvContext` keeps the engine's synchronous source reads\n // exactly as they were before the cold-collection gate existed.\n const baseCtx = ungatedMvContext(accessor.getQueryContext())\n const ctxForQuery: MVQueryContext = spec.predicates\n ? wrapDbWithPredicates(baseCtx, spec.predicates)\n : baseCtx\n // UNION-form strategies: read every arm, map to the unified\n // row shape, concatenate, then optionally groupBy + aggregate.\n // Projection-form strategies (#810): hydrate the primary source,\n // attach forward + collect legs, map, then the same optional\n // grouping tail. The single-source `query()` path is untouched.\n let rows: ReadonlyArray<Record<string, unknown>>\n if (spec.unionSources) {\n rows = await materializeUnionResult(spec, ctxForQuery)\n } else if (spec.projection) {\n rows = await materializeProjectionResult(spec, ctxForQuery)\n } else {\n const q = spec.query!(ctxForQuery)\n rows = await materializeQueryResult(q, spec.name, spec.i18nLocale, spec.i18nFields)\n }\n\n // #1007 — the post-aggregate projection. Applied here, after every form has\n // produced its finished rows, so union / projection / query all get the\n // same single definition of \"last step before materialisation\".\n if (spec.derive) rows = applyDerive(spec, rows)\n\n // #777 — exclude this MV's OWN previously-stamped output rows from the\n // input scan. A same-collection Query-form MV copies the whole source row\n // verbatim into its output, so a stale output row can itself satisfy the\n // MV's own input filter (when the filter is on a field disjoint from the\n // partition field) and get re-selected as if it were live source — the\n // row self-perpetuates after its true source is gone. Prior output is\n // never this MV's own source.\n rows = rows.filter((row) => {\n const stamp = row._materializedFrom as { mvName?: string } | undefined\n return stamp?.mvName !== spec.name\n })\n\n // 2. Cost ceiling check BEFORE any writes — keeps the rollback\n // clean if the source-write is wrapped in a transaction.\n if (rows.length > maxRows) {\n throw new MaterializedViewTooLargeError(spec.name, rows.length, maxRows)\n }\n\n const txCtx = accessor.getActiveTxContext()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const adapter = (outputColl as any).adapter as {\n get(v: string, c: string, i: string): Promise<EncryptedEnvelope | null>\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const vaultName = (outputColl as any).vault as string\n\n // 3. Compute the post-refresh id set so we can diff against the\n // prior-emitted id set for tombstoning (when onEmpty === 'delete').\n const newIds = new Set<string>()\n const enrichedRows: Array<{ id: string; record: Record<string, unknown> }> = []\n for (const row of rows) {\n const id = spec.rowKey(row)\n newIds.add(id)\n const meta: MaterializedFromMeta = {\n mvName: spec.name,\n queryHash: reg.queryHash,\n sourceVersions: {},\n materializedAt: new Date().toISOString(),\n }\n enrichedRows.push({ id, record: { ...row, _materializedFrom: meta } })\n }\n\n // 4. Write the new rows — skipping any whose content is unchanged (#1418).\n //\n // ⛔ THE OUTPUT ROW COUNT, NOT THE SOURCE SCAN, IS WHAT MADE THIS EXPENSIVE.\n // This loop used to encrypt-and-store EVERY row of the view on EVERY source\n // write, so per-write cost tracked the size of the view: measured 23 ms at\n // 250 output rows and 41.6 ms at 450, for source writes the MV's own `map`\n // dropped entirely. Comparing against what this MV last wrote turns \"one\n // source write rewrites the whole view\" into \"one source write rewrites the\n // groups that moved\". See `emit-memo.ts` for why this, and not a\n // predict-whether-the-refresh-is-needed short circuit.\n const memoKey = emitMemoKey(vaultName, spec.name, reg.outputCollection)\n // Read the stamp BEFORE writing: it has to describe the collection as this\n // refresh found it, so a write by anyone else since last time invalidates.\n const priorEmitted = readEmitMemo(memoKey, outputColl._cacheStamp)\n const emitted = new Map<string, string>()\n\n let written = 0\n let skipped = 0\n let failed = 0\n for (const { id, record } of enrichedRows) {\n const contentKey = rowContentKey(record, reg.queryHash)\n // ⚠️ A txCtx changes what a \"skip\" means: the rollback journal below\n // needs an entry for every row the transaction could revert, and a row we\n // never wrote has nothing to revert TO. Rather than reason about partial\n // journals, the memo stands down inside a transaction entirely.\n // #1439 — and only when no `beforePut` gate can fire FOR THIS ROW. Asking\n // the bus \"is anything registered\" instead disabled the skip for every\n // collection in any vault carrying a guard or a periods strategy —\n // measured by the reporter at 54 redundant writes per source write with\n // guards alone, which is close to every real consumer.\n if (\n contentKey !== null && txCtx === null\n && !outputColl._derivedWriteGated(record)\n && priorEmitted?.get(id) === contentKey\n ) {\n skipped++\n emitted.set(id, contentKey)\n continue\n }\n try {\n if (txCtx !== null) {\n const prior = await adapter.get(vaultName, reg.outputCollection, id)\n txCtx._executed.push({\n op: { type: 'put', vaultName, collectionName: reg.outputCollection, id },\n priorEnvelope: prior,\n })\n }\n let landed = false\n if (accessor.dispatchCtx) {\n if (await putDerivedOutput(outputColl, id, record, accessor.dispatchCtx) === 'written') {\n written++\n landed = true\n }\n } else {\n await outputColl.put(id, record)\n written++\n landed = true\n }\n // ⛔ ONLY a write that actually landed is remembered. `putDerivedOutput`\n // declines inside a frozen period, and recording that row would make\n // every later refresh skip a row that is not there.\n if (landed && contentKey !== null) emitted.set(id, contentKey)\n } catch (err) {\n failed++\n if (strict) throw err\n \n console.warn(`[mv] \"${spec.name}\" row write failed:`, err)\n }\n }\n\n // 5. Tombstone rows that existed before but don't appear now.\n // `onEmpty: 'keep'` skips this pass entirely. Uses\n // `_internalDelete` so a user-registered `onDelete` on the\n // output collection does NOT fire on housekeeping (composition fix).\n let deleted = 0\n const residueUndecodable: string[] = []\n const residueDeclined: string[] = []\n if (onEmpty === 'delete') {\n const priorIds = await listOutputIds(outputColl)\n for (const priorId of priorIds) {\n if (newIds.has(priorId)) continue\n // #762 — a same-collection partition MV (`output: { collection: <source>, partition }`,\n // the DERIV-PP30-001 shape) writes INTO its own source collection, so `listOutputIds`\n // also returns untouched USER source rows here. Decode each candidate and only\n // tombstone rows THIS MV stamped via `_materializedFrom.mvName` — the exact discipline\n // `invalidateMVAtRest` uses (stale.ts:151-162). An unstamped row, or one stamped by a\n // different MV, is never this MV's to delete.\n const priorEnvelope = await adapter.get(vaultName, reg.outputCollection, priorId)\n if (priorEnvelope === null) continue\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const priorDecoded = await (outputColl as any)._decodeEnvelope(priorEnvelope, priorId)\n if (priorDecoded === null) {\n // #782 part a — ownership unknown (undecodable, e.g. elevated above tier 0 on a\n // tiered output collection): can't rule out this being THIS MV's own stamped row.\n // Surface it rather than silently skip (mirrors invalidateMVAtRest's #776 posture —\n // previously this leg had NO residue channel at all).\n residueUndecodable.push(`${reg.outputCollection}:${priorId}`)\n continue\n }\n const priorStampedBy =\n typeof priorDecoded === 'object'\n ? (priorDecoded as Record<string, unknown>)._materializedFrom as { mvName?: string } | undefined\n : undefined\n if (priorStampedBy?.mvName !== spec.name) continue\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const outAny = outputColl as any\n if (typeof outAny._internalDelete === 'function') {\n // #776 part b — gate on the boolean, matching invalidateMVAtRest's discipline\n // (stale.ts): `_internalDelete` returns `false` for a #718 elevated-skip (no\n // erasure happened), and that must not inflate the tombstone count.\n if (await outAny._internalDelete(priorId, txCtx)) {\n deleted++\n } else {\n // #782 part b — decoded AND stamp-owned, but erasure was declined (#718\n // tier-elevation gate). Ownership IS confirmed here — a real silent survival,\n // not a legit stamp-mismatch skip. Surface it too.\n residueDeclined.push(`${reg.outputCollection}:${priorId}`)\n }\n } else {\n // Defensive fallback — should never hit in real flow since\n // every Collection has `_internalDelete`.\n await outputColl.delete(priorId)\n deleted++\n }\n } catch (err) {\n failed++\n if (strict) throw err\n\n console.warn(`[mv] \"${spec.name}\" tombstone failed for id=\"${priorId}\":`, err)\n }\n }\n }\n\n // Record the stamp AFTER every write and tombstone, so the next refresh's\n // check means \"nothing has happened to this collection since I finished\".\n // A row that failed, was declined, or was tombstoned is simply absent from\n // `emitted` and will be written again.\n writeEmitMemo(memoKey, outputColl._cacheStamp, emitted)\n\n return { written, skipped, deleted, failed, residueUndecodable, residueDeclined }\n },\n}\n\n/**\n * List ids currently present in the MV's output collection via the\n * adapter directly (avoids triggering the lazy resolve-on-read path\n * we're INSIDE). Returns an empty array if the collection doesn't\n * exist or the adapter doesn't surface a list method.\n *\n * @internal\n */\nasync function listOutputIds(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputColl: Collection<any>,\n): Promise<string[]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cAny = outputColl as any\n const adapter = cAny.adapter as { list?: (v: string, c: string) => Promise<readonly string[]> }\n const vault = cAny.vault as string\n const name = cAny.name as string\n if (typeof adapter?.list !== 'function') return []\n try {\n const ids = await adapter.list(vault, name)\n return [...ids]\n } catch {\n return []\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,WAAW,GAAqB;AACvC,SAAO,OAAO,MAAM,YAAY,MAAM,QAAS,EAA6B,aAAa;AAC3F;AAWO,SAAS,oBACd,MACA,QACA,aACwC;AACxC,MAAI,KAAK,WAAW,EAAG,QAAO;AAE9B,MAAI,SAA2B,OAAO;AACtC,MAAI,aAAa;AACf,UAAM,eAA0D,CAAC;AACjE,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,GAAG;AAC3C,UAAI,CAAC,WAAW,CAAC,EAAG,cAAa,CAAC,IAAI;AAAA,IACxC;AACA,QAAI,OAAO,KAAK,YAAY,EAAE,SAAS,GAAG;AACxC,YAAM,UAAU,UAAU,OAAO,EAAE,EAAE,YAAY,CAAC;AAClD,UAAI,UAAU,QAAQ,aAAc,YAA0B;AAI9D,gBAAU,qBAAqB,SAAuB;AAAA,QACpD,sBAAsB,CAAC,GAAG,MAAM,QAAQ,uBAAuB,GAAG,CAAC;AAAA,MACrE,CAAC;AACD,eAAS,E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AAEF,gBAAM,SAAS;AACf,cAAI,OAAO,OAAO,oBAAoB,YAAY;AAIhD,gBAAI,MAAM,OAAO,gBAAgB,SAAS,KAAK,GAAG;AAChD;AAAA,YACF,OAAO;AAIL,8BAAgB,KAAK,GAAG,IAAI,gBAAgB,IAAI,OAAO,EAAE;AAAA,YAC3D;AAAA,UACF,OAAO;AAGL,kBAAM,WAAW,OAAO,OAAO;AAC/B;AAAA,UACF;AAAA,QACF,SAAS,KAAK;AACZ;AACA,cAAI,OAAQ,OAAM;AAElB,kBAAQ,KAAK,SAAS,KAAK,IAAI,8BAA8B,OAAO,MAAM,GAAG;AAAA,QAC/E;AAAA,MACF;AAAA,IACF;AAMA,kBAAc,SAAS,WAAW,aAAa,OAAO;AAEtD,WAAO,EAAE,SAAS,SAAS,SAAS,QAAQ,oBAAoB,gBAAgB;AAAA,EAClF;AACF;AAUA,eAAe,cAEb,YACmB;AAEnB,QAAM,OAAO;AACb,QAAM,UAAU,KAAK;AACrB,QAAM,QAAQ,KAAK;AACnB,QAAM,OAAO,KAAK;AAClB,MAAI,OAAO,SAAS,SAAS,WAAY,QAAO,CAAC;AACjD,MAAI;AACF,UAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,IAAI;AAC1C,WAAO,CAAC,GAAG,GAAG;AAAA,EAChB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/via/classified/descriptor.ts","../src/via/classified/errors.ts","../src/via/classified/resolve.ts","../src/via/classified/write.ts","../src/via/classified/guards.ts","../src/via/classified/binding.ts","../src/port/with/classified-strategy.ts"],"sourcesContent":["/**\n * Classified fields — behavioral sensitive-field descriptors (stage 1).\n * Design: design-history/2026-07-04-classified-fields-design.md\n * Law: open on write, declarative on read — read-side behavior is this\n * closed vocabulary; there are no read-side callbacks.\n * @module\n */\n\nexport type ClassifiedStorage = 'recoverable' | 'never' | 'digest-only'\n\nexport type ClassifiedList =\n | { readonly kind: 'omit' }\n | { readonly kind: 'mask'; readonly pattern: string }\n | { readonly kind: 'rider'; readonly rider: string }\n\nexport type ClassifiedRider = (value: unknown) => unknown\n\nexport interface ClassifiedFieldSpec {\n readonly _noydbClassified: true\n /**\n * Via port brand marker — lets a `ClassifiedFieldSpec` satisfy the\n * kernel's opaque `ViaDescriptor` (#629 Task 5). Optional (unlike\n * `MoneyDescriptor._viaBrand`/`I18nTextDescriptor._viaBrand`, which are\n * required): every `classified.*()` preset factory stamps it, but the\n * pre-existing test suite's hand-rolled `ClassifiedFieldSpec` fixtures\n * (built without going through a preset) predate this field and would\n * fail to compile if it were mandatory.\n */\n readonly _viaBrand?: 'classified'\n readonly preset: string\n readonly storage: ClassifiedStorage\n readonly list: ClassifiedList\n readonly sensitivity: 'pii' | 'secret'\n /** Write-time safe projections; companion field name is `<field>_<rider>`. */\n readonly riders?: Record<string, ClassifiedRider>\n /** Write-time validator: error message, or null when valid. */\n readonly validate?: (value: unknown) => string | null\n /** Digest-only verify policy (stage 2). Mode both sides normalize under. */\n readonly verifyNormalize?: 'password' | 'secret-answer'\n /** Decorate ok:true verdicts with mustRotate after this many days (I1). */\n readonly rotateDays?: number\n /** Refuse reuse of the last N values on rotate (cap 8, spec Q4). */\n readonly notLastN?: number\n /** Member of the collection's matchGroup (secretAnswer preset). */\n readonly verifyGroupMember?: true\n /**\n * Opt into a store-visible blind-index (`_bidx`) tag so equal values become\n * queryable/joinable while staying digest-only. Digest-only knob (R7); gated\n * behind the collection's `acknowledgeEquatableRisk` door (R8). Equal values\n * produce equal tags — a partition leak a DEK holder can offline-dictionary\n * at the PBKDF2 floor. Absent/false ⇒ refused-by-default.\n */\n readonly equatable?: true\n}\n\nexport interface ClassifiedGroup {\n readonly _noydbClassifiedGroup: true\n /** Via port brand marker — see {@link ClassifiedFieldSpec._viaBrand}. */\n readonly _viaBrand?: 'classified'\n readonly preset: string\n /** member record-field name -> spec (differential per-member policy). */\n readonly members: Record<string, ClassifiedFieldSpec>\n}\n\nexport type ClassifiedEntry = ClassifiedFieldSpec | ClassifiedGroup\n\nexport function isClassifiedFieldSpec(x: unknown): x is ClassifiedFieldSpec {\n return typeof x === 'object' && x !== null\n && (x as { _noydbClassified?: unknown })._noydbClassified === true\n}\n\nexport function isClassifiedGroup(x: unknown): x is ClassifiedGroup {\n return typeof x === 'object' && x !== null\n && (x as { _noydbClassifiedGroup?: unknown })._noydbClassifiedGroup === true\n}\n","/**\n * Configuration/write errors for classified fields. @module\n *\n * `ClassifiedConfigError` / `ClassifiedRevealError` moved to `kernel/errors.ts`\n * (stage 2) so `kernel/enclave/classify/*` can throw them without importing\n * with-*. Re-exported here under the same names so existing import paths\n * keep working.\n */\nexport { ClassifiedConfigError, ClassifiedRevealError, ClassifiedVerifyError, ClassifiedRotationError } from '../../kernel/errors.js'\n\nexport class ClassifiedNeverStoredError extends Error {\n constructor(public readonly collection: string, public readonly field: string) {\n super(`Field \"${field}\" in collection \"${collection}\" is classified storage:'never' `\n + `(e.g. a CVC) and must not be persisted. Validate it at capture and drop it before put().`)\n this.name = 'ClassifiedNeverStoredError'\n }\n}\n\nexport class ClassifiedValidationError extends Error {\n constructor(public readonly collection: string, public readonly field: string, detail: string) {\n super(`Classified field \"${field}\" in collection \"${collection}\" failed validation: ${detail}`)\n this.name = 'ClassifiedValidationError'\n }\n}\n","/** Flatten a classifiedFields config into a per-field map + rider computed entries. @module */\n\nimport { isClassifiedGroup, type ClassifiedEntry, type ClassifiedFieldSpec } from './descriptor.js'\nimport { ClassifiedConfigError } from './errors.js'\n\nexport type { ClassifiedEntry, ClassifiedFieldSpec, ClassifiedGroup, ClassifiedList } from './descriptor.js'\nexport { ClassifiedConfigError } from './errors.js'\n\nexport interface ResolvedClassified {\n readonly byField: Record<string, ClassifiedFieldSpec>\n readonly riderComputed: Record<string, (record: Record<string, unknown>) => unknown>\n}\n\nexport function resolveClassifiedFields(\n collection: string,\n config: Record<string, ClassifiedEntry>,\n): ResolvedClassified {\n const byField: Record<string, ClassifiedFieldSpec> = {}\n const claim = (field: string, spec: ClassifiedFieldSpec): void => {\n if (byField[field] !== undefined) {\n throw new ClassifiedConfigError(collection,\n `field \"${field}\" is claimed twice — storage forms are mutually exclusive per field (R5): ` +\n `a field is digest-only OR recoverable OR never, exactly one`)\n }\n byField[field] = spec\n }\n for (const [key, entry] of Object.entries(config)) {\n if (isClassifiedGroup(entry)) {\n for (const [field, spec] of Object.entries(entry.members)) claim(field, spec)\n } else {\n claim(key, entry)\n }\n }\n const riderComputed: Record<string, (record: Record<string, unknown>) => unknown> = {}\n for (const [field, spec] of Object.entries(byField)) {\n for (const [name, rider] of Object.entries(spec.riders ?? {})) {\n const companion = `${field}_${name}`\n if (byField[companion] !== undefined || riderComputed[companion] !== undefined) {\n throw new ClassifiedConfigError(collection, `rider companion \"${companion}\" collides with a declared field`)\n }\n riderComputed[companion] = (record) =>\n record[field] === undefined ? undefined : rider(record[field])\n }\n }\n return { byField, riderComputed }\n}\n","/** Write-path enforcement: storage:'never' rejection + preset validators.\n * Runs BEFORE riders/computed and BEFORE schema validation. Pure. @module */\n\nimport type { ClassifiedFieldSpec } from './descriptor.js'\nimport { ClassifiedNeverStoredError, ClassifiedValidationError } from './errors.js'\n\nexport function enforceClassifiedWrite(\n record: Record<string, unknown>,\n byField: Record<string, ClassifiedFieldSpec>,\n collection: string,\n): void {\n for (const [field, spec] of Object.entries(byField)) {\n const value = record[field]\n if (value === undefined) continue\n if (value === null && spec.storage === 'digest-only') continue // explicit clear (C6 branch 3)\n if (spec.storage === 'never') throw new ClassifiedNeverStoredError(collection, field)\n const problem = spec.validate?.(value) ?? null\n if (problem !== null) throw new ClassifiedValidationError(collection, field, problem)\n }\n}\n","/**\n * Refusal matrix R1-R5 (spec) — ONE guard, run at BOTH doors:\n * `collection()` config resolution AND `_applyClassifiedFields` (the reconcile\n * seam), because crdt/conflictPolicy/perRecordKeys are construction-only\n * while classifiedFields can attach later (C5's lesson). @module\n */\nimport type { ClassifiedFieldSpec } from './descriptor.js'\nimport { ClassifiedConfigError } from '../../kernel/errors.js'\n\nexport interface ClassifiedGuardCtx {\n readonly perRecordKeys: boolean\n readonly crdt: boolean\n readonly hasConflictPolicy: boolean\n /** False on plaintext (`encrypt: false`) collections — no vdig/seal path exists. */\n readonly storeCiphertext: boolean\n readonly deterministicFields: ReadonlySet<string> | null\n readonly indexedFields: ReadonlySet<string>\n readonly textIndexFields: ReadonlySet<string>\n readonly vectorSourceFields: ReadonlySet<string>\n readonly subjectKeyField: string | undefined\n readonly bareSensitiveFields: ReadonlySet<string>\n /** Collection-level gate for the `equatable` knob (R8 double door). */\n readonly acknowledgeEquatableRisk: boolean\n}\n\nexport function guardClassifiedCompat(\n collection: string,\n byField: Record<string, ClassifiedFieldSpec>,\n ctx: ClassifiedGuardCtx,\n): void {\n const digestOnly = Object.entries(byField)\n .filter(([, s]) => s.storage === 'digest-only')\n const protectedForms = Object.values(byField)\n .filter((s) => s.storage === 'digest-only' || s.storage === 'recoverable')\n\n // R2 — merge resolvers bypass the write pipeline entirely (C5): a merge\n // could carry stale/foreign _vdig or resurrect plaintext (the CRDT put\n // branch persists via encryptJsonString with no vdig backstop). Fail-loud.\n if (protectedForms.length > 0 && (ctx.crdt || ctx.hasConflictPolicy)) {\n throw new ClassifiedConfigError(collection,\n 'digest-only/recoverable classified fields cannot combine with a crdt mode or a ' +\n 'conflictPolicy resolver — merge paths bypass write enforcement (R2)')\n }\n // R7 — `equatable` is a digest-only knob: it drives the `_bidx` blind-index\n // slot, which only exists on the digest-only write path. A recoverable/never\n // field carrying it would silently no-op (recoverable equality is `_det`'s\n // job). Refuse rather than accept-and-ignore. Checked over ALL specs, before\n // the digest-only early-return below, precisely to catch the non-digest case.\n for (const [f, spec] of Object.entries(byField)) {\n if (spec.equatable === true && spec.storage !== 'digest-only') {\n throw new ClassifiedConfigError(collection,\n `field \"${f}\" declares equatable but storage is '${spec.storage}' — equatable is a ` +\n `digest-only knob; recoverable equality is _det's job (R7)`)\n }\n }\n\n // R8 — the equatable double door (mirrors deterministicFields ×\n // acknowledgeDeterministicRisk): any field opting into `equatable` requires\n // the collection to acknowledge the partition-leak risk. One-directional —\n // `acknowledgeEquatableRisk: true` with ZERO equatable members is a silent\n // no-op (never throws here), so the ack can sit on a collection config\n // ahead of the field landing.\n const hasEquatable = Object.values(byField).some((s) => s.equatable === true)\n if (hasEquatable && ctx.acknowledgeEquatableRisk !== true) {\n throw new ClassifiedConfigError(collection,\n `classified equatable fields require \\`acknowledgeEquatableRisk: true\\` — equal values ` +\n `produce equal store-visible index tags (a partition leak a DEK holder can offline-` +\n `dictionary at the PBKDF2 floor); the door is the real control for low-entropy fields (R8)`)\n }\n\n if (digestOnly.length === 0) return\n\n // Digest-only on a plaintext collection: the codec's vdig block is gated on\n // storeCiphertext, so the secret would persist as raw plaintext. Refuse.\n if (!ctx.storeCiphertext) {\n throw new ClassifiedConfigError(collection,\n `storage:'digest-only' requires an encrypted collection — with encrypt: false the ` +\n `write path skips the digest slot entirely and the secret would persist as raw plaintext`)\n }\n // R1 — vdig slot keys are CEK-only (I3); without perRecordKeys a digest\n // would survive forget() in backups as offline-crackable material.\n if (!ctx.perRecordKeys) {\n throw new ClassifiedConfigError(collection,\n `storage:'digest-only' requires perRecordKeys: true — vdig keys derive from the ` +\n `per-record CEK so forget() shreds them (R1)`)\n }\n for (const [f, spec] of digestOnly) {\n // notLastN cap: presets clamp this at construction, but a raw spec object\n // bypasses the preset — enforce the same 0..8 cap in the policy projection.\n const n = spec.notLastN ?? 0\n if (!Number.isInteger(n) || n < 0 || n > 8) {\n throw new ClassifiedConfigError(collection,\n `digest-only field \"${f}\" declares notLastN ${n} — must be an integer 0..8 ` +\n `(write cost is n × 600K PBKDF2; ring blast radius is documented)`)\n }\n if (ctx.bareSensitiveFields.has(f)) {\n // R5 — the sealed block runs before the vdig block in the codec, so the\n // overlap would seal the value recoverably (silent downgrade + I4\n // double-slot). Storage forms are mutually exclusive per field.\n throw new ClassifiedConfigError(collection,\n `field \"${f}\" is digest-only AND listed in sensitive[] — storage forms are mutually exclusive per field (R5)`)\n }\n if (ctx.deterministicFields?.has(f)) {\n throw new ClassifiedConfigError(collection,\n `digest-only field \"${f}\" cannot be deterministic — equality-correlatable ciphertext defeats per-write salts (R3)`)\n }\n if (ctx.indexedFields.has(f) || ctx.textIndexFields.has(f)\n || ctx.vectorSourceFields.has(f) || ctx.subjectKeyField === f) {\n throw new ClassifiedConfigError(collection,\n `digest-only field \"${f}\" cannot be indexed, text-indexed, embedded, or a forget-subject key (R4)`)\n }\n }\n}\n","/**\n * The classified `NoydbVia` (#629 Task 5, LIVE since Task 6) — wires\n * classified-fields declaration/write-enforcement/at-rest sealing/erasure\n * into the kernel's generic Via port. Mirrors `via/money/binding.ts`'s\n * inline declaration-time validation and `via/i18n/binding.ts`'s\n * `linkXVia` static-link pattern — except the link itself is EAGER\n * (`port/with/classified-strategy.ts` calls `linkClassifiedVia()` at module\n * load, not lazily from a `classified.*()` preset call): several fixtures\n * build a raw `ClassifiedFieldSpec` literal without ever calling a preset,\n * and the binder must be installed before `compileVias` needs it\n * regardless.\n *\n * `compileVias` (`kernel/collection-config.ts`) compiles this binding\n * in whenever a collection declares `classifiedFields` — money then i18n\n * then classified, order pinned. `kernel/collection.ts`'s `_putInternal`\n * runs `enforceClassifiedWrite`'s effect via the pipeline's `enforceWrite`\n * phase; the codec's `encodeAtRest`/`decodeAtRest` hooks (Task 3's boundary)\n * replace the inline `sensitiveFields` seal path for any collection this\n * binding is compiled into.\n *\n * `declare` — `classifiedVia(cfg)` runs `resolveClassifiedFields` +\n * `guardClassifiedCompat` at CONSTRUCTION time (the same #553 pattern\n * `moneyVia`'s `validateMoneyFieldPaths(moneyFields)` call uses) —\n * mirrors today's \"door 1\" (`collection-config.ts`'s\n * `resolveCollectionConfig`). Both may throw `ClassifiedConfigError`.\n */\nimport type { NoydbVia, ViaWriteCtx, ViaCryptoCtx, SealedSlotRef, ViaEraseCtx, ViaEraseReport } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport { SealedHandle } from '../../kernel/types.js'\nimport { resolveClassifiedFields, type ClassifiedEntry } from './resolve.js'\nimport { guardClassifiedCompat, type ClassifiedGuardCtx } from './guards.js'\nimport { enforceClassifiedWrite } from './write.js'\nimport type { ClassifiedFieldSpec } from './descriptor.js'\n\n/**\n * One classified per-slot shred/residue verdict — mirrors\n * `RecordCodec.SealedShredSlot` (`kernel/enclave/record-keys/record-codec.ts`)\n * byte-for-byte. Duplicated here (not imported) so this binding never\n * reaches into `kernel/enclave/` (`via-enclave-isolation`, #629) — the\n * closure that PRODUCES real values of this shape is codec-owned and\n * injected via {@link ClassifiedViaConfig.classifySealedShred}.\n */\nexport interface ClassifiedShredSlot {\n readonly field: string\n readonly class: 'shreddable' | 'dekResidue' | 'live-shreddable+dekResidue-in-backups'\n}\n\n/**\n * Config a classified collection's declarations resolve to — the binding's\n * construction input. `entries`/`guardCtx` are the raw \"door 1\" inputs\n * (`resolveClassifiedFields`/`guardClassifiedCompat`'s own parameters);\n * `classifySealedShred`/`purgeSealedCekEnvelopes` are OPTIONAL codec/vault-\n * provided closures for the `erase` hook — undefined in this dormant task\n * (no caller wires them yet), wired for real in #629 Task 10 (\"posture\n * enforcement — forget + erase hooks live\").\n */\nexport interface ClassifiedViaConfig {\n readonly entries: Record<string, ClassifiedEntry>\n readonly collectionName: string\n readonly guardCtx: ClassifiedGuardCtx\n /**\n * Codec-provided closure mirroring `RecordCodec.classifySealedShred` —\n * classifies a live envelope's `_sealed` slots for crypto-shred\n * completeness (see that method's doc comment for the shreddable/\n * dekResidue/both-class semantics). `live` is `ViaEraseCtx.live`'s opaque\n * envelope, passed straight through. NOT `readonly` (#629 Task 10):\n * `compileVias` builds this cfg before the owning `Collection`'s\n * `RecordCodec` exists, so `Collection`'s constructor mutates this field\n * in place once `this.codec` is available — the closure `eraseClassified`\n * reads is looked up at CALL time, not at binding-construction time, so\n * the late assignment is picked up correctly.\n */\n classifySealedShred?: (live: unknown) => Promise<{ readonly slots: readonly ClassifiedShredSlot[] }>\n /**\n * Vault-provided closure that purges every `_sealed_cek/<collection>/<id>/*`\n * host-delivery envelope for one record (mirrors `rotateRecordCek`'s own\n * prefix-delete) and returns the count purged. Deliberately left UNWIRED\n * by `compileVias` (#629 Task 10) — `forget-sealed-erasure.test.ts`\n * proves this purge is UNCONDITIONAL on `sealRecordToHost` usage alone,\n * independent of whether `classifiedFields` is declared (a bare\n * `sensitive: [...]` collection exercises it with no classified binding\n * at all) — vault.ts keeps owning it directly so that case stays correct.\n */\n readonly purgeSealedCekEnvelopes?: (id: string) => Promise<number>\n}\n\n/** Fields declared `storage: 'recoverable'` (digest-only stays codec-inline; `'never'` is rejected by `enforceWrite` before either hook runs). */\nfunction recoverableFields(byField: Record<string, ClassifiedFieldSpec>): string[] {\n return Object.entries(byField).filter(([, spec]) => spec.storage === 'recoverable').map(([field]) => field)\n}\n\n/**\n * The full set this binding's `encodeAtRest`/`decodeAtRest` seal: declared\n * recoverable classified fields UNION bare `sensitive[]` fields — mirrors\n * `collection-config.ts`'s pre-cutover \"recoverable classified fields are\n * unioned into sensitiveFields... zero new crypto code\" semantics. Once this\n * binding is compiled into a collection's pipeline, `hasAtRestHooks` is true\n * and the codec's inline `sensitiveFields` seal path (record-codec.ts) is\n * DEAD for that collection — mutually exclusive with the hook path (#629\n * Task 3) — so bare `sensitive[]` fields MUST seal through here too, or\n * they'd silently stop being sealed at all (#629 Task 6 reconciliation).\n * `guardCtx.bareSensitiveFields` is the exact same `Set` the collection's\n * refusal-matrix guard already carries (`ClassifiedGuardCtx`).\n */\nfunction sealFieldNames(byField: Record<string, ClassifiedFieldSpec>, guardCtx: ClassifiedGuardCtx): string[] {\n return [...recoverableFields(byField), ...guardCtx.bareSensitiveFields]\n}\n\n/**\n * Seal every named field present with a defined value into its own sealed\n * slot via `crypto.sealedSlots`, peeling it out of the record.\n */\nasync function encodeClassifiedAtRest(\n record: Record<string, unknown>,\n crypto: ViaCryptoCtx,\n fields: readonly string[],\n): Promise<{ record: Record<string, unknown>; sealed?: Record<string, SealedSlotRef> }> {\n let open = record\n let sealed: Record<string, SealedSlotRef> | undefined\n for (const field of fields) {\n if (!(field in record)) continue\n const value = record[field]\n if (value === undefined) continue\n const ref = await crypto.sealedSlots.seal(field, value)\n if (open === record) open = { ...record }\n delete open[field]\n sealed ??= {}\n sealed[field] = ref\n }\n return sealed ? { record: open, sealed } : { record }\n}\n\n/**\n * Restore every named field's sealed slot back onto the record: an opaque\n * `SealedHandle` under `asHandles` (never materialises plaintext into the\n * cache — `SealedHandle.toJSON()` returns `'[sealed]'`, the export-redaction\n * guarantee `reveal()` alone can lift), the plaintext value otherwise.\n */\nasync function decodeClassifiedAtRest(\n record: Record<string, unknown>,\n sealed: Record<string, SealedSlotRef>,\n crypto: ViaCryptoCtx,\n opts: { asHandles: boolean },\n fields: readonly string[],\n): Promise<Record<string, unknown>> {\n let out = record\n for (const field of fields) {\n const ref = sealed[field]\n if (ref === undefined) continue\n if (out === record) out = { ...record }\n out[field] = opts.asHandles\n ? new SealedHandle(() => crypto.sealedSlots.unseal(field, ref))\n : await crypto.sealedSlots.unseal(field, ref)\n }\n return out\n}\n\n/**\n * `forget()`'s per-ref erasure participation: classify the live envelope's\n * sealed slots (via the codec-provided closure) and mark each shreddable\n * one deleted on this call's sealed-slots capability, then purge the\n * record's sealed-CEK host-delivery envelopes (via the vault-provided\n * closure). Both closures are optional — undefined (this dormant task's\n * only caller, its own unit tests) reports a zero-shredded, zero-residue\n * no-op rather than throwing.\n */\nasync function eraseClassified(\n ctx: ViaEraseCtx,\n cfg: ClassifiedViaConfig,\n): Promise<ViaEraseReport> {\n let shredded = 0\n const residue: unknown[] = []\n\n if (cfg.classifySealedShred) {\n const { slots } = await cfg.classifySealedShred(ctx.live)\n for (const slot of slots) {\n if (slot.class === 'shreddable' || slot.class === 'live-shreddable+dekResidue-in-backups') {\n shredded += 1\n await ctx.crypto.sealedSlots.delete(slot.field)\n }\n if (slot.class === 'dekResidue' || slot.class === 'live-shreddable+dekResidue-in-backups') {\n residue.push({ kind: 'classified-sealed-dek-residue', field: slot.field })\n }\n }\n }\n\n if (cfg.purgeSealedCekEnvelopes) {\n shredded += await cfg.purgeSealedCekEnvelopes(ctx.id)\n }\n\n return { shredded, residue }\n}\n\nfunction buildClassifiedDescribeFragment(byField: Record<string, ClassifiedFieldSpec>): Record<string, unknown> {\n return {\n classifiedFields: Object.fromEntries(\n Object.entries(byField).map(([field, spec]) => [field, { storage: spec.storage, sensitivity: spec.sensitivity }]),\n ),\n }\n}\n\nexport function classifiedVia(cfg: ClassifiedViaConfig): NoydbVia {\n // declare — door 1: resolve + guard, exactly like collection-config.ts's\n // resolveCollectionConfig does today. Throws ClassifiedConfigError on any\n // R1-R8 refusal-matrix violation or field-collision.\n const resolved = resolveClassifiedFields(cfg.collectionName, cfg.entries)\n guardClassifiedCompat(cfg.collectionName, resolved.byField, cfg.guardCtx)\n const byField = resolved.byField\n const sealFields = sealFieldNames(byField, cfg.guardCtx)\n\n return {\n brand: 'classified',\n posture: { encryptedAtRest: 'sealed', queryable: 'det-exact', exportable: false, forgettable: true },\n covers: (field) => field in byField,\n coveredFields: Object.keys(byField), // #1447 — the FIELD only; the sensitivity label is deliberately NOT reported\n // async (rather than a bare passthrough) so a refusal is always a\n // rejected Promise for direct callers, matching every other async-stack\n // hook's calling convention — `enforceClassifiedWrite` itself stays sync.\n enforceWrite: async (record: Record<string, unknown>, _ctx: ViaWriteCtx) =>\n enforceClassifiedWrite(record, byField, cfg.collectionName),\n encodeAtRest: (record, crypto) => encodeClassifiedAtRest(record, crypto, sealFields),\n decodeAtRest: (record, sealed, crypto, opts) => decodeClassifiedAtRest(record, sealed, crypto, opts, sealFields),\n erase: (ctx) => eraseClassified(ctx, cfg),\n describeFragment: () => buildClassifiedDescribeFragment(byField),\n }\n}\n\nexport function linkClassifiedVia(): void {\n installViaBinder('classified', (c) => classifiedVia(c as ClassifiedViaConfig))\n}\n","/**\n * Classified strategy seam (#629 Task 5 — moved out of\n * `via/classified/strategy.ts`, precedent: `port/with/i18n-strategy.ts`).\n * Lives on the `/with` port (the one seam the kernel spine may import\n * statically) so `Collection`/`Vault` can hold the `NO_CLASSIFIED` default\n * without a spine→service static import.\n *\n * This file (unlike `via/classified/**`) is NOT subject to the\n * `via-enclave-isolation` architecture guard — it may import `EnclaveKey`\n * from the enclave barrel freely, the same way `port/with/i18n-strategy.ts`\n * did before #629 Task 4's DictionaryHandle cutover.\n *\n * The ② capability seam for classified read-egress ops (stage 1: reveal;\n * stage 2: verify).\n *\n * @internal\n */\nimport type { ClassifiedFieldSpec } from '../../via/classified/descriptor.js'\nimport { ClassifiedNotEnabledError } from '../../kernel/errors.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\nimport { linkClassifiedVia } from '../../via/classified/binding.js'\n\n// #629 Task 10 — re-export the classified binding's erase-cfg TYPE (not\n// `via/classified/binding.js` directly) so the kernel spine can name\n// it for the post-construction `classifySealedShred` wiring, same rationale\n// as `resolveClassifiedFields`/`guardClassifiedCompat` above.\nexport type { ClassifiedViaConfig } from '../../via/classified/binding.js'\n\nexport type { ClassifiedVerdict } from '../../kernel/types.js'\nimport type { ClassifiedVerdict } from '../../kernel/types.js'\n\n// #629 Task 6 — the classified binding's construction-time resolve/guard,\n// re-exported here (not `via/classified/{resolve,guards}.js` directly)\n// so the kernel spine keeps importing only this one `/with` port seam, same\n// rationale as `NO_CLASSIFIED` below.\nexport { resolveClassifiedFields, type ClassifiedEntry, type ResolvedClassified } from '../../via/classified/resolve.js'\nexport { guardClassifiedCompat, type ClassifiedGuardCtx } from '../../via/classified/guards.js'\nexport type { ClassifiedFieldSpec }\n\n// Install the classified Via binder EAGERLY — unlike money()/i18nText(),\n// several classified fixtures (both hub tests and consumer code) build a raw\n// `ClassifiedFieldSpec` object literal without ever calling a\n// `classified.*()` preset (bypassing `via/classified/presets.ts`\n// entirely — an intentionally supported pattern, see that module's Task 5\n// doc comment). Linking lazily at preset-call time (the money/i18n pattern)\n// would leave `viaBinder('classified')` unlinked for those declarations.\n// This port module is already unconditionally imported by the kernel spine\n// (for the `NO_CLASSIFIED` strategy default below), so linking here\n// guarantees the binder is always installed before `compileVias`\n// ever needs it, regardless of how a collection's classifiedFields were\n// constructed.\nlinkClassifiedVia()\n\nexport interface ClassifiedRevealCtx {\n readonly collection: string\n readonly spec: ClassifiedFieldSpec\n /** True on an encrypted collection — false selects the plaintext-body read. */\n readonly encrypted: boolean\n readonly getEnvelope: (id: string) => Promise<EncryptedEnvelope | null>\n readonly resolveCek: (env: EncryptedEnvelope) => Promise<EnclaveKey | undefined>\n readonly getDEK: () => Promise<EnclaveKey>\n readonly onAccess?: ((op: 'reveal', id: string) => Promise<void>) | undefined\n}\n\nexport interface ClassifiedVerifyCtx {\n readonly collection: string\n readonly spec: ClassifiedFieldSpec\n readonly getEnvelope: (id: string) => Promise<EncryptedEnvelope | null> // raw envelope, NOT a decrypted view\n readonly resolveCek: (env: EncryptedEnvelope) => Promise<EnclaveKey | undefined>\n readonly getDEK: () => Promise<EnclaveKey>\n readonly now: () => number // injected (Q7)\n /** Group members resolved by the collection (matchGroup only). */\n readonly groupMembers?: ReadonlyArray<{ readonly field: string; readonly spec: ClassifiedFieldSpec }>\n readonly onAccess?: ((op: 'verify' | 'find', id: string) => Promise<void>) | undefined\n}\n\nexport interface ClassifiedStrategy {\n reveal(ctx: ClassifiedRevealCtx, id: string, field: string): Promise<unknown>\n verify(ctx: ClassifiedVerifyCtx, id: string, field: string, candidate: string): Promise<ClassifiedVerdict>\n verifyText(ctx: ClassifiedVerifyCtx, id: string, field: string, candidate: string): Promise<ClassifiedVerdict>\n matchGroup(ctx: ClassifiedVerifyCtx, id: string, answers: Record<string, string>,\n opts: { readonly min: number }): Promise<{ readonly passed: boolean }>\n computeTarget(ctx: ClassifiedVerifyCtx, field: string, candidate: string, costByte?: number): Promise<string | null>\n}\n\nexport const NO_CLASSIFIED: ClassifiedStrategy = {\n async reveal() { throw new ClassifiedNotEnabledError() },\n async verify() { throw new ClassifiedNotEnabledError() },\n async verifyText() { throw new ClassifiedNotEnabledError() },\n async matchGroup() { throw new ClassifiedNotEnabledError() },\n async computeTarget() { throw new ClassifiedNotEnabledError() },\n}\n"],"mappings":";;;;;;;;;;;;AAkEO,SAAS,sBAAsB,GAAsC;AAC1E,SAAO,OAAO,MAAM,YAAY,MAAM,QAChC,EAAqC,qBAAqB;AAClE;AAEO,SAAS,kBAAkB,GAAkC;AAClE,SAAO,OAAO,MAAM,YAAY,MAAM,QAChC,EAA0C,0BAA0B;AAC5E;;;AChEO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAA4B,YAAoC,OAAe;AAC7E,UAAM,UAAU,KAAK,oBAAoB,UAAU,0HAC2C;AAFpE;AAAoC;AAG9D,SAAK,OAAO;AAAA,EACd;AAAA,EAJ4B;AAAA,EAAoC;AAKlE;AAEO,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,YAA4B,YAAoC,OAAe,QAAgB;AAC7F,UAAM,qBAAqB,KAAK,oBAAoB,UAAU,wBAAwB,MAAM,EAAE;AADpE;AAAoC;AAE9D,SAAK,OAAO;AAAA,EACd;AAAA,EAH4B;AAAA,EAAoC;AAIlE;;;ACVO,SAAS,wBACd,YACA,QACoB;AACpB,QAAM,UAA+C,CAAC;AACtD,QAAM,QAAQ,CAAC,OAAe,SAAoC;AAChE,QAAI,QAAQ,KAAK,MAAM,QAAW;AAChC,YAAM,IAAI;AAAA,QAAsB;AAAA,QAC9B,UAAU,KAAK;AAAA,MAC8C;AAAA,IACjE;AACA,YAAQ,KAAK,IAAI;AAAA,EACnB;AACA,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,kBAAkB,KAAK,GAAG;AAC5B,iBAAW,CAAC,OAAO,IAAI,KAAK,OAAO,QAAQ,MAAM,OAAO,EAAG,OAAM,OAAO,IAAI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AAAA;AAAA;AAAA;AAAA,IAIlC,cAAc,OAAO,QAAiC,SACpD,uBAAuB,QAAQ,SAAS,IAAI,cAAc;AAAA,IAC5D,cAAc,CAAC,QAAQ,WAAW,uBAAuB,QAAQ,QAAQ,UAAU;AAAA,IACnF,cAAc,CAAC,QAAQ,QAAQ,QAAQ,SAAS,uBAAuB,QAAQ,QAAQ,QAAQ,MAAM,UAAU;AAAA,IAC/G,OAAO,CAAC,QAAQ,gBAAgB,KAAK,GAAG;AAAA,IACxC,kBAAkB,MAAM,gCAAgC,OAAO;AAAA,EACjE;AACF;AAEO,SAAS,oBAA0B;AACxC,mBAAiB,cAAc,CAAC,MAAM,cAAc,CAAwB,CAAC;AAC/E;;;ACjLA,kBAAkB;AAkCX,IAAM,gBAAoC;AAAA,EAC/C,MAAM,SAAS;AAAE,UAAM,IAAI,0BAA0B;AAAA,EAAE;AAAA,EACvD,MAAM,SAAS;AAAE,UAAM,IAAI,0BAA0B;AAAA,EAAE;AAAA,EACvD,MAAM,aAAa;AAAE,UAAM,IAAI,0BAA0B;AAAA,EAAE;AAAA,EAC3D,MAAM,aAAa;AAAE,UAAM,IAAI,0BAA0B;AAAA,EAAE;AAAA,EAC3D,MAAM,gBAAgB;AAAE,UAAM,IAAI,0BAA0B;AAAA,EAAE;AAChE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-audit/attestation/signer.ts"],"sourcesContent":["import type { NoydbStore } from '../../kernel/types.js'\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ConflictError } from '../../kernel/errors.js'\nimport { generateDocSigningKeyPair } from '@noy-db/attestation'\n\nexport const ATTESTATIONS_COLLECTION = '_attestations'\nexport const SIGNER_RECORD_ID = '_signer'\nexport const REVOKED_RECORD_ID = '_revoked'\n\nexport interface DocSigner {\n readonly keyId: string\n readonly publicKeyB64: string\n readonly privateKeyPkcs8B64: string\n}\n\n/**\n * Pure read: return the firm's persisted document-signing keypair, or `null`\n * if none has been minted yet. Never writes — callers that must NOT mint\n * (e.g. an ungated public-key getter) use this instead of `loadOrCreateSigner`.\n *\n * Stored as an encrypted record `_attestations/_signer` under the\n * `_attestations` collection DEK (resolved via `getDEK`, which is\n * AES-KW-wrapped under the owner KEK + persisted by the keyring). The KEK\n * itself is AES-KW-only and cannot AES-GCM-encrypt these bytes — hence\n * storage under a normal collection DEK.\n */\nexport async function loadSigner(\n store: NoydbStore,\n vault: string,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<DocSigner | null> {\n const existing = await store.get(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID)\n if (!existing) return null\n const dek = await getDEK(ATTESTATIONS_COLLECTION)\n const json = await openEnvelopeJson({ collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID }, existing, dek)\n return JSON.parse(json) as DocSigner\n}\n\n/**\n * Lazily mint (or load) the firm's Ed25519 document-signing keypair.\n *\n * On a concurrent first-mint, two callers can both read `null` and both mint\n * distinct keypairs. The `put(…, expectedVersion: 0)` (\"must not already\n * exist\") lets exactly one win; the loser catches `ConflictError`, re-reads,\n * and returns the winner's signer — converging on a single keypair rather than\n * clobbering it or surfacing a raw conflict. (All real stores treat a missing\n * record + `ev: 0` as a no-conflict write, so the catch fires on lost-race only.)\n */\nexport async function loadOrCreateSigner(\n store: NoydbStore,\n vault: string,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<DocSigner> {\n const existing = await loadSigner(store, vault, getDEK)\n if (existing) return existing\n\n const dek = await getDEK(ATTESTATIONS_COLLECTION)\n const signer = await generateDocSigningKeyPair()\n const identity = { collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID, version: 1 }\n const { iv, data } = await encrypt(JSON.stringify(signer), dek, buildRecordAad(identity))\n const env = buildRecordEnvelope(\n identity,\n { iv, data },\n )\n try {\n await store.put(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID, env, 0)\n return signer\n } catch (e) {\n if (!(e instanceof ConflictError)) throw e\n // Lost the race — another writer minted first. Adopt the winner.\n const winner = await loadSigner(store, vault, getDEK)\n if (!winner) {\n throw new ConflictError(0, 'loadOrCreateSigner: signer mint lost a concurrent race but the winning record could not be re-read.')\n }\n return winner\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,SAAS,iCAAiC;AAEnC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAmBjC,eAAsB,WACpB,OACA,OACA,QAC2B;AAC3B,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,yBAAyB,gBAAgB;AACjF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,MAAM,MAAM,OAAO,uBAAuB;AAChD,QAAM,OAAO,MAAM,iBAAiB,EAAE,YAAY,yBAAyB,IAAI,iBAAiB,GAAG,UAAU,GAAG;AAChH,SAAO,KAAK,MAAM,IAAI;AACxB;AAYA,eAAsB,mBACpB,OACA,OACA,QACoB;AACpB,QAAM,WAAW,MAAM,WAAW,OAAO,OAAO,MAAM;AACtD,MAAI,SAAU,QAAO;AAErB,QAAM,MAAM,MAAM,OAAO,uBAAuB;AAChD,QAAM,SAAS,MAAM,0BAA0B;AAC/C,QAAM,WAAW,EAAE,YAAY,yBAAyB,IAAI,kBAAkB,SAAS,EAAE;AACzF,QAAM,EAAE,IAAI,KAAK,IAAI,MAAM,QAAQ,KAAK,UAAU,MAAM,GAAG,KAAK,eAAe,QAAQ,CAAC;AACxF,QAAM,MAAM;AAAA,IACV;AAAA,IACA,EAAE,IAAI,KAAK;AAAA,EACb;AACA,MAAI;AACF,UAAM,MAAM,IAAI,OAAO,yBAAyB,kBAAkB,KAAK,CAAC;AACxE,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,EAAE,aAAa,eAAgB,OAAM;AAEzC,UAAM,SAAS,MAAM,WAAW,OAAO,OAAO,MAAM;AACpD,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,cAAc,GAAG,qGAAqG;AAAA,IAClI;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-commit/history/history.ts","../src/with-commit/history/strategy.ts"],"sourcesContent":["import { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport type { RecordIdentity } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope, HistoryOptions, PruneOptions } from '../../kernel/types.js'\nimport { isTombstone, isTombstoneShape, rewrapEnvelope, isRewrappedUnder, type EnclaveKey } from '../../kernel/enclave/index.js'\n\n/**\n * History storage convention:\n * Collection: `_history`\n * ID format: `{collection}:{recordId}:{paddedVersion}`\n * Version is zero-padded to 10 digits for lexicographic sorting.\n */\n\nconst HISTORY_COLLECTION = '_history'\nconst VERSION_PAD = 10\n\nfunction historyId(collection: string, recordId: string, version: number): string {\n return `${collection}:${recordId}:${String(version).padStart(VERSION_PAD, '0')}`\n}\n\n/**\n * The identity a history snapshot is **sealed against** — its STORAGE location,\n * not the live record it is a copy of (#1041).\n *\n * ## Why storage, and why this is a decision rather than a detail\n *\n * A snapshot is a copy, so two identities are available: the live record\n * (`collection`/`recordId`) or where the bytes actually land\n * (`_history`/`historyId(...)`). They are not equivalent under attack.\n *\n * Binding the LIVE identity makes a snapshot's AAD **indistinguishable from the\n * live record's at the same version** — so an untrusted store could serve a\n * history entry *as the current record* and the client would accept it. It also\n * leaves entries relocatable within `_history`.\n *\n * Binding STORAGE identity closes both. The cost is that the id must be known\n * *before* the envelope is sealed, where `saveHistory` previously derived it\n * *after* (from `envelope._v`) — which is precisely the restructure this\n * function exists to make possible.\n *\n * `saveHistory` uses this too, so the sealed identity and the put location have\n * **one definition** and cannot drift apart. Changing the layout here changes\n * both at once, by construction.\n */\nexport function historyIdentity(collection: string, recordId: string, version: number): RecordIdentity {\n // The snapshot's own `_v` IS the version it preserves — the same number that\n // appears in its id. One argument feeds both, so they cannot disagree (#1093).\n return { collection: HISTORY_COLLECTION, id: historyId(collection, recordId, version), version }\n}\n\n// Unused today, kept for future history-id parsing utilities.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseHistoryId(id: string): { collection: string; recordId: string; version: number } | null {\n const lastColon = id.lastIndexOf(':')\n if (lastColon < 0) return null\n const versionStr = id.slice(lastColon + 1)\n const rest = id.slice(0, lastColon)\n const firstColon = rest.indexOf(':')\n if (firstColon < 0) return null\n return {\n collection: rest.slice(0, firstColon),\n recordId: rest.slice(firstColon + 1),\n version: parseInt(versionStr, 10),\n }\n}\n\nfunction matchesPrefix(id: string, collection: string, recordId?: string): boolean {\n if (recordId) {\n return id.startsWith(`${collection}:${recordId}:`)\n }\n return id.startsWith(`${collection}:`)\n}\n\n/** Save a history entry (a complete encrypted envelope snapshot). */\nexport async function saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n): Promise<void> {\n // Same derivation the caller sealed against — one definition, so the sealed\n // identity and the put location cannot drift (#1041).\n const { id } = historyIdentity(collection, recordId, envelope._v)\n await adapter.put(vault, HISTORY_COLLECTION, id, envelope)\n}\n\n/** Get history entries for a record, sorted newest-first. */\nexport async function getHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n): Promise<EncryptedEnvelope[]> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => matchesPrefix(id, collection, recordId))\n .sort()\n .reverse() // newest first\n\n const entries: EncryptedEnvelope[] = []\n\n for (const id of matchingIds) {\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!envelope) continue\n\n // Apply time filters\n if (options?.from && envelope._ts < options.from) continue\n if (options?.to && envelope._ts > options.to) continue\n\n entries.push(envelope)\n\n if (options?.limit && entries.length >= options.limit) break\n }\n\n return entries\n}\n\n/** Get a specific version's envelope from history. */\nexport async function getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n): Promise<EncryptedEnvelope | null> {\n const id = historyId(collection, recordId, version)\n return adapter.get(vault, HISTORY_COLLECTION, id)\n}\n\n/** Prune history entries. Returns the number of entries deleted. */\nexport async function pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => recordId ? matchesPrefix(id, collection, recordId) : matchesPrefix(id, collection))\n .sort()\n\n let toDelete: string[] = []\n\n if (options.keepVersions !== undefined) {\n // Keep only the N most recent, delete the rest\n const keep = options.keepVersions\n if (matchingIds.length > keep) {\n toDelete = matchingIds.slice(0, matchingIds.length - keep)\n }\n }\n\n if (options.beforeDate) {\n // Delete entries older than the specified date\n for (const id of matchingIds) {\n if (toDelete.includes(id)) continue\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (envelope && envelope._ts < options.beforeDate) {\n toDelete.push(id)\n }\n }\n }\n\n // Deduplicate\n const uniqueDeletes = [...new Set(toDelete)]\n\n for (const id of uniqueDeletes) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return uniqueDeletes.length\n}\n\n/** Clear all history for a vault, optionally scoped to a collection or record. */\nexport async function clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n let toDelete: string[]\n\n if (collection && recordId) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection, recordId))\n } else if (collection) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection))\n } else {\n toDelete = allIds\n }\n\n for (const id of toDelete) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return toDelete.length\n}\n\n/**\n * Crypto-shred every `_history` version of a record. Each non-tombstone\n * history envelope is OVERWRITTEN in place with a tombstone\n * `{ _noydb, _v, _ts: now, _by: actor, _iv: '', _data: '' }` — dropping\n * `_iv`/`_data`/`_cek`/`_det`, so the prior ciphertext (and the wrapped CEK\n * that could decrypt it) is gone everywhere this store reaches. The version\n * counter (`_v`) is preserved so the audit trail still shows \"N versions\n * existed and were erased.\"\n *\n * Overwrite — NOT delete — so the history key itself survives as proof the\n * version existed. Already-tombstoned versions (re-run / idempotent forget)\n * are left untouched and not counted.\n *\n * Returns the number of history versions newly tombstoned.\n */\nexport async function tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds.filter(id => matchesPrefix(id, collection, recordId))\n\n const now = new Date().toISOString()\n let count = 0\n for (const id of matchingIds) {\n const env = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!env) continue\n // Already a tombstone (no body and no wrapped CEK)? Skip — idempotent.\n if (isTombstone(env, encrypted)) continue\n // `by` rides on the IDENTITY — passing it in the body went through a\n // conditional spread, which TypeScript does not excess-property-check, so\n // it was silently dropped once `_by` moved to the identity (#1041).\n const tombstone: EncryptedEnvelope = buildRecordEnvelope(\n { collection: HISTORY_COLLECTION, id, ...(actor ? { by: actor } : {}), version: env._v },\n { ts: now, iv: '', data: '' },\n )\n await adapter.put(vault, HISTORY_COLLECTION, id, tombstone)\n count++\n }\n return count\n}\n\n/**\n * Re-key every `_history` snapshot of a record from `fromDek` to `toDek`.\n * Mirrors what `rewrapBodyToDek` already does for a record's LIVE body on a\n * tier move (elevate/demote/putAtTier) — each `_history` envelope also\n * carries its own `_cek`, wrapped under the collection's tier-0 DEK at write\n * time (`record-codec.ts`), so a tier move that rewraps only the live\n * envelope leaves prior versions decryptable at rest under the tier the\n * record left. This is defense-in-depth *beneath* the read-gate\n * (`history()`/`getVersion()` already return empty for an elevated record;\n * this protects the ciphertext even if that gate is bypassed).\n *\n * Rewraps content in place — unlike `tombstoneHistory`, it does NOT blank\n * `_iv`/`_data`/`_cek` — so a subsequent `demote()` restores tier-0\n * readability. Tombstone-shaped entries (a forgotten/shredded version —\n * blanked `_data`, no `_cek`) are skipped: there is no key material left to\n * rewrap.\n *\n * **Legacy fallback.** A snapshot written before this fix stays wrapped\n * under the tier-0 DEK even after its live record has since moved tiers, so\n * a rewrap attempted with a tier-N `fromDek` fails to unwrap/decrypt. When\n * the caller supplies `tier0Dek`, a failed rewrap is retried once with\n * `tier0Dek` as `fromDek` (the only other key a pre-fix snapshot can be\n * wrapped under — history is written only by tier-0 `put()`). The output is\n * always wrapped under `toDek` regardless of which `fromDek` succeeded. A\n * rewrap that fails under BOTH keys re-throws — that is real corruption, not\n * a tier mismatch, and must not be swallowed.\n *\n * **Crash-atomicity / idempotency (#712 whole-branch-fix-3).** This loop has\n * no transaction around it: a crash after some entries have been rewritten\n * under `toDek` but before the loop finishes leaves the record's history\n * split across two keys. A retry of the SAME call must not re-fail on the\n * entries that already made it — so each entry is probed with\n * `isRewrappedUnder(env, toDek)` FIRST; a match means it's already at the\n * target key and is skipped (put nothing). This makes same-target retries\n * and demote-after-crash fully self-healing. It does NOT close every crash\n * window: a crash that lands SOME entries under `toDek` while the record's\n * NEXT move target differs from this call's `toDek` (an intermediate-tier\n * crash — e.g. elevate 0→1 crashes mid-loop, then the record is moved 1→2)\n * still finds those entries unreadable under either `fromDek` or the\n * tier-0 fallback, since `toDek` is a third key the next call never probes\n * for. That residual window is an accepted, fail-closed limitation (see\n * `.changeset/history-at-rest.md` and the design doc) — availability is\n * lost, never confidentiality.\n */\nexport async function rewrapHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n fromDek: EnclaveKey,\n toDek: EnclaveKey,\n tier0Dek?: EnclaveKey,\n): Promise<void> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds.filter(id => matchesPrefix(id, collection, recordId))\n\n for (const id of matchingIds) {\n const env = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!env) continue\n // Already a tombstone (forgotten/shredded version)? Nothing to rewrap.\n if (isTombstoneShape(env)) continue\n // #712/whole-branch-fix-3: toDek-first idempotency skip — already at the\n // target key (a same-target retry, or demote-after-crash landing back on\n // a key it already reached)? Nothing to do; put nothing.\n // In-place re-key of a `_history` entry: the address does not move, so the\n // same identity opens and re-seals it (#1041). Built from the entry itself,\n // exactly as a reader would via `recordAadFor`.\n const identity = {\n collection: HISTORY_COLLECTION, id, version: env._v,\n ...(env._tier !== undefined ? { tier: env._tier } : {}),\n ...(env._by !== undefined ? { by: env._by } : {}),\n }\n if (await isRewrappedUnder(identity, env, toDek)) continue\n\n let next: EncryptedEnvelope\n try {\n next = await rewrapEnvelope(identity, env, fromDek, toDek)\n } catch (err) {\n if (!tier0Dek) throw err\n // Legacy fallback: retry once under the tier-0 DEK. A failure here is\n // real corruption, not a tier mismatch — let it propagate.\n next = await rewrapEnvelope(identity, env, tier0Dek, toDek)\n }\n\n await adapter.put(vault, HISTORY_COLLECTION, id, next)\n }\n}\n","/**\n * Strategy seam for the optional history + ledger + time-machine\n * service. Core imports `HistoryStrategy` type-only + `NO_HISTORY`\n * stub; real implementations of `saveHistory`, `LedgerStore`,\n * `VaultInstant`, `computePatch`, `diff` etc. are only reachable via\n * `withHistory()` in `./active.ts`.\n *\n * Applications that don't track per-record versioning, don't need the\n * hash-chained audit ledger, and don't restore to past instants ship\n * none of the ~1,880 LOC behind this seam.\n *\n * Strategy contract:\n *\n * - **saveHistory / pruneHistory / clearHistory** — no-ops under\n * NO_HISTORY. Writes still succeed; no snapshot is captured.\n * - **getHistoryEntries / getVersionEnvelope / diff** — throw under\n * NO_HISTORY. These are read APIs the consumer would only call\n * after explicitly asking for history; the throw guides them to\n * `@noy-db/hub/history`.\n * - **envelopePayloadHash / computePatch** — return empty / `[]`\n * under NO_HISTORY. These are only used inside the\n * `if (this.ledger)` branch, which is itself gated by\n * `buildLedger()` returning null.\n * - **buildLedger** — returns `null` under NO_HISTORY. The Vault's\n * public `vault.ledger()` accessor throws when null.\n * - **buildVaultInstant** — throws under NO_HISTORY. `vault.at()`\n * propagates the throw.\n *\n * @internal\n */\n\nimport type {\n EncryptedEnvelope,\n NoydbStore,\n HistoryOptions,\n PruneOptions,\n} from '../../kernel/types.js'\nimport type { LedgerStore } from './ledger/store.js'\nimport type { JsonPatch } from './ledger/patch.js'\nimport type { DiffEntry } from './diff.js'\nimport type { VaultInstant, VaultEngine } from './time-machine.js'\nimport type { EnclaveKey, RecordIdentity } from '../../kernel/enclave/index.js'\nimport { historyIdentity } from './history.js'\n\n/**\n * Options accepted by `HistoryStrategy.buildLedger`. Mirrors the\n * `LedgerStore` constructor verbatim — kept in this file so `core`\n * code never imports the LedgerStore module at runtime.\n *\n * @internal\n */\nexport interface BuildLedgerOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\n/**\n * @internal\n */\nexport interface HistoryStrategy {\n /**\n * Persist a full encrypted envelope snapshot of the prior version\n * under `_history/{collection}:{id}:{paddedVersion}`. No-op under\n * `NO_HISTORY`.\n */\n saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n ): Promise<void>\n\n /**\n * The identity a snapshot of `collection/recordId@version` must be **sealed\n * against** — its `_history` storage location (#1041).\n *\n * On the port because the kernel writes history snapshots but must not import\n * `with-commit` to learn its layout. Exposing it here keeps the derivation in\n * the module that owns the layout, and `saveHistory` uses the same function,\n * so the sealed identity and the put location cannot drift.\n */\n historyIdentity(collection: string, recordId: string, version: number): RecordIdentity\n\n /**\n * List history envelopes for a record, newest first. Throws under\n * `NO_HISTORY` — callers reach this via `collection.history()` /\n * `collection.getVersion()` / `collection.diff()`, which only work\n * with the strategy enabled.\n */\n getHistoryEntries(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n ): Promise<EncryptedEnvelope[]>\n\n /**\n * Fetch a specific version's envelope. Throws under `NO_HISTORY`.\n */\n getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n ): Promise<EncryptedEnvelope | null>\n\n /**\n * Prune history entries by retention rule. Returns `0` under\n * `NO_HISTORY`.\n */\n pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n ): Promise<number>\n\n /**\n * Clear all history for vault/collection/record. Returns `0` under\n * `NO_HISTORY`.\n */\n clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n ): Promise<number>\n\n /**\n * Crypto-shred (overwrite-to-tombstone) every `_history` version of a\n * record for GDPR erasure. Returns the number of versions newly\n * tombstoned, or `0` under `NO_HISTORY` (no history = nothing to shred).\n */\n tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n ): Promise<number>\n\n /**\n * Re-key every `_history` snapshot of a record from `fromDek` to `toDek`\n * on a tier move (elevate/demote/putAtTier), mirroring the live-body\n * rewrap so prior versions are not left decryptable at rest under a tier\n * the record has moved away from. Optional `tier0Dek` enables the legacy\n * fallback for snapshots written before this rewrap existed (see\n * `history.ts` for the full contract). No-op under `NO_HISTORY` (no\n * history = nothing to rewrap).\n */\n rewrapHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n fromDek: EnclaveKey,\n toDek: EnclaveKey,\n tier0Dek?: EnclaveKey,\n ): Promise<void>\n\n /**\n * Compute the SHA-256 hash of an envelope's encrypted payload, used\n * by `LedgerStore.append` to track tamper-evidence. Returns the\n * empty string under `NO_HISTORY` (the call site is gated by\n * `if (this.ledger)`, so the value is never observed).\n */\n envelopePayloadHash(envelope: EncryptedEnvelope | null): Promise<string>\n\n /**\n * Compute the JSON patch from `from` → `to`. Returns `[]` under\n * `NO_HISTORY`.\n */\n computePatch(from: unknown, to: unknown): JsonPatch\n\n /**\n * Compute the typed diff between two records. Throws under\n * `NO_HISTORY` — `collection.diff()` is a history-read API.\n */\n diff(recordA: unknown, recordB: unknown): DiffEntry[]\n\n /**\n * Construct (or return null) a `LedgerStore` for the vault. Returns\n * `null` under `NO_HISTORY`; the Vault treats null as \"no ledger\n * attached\" — collection write paths skip the append branch and the\n * public `vault.ledger()` accessor throws.\n */\n buildLedger(opts: BuildLedgerOptions): LedgerStore | null\n\n /**\n * Construct a `VaultInstant` for time-machine reads. Throws under\n * `NO_HISTORY`.\n */\n buildVaultInstant(engine: VaultEngine, timestamp: string): VaultInstant\n}\n\n/**\n * Error thrown when the consumer reaches a history-gated surface\n * without opting into the strategy. The message names the offending\n * operation and points to the subpath import.\n *\n * @internal\n */\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op} requires the history strategy. Import ` +\n '`{ withHistory }` from \"@noy-db/hub/history\" and pass it to ' +\n '`createNoydb({ historyStrategy: withHistory() })`.',\n )\n}\n\n/**\n * No-history stub. Snapshots and prune/clear are no-ops; reads and\n * time-machine throw with an actionable message; ledger construction\n * returns null so the write-path's `if (this.ledger)` branch is dead\n * code in the bundle.\n *\n * @internal\n */\nexport const NO_HISTORY: HistoryStrategy = {\n async saveHistory() {},\n // Unreachable in practice — `saveHistory` above is a no-op, so nothing is\n // ever sealed. Returns the real layout rather than a sentinel so a future\n // caller that reads it without writing cannot be misled.\n historyIdentity: (collection, recordId, version) => historyIdentity(collection, recordId, version),\n async getHistoryEntries() { throw notEnabled('collection.history()') },\n async getVersionEnvelope() { throw notEnabled('collection.getVersion()') },\n async pruneHistory() { return 0 },\n async clearHistory() { return 0 },\n async tombstoneHistory() { return 0 },\n async rewrapHistory() {},\n async envelopePayloadHash() { return '' },\n computePatch() { return [] },\n diff() { throw notEnabled('collection.diff()') },\n buildLedger() { return null },\n buildVaultInstant() { throw notEnabled('vault.at() / vault.timeMachine()') },\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAM,qBAAqB;AAC3B,IAAM,cAAc;AAEpB,SAAS,UAAU,YAAoB,UAAkB,SAAyB;AAChF,SAAO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AAG;AAElD,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,eAAe,UAAU,KAAK,SAAS,KAAK;AAAA,IAC3D,SAAS,KAAK;AACZ,UAAI,CAAC,SAAU,OAAM;AAGrB,aAAO,MAAM,eAAe,UAAU,KAAK,UAAU,KAAK;AAAA,IAC5D;AAEA,UAAM,QAAQ,IAAI,OAAO,oBAAoB,IAAI,IAAI;AAAA,EACvD;AACF;;;ACzHA,SAAS,WAAW,IAAmB;AACrC,SAAO,IAAI;AAAA,IACT,GAAG,EAAE;AAAA,EAGP;AACF;AAUO,IAAM,aAA8B;AAAA,EACzC,MAAM,cAAc;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA,EAIrB,iBAAiB,CAAC,YAAY,UAAU,YAAY,gBAAgB,YAAY,UAAU,OAAO;AAAA,EACjG,MAAM,oBAAoB;AAAE,UAAM,WAAW,sBAAsB;AAAA,EAAE;AAAA,EACrE,MAAM,qBAAqB;AAAE,UAAM,WAAW,yBAAyB;AAAA,EAAE;AAAA,EACzE,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,mBAAmB;AAAE,WAAO;AAAA,EAAE;AAAA,EACpC,MAAM,gBAAgB;AAAA,EAAC;AAAA,EACvB,MAAM,sBAAsB;AAAE,WAAO;AAAA,EAAG;AAAA,EACxC,eAAe;AAAE,WAAO,CAAC;AAAA,EAAE;AAAA,EAC3B,OAAO;AAAE,UAAM,WAAW,mBAAmB;AAAA,EAAE;AAAA,EAC/C,cAAc;AAAE,WAAO;AAAA,EAAK;AAAA,EAC5B,oBAAoB;AAAE,UAAM,WAAW,kCAAkC;AAAA,EAAE;AAC7E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/port/with/coverage-strategy.ts"],"sourcesContent":["/**\n * Read-coverage sensor contract (#1363, from the #1251 design).\n *\n * ⛔⛔ **THIS IS TELEMETRY. IT IS NOT A CONTROL.** Against an insider holding\n * the device and local keys, it prevents nothing — they hold the DEK, so the\n * plaintext is derivable whatever hub decides. What it does is make bulk\n * extraction **visible early, attributable and loud**. The real remediation is\n * key custody — tiers and per-collection DEKs — and any deployment that reads\n * this as a control has been made *less* safe by it, because it stops building\n * the key boundary that would actually bind.\n *\n * Lives on the `/with` port (the one seam the kernel spine may import\n * statically) so `Collection`/`RecordCodec` can hold the {@link NO_COVERAGE}\n * floor default without a spine→service static import.\n *\n * ⛔ There is deliberately NO refusal path here, and none may be added. The\n * design ruled (#1251 §3) that set-completion ALERTING beats threshold\n * blocking: a refusal at a boundary is a threshold the reader can\n * binary-search, and a signal is not. Adding \"just an option\" to refuse\n * reintroduces exactly the objection the shape was chosen to dissolve.\n *\n * @internal\n */\n\n/**\n * The one event every sensor in the #1251 design emits, whatever its\n * enforcement point — so a controller subscribes once. Emitted on the Noydb\n * event bus as `'coverage:threshold'`.\n */\nexport interface CoverageEvent {\n /** Authenticated identity the reads are attributed to (`keyring.userId`). */\n readonly principal: string\n readonly vault: string\n readonly collection: string\n /** Records novel to this window (Bloom-estimated; under-reports, never over). */\n readonly novel: number\n /** Decrypts served to this principal for this collection, all time. */\n readonly served: number\n /** Distinct-ever-decrypted as a fraction of the declared corpus, 0..1 (HLL-estimated). */\n readonly coverage: number\n /** ISO-8601 start of the window the crossing was observed in. */\n readonly window: string\n /** Which sensor produced it. `'hub/coverage'` for this one. */\n readonly source: string\n}\n\n/**\n * The decrypt observer: called once per record decrypt, with the record id.\n *\n * ⛔ The id is passed so the sketch can be UPDATED with it, and must never be\n * retained. See `with-audit/coverage/sketch.ts`.\n */\nexport type CoverageObserver = (id: string) => void\n\n/** The minimal emitter slice the sensor needs. Structural, to avoid an import. */\nexport interface CoverageEmitter {\n emit(event: 'coverage:threshold', data: CoverageEvent): void\n}\n\n/** Field descriptors, read only for the `bulk` axis. Structural by design. */\nexport type CoverageFieldMeta = Readonly<Record<string, { readonly bulk?: 'sensitive' }>>\n\nexport interface CoverageStrategy {\n /**\n * Resolve the decrypt observer for one collection, or `undefined` when\n * nothing should be accounted — which is the un-opted-in case, and also the\n * opted-in case for a collection declaring no `bulk: 'sensitive'` field.\n *\n * `fieldMeta` is a THUNK because `fieldMeta` can be attached to a Collection\n * after construction (`_applyFieldMeta`, first-wins), and this is called\n * from the constructor.\n *\n * ⛔ `eager` is load-bearing, not informational — see the eager-hydration\n * note in `with-audit/coverage/accounting.ts`. An eager collection decrypts\n * its WHOLE corpus at hydration, so a decrypt-point sensor reads 100%\n * coverage for anyone who opens the vault.\n */\n observer(\n vault: string,\n collection: string,\n principal: string,\n fieldMeta: () => CoverageFieldMeta | undefined,\n emitter: CoverageEmitter,\n eager: boolean,\n ): CoverageObserver | undefined\n}\n\n/**\n * The un-opted-in floor: no observer, therefore no accounting, no allocation\n * per read, and no coverage code in the bundle. `Collection` calls\n * `observer()` once at construction and stores `undefined`; `RecordCodec`'s\n * hot path is a single `!== undefined` test.\n */\nexport const NO_COVERAGE: CoverageStrategy = { observer: () => undefined }\n"],"mappings":";AA6FO,IAAM,cAAgC,EAAE,UAAU,MAAM,OAAU;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-audit/portability/withdraw-accessible.ts"],"sourcesContent":["/**\n * `unilateralWithdrawal`: a non-owner extracts their accessible scope\n * AND disposes of the source copy. Destructive; gated by the default-off\n * fail-closed built-in `client-unilateral-withdraw` policy (checked in the\n * UserApi wrapper).\n *\n * Two source dispositions:\n * - 'delete' — delete-closure: the records leave the source vault entirely.\n * - 'freeze' — the firm retains a cryptographically-frozen, read-only, write-once\n * snapshot (hash-pinned in the tamper-evident ledger) while the live\n * records are removed.\n *\n * Ordering guarantees no data loss: the client's re-keyed export bundle (and the\n * freeze snapshot) are produced BEFORE anything is deleted.\n *\n * The `freezeAndDeleteClosure` core is shared with the two-party approval path\n * (`request-withdrawal.ts`).\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport { buildRecordEnvelope, sha256Hex } from '../../kernel/enclave/index.js'\nimport { ReadOnlyError } from '../../kernel/errors.js'\nimport { resolveAccessibleCollections, buildAccessibleBundle } from './export-accessible.js'\n\nexport const FROZEN_SNAPSHOTS_COLLECTION = '_frozen_snapshots'\nconst ENC = new TextEncoder()\n\n/** 24-hex-char random id (used for withdrawal ids + request ids). */\nexport function randomId(): string {\n const b = globalThis.crypto.getRandomValues(new Uint8Array(12))\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n}\n\nexport interface FrozenSnapshotRef {\n readonly withdrawalId: string\n readonly sha256: string\n readonly recordCount: number\n readonly frozenAt: string\n}\n\nexport interface WithdrawAccessibleOptions {\n /** Legal/contractual basis recorded in the audit (e.g. 'gdpr-art-17'). */\n readonly legalBasis: string\n /** Re-key the exported bundle to a new owner secret. */\n readonly reKey?: { readonly secret: string }\n /** Source disposition. Default 'delete'. */\n readonly disposition?: 'delete' | 'freeze'\n readonly scope?: { readonly collections?: readonly string[] }\n /** Stable id for idempotent resume (default random). */\n readonly withdrawalId?: string\n}\n\nexport interface WithdrawResult {\n readonly bundle: Uint8Array\n readonly snapshot?: FrozenSnapshotRef\n}\n\n/**\n * Freeze a write-once, hash-pinned snapshot of the current ciphertext for\n * `collections` WITHOUT touching the live records. Returns the snapshot ref.\n *\n * This is the non-destructive core shared by two callers:\n * - `freezeAndDeleteClosure` (withdrawal, disposition `'freeze'`) — which\n * pins the snapshot and THEN delete-closures the live records.\n * - FR-6 `liberateVault` (custody) — which pins a PRE-liberation evidence\n * snapshot but PRESERVES the live data for the new owner (operational\n * continuity; liberation transfers, it does not erase).\n *\n * The snapshot put is write-once (CAS expectedVersion 0) and the ledger pin is\n * appended on success, so a crashed run re-run with the same `withdrawalId` is\n * safe. The snapshot is taken under the vault's own firm-owned DEKs — no re-key.\n */\nexport async function freezeSnapshotOnly(\n vault: Vault,\n collections: readonly string[],\n opts: { actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef> {\n const { name: vaultName, adapter } = vault._introspectState()\n\n // Enumerate the closure (record ids per collection).\n const closure: Array<{ collection: string; id: string }> = []\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) closure.push({ collection: c, id })\n }\n\n const withdrawalId = opts.withdrawalId ?? `wd-${randomId()}`\n const snap: Record<string, Record<string, unknown>> = {}\n for (const { collection, id } of closure) {\n const env = await adapter.get(vaultName, collection, id)\n if (env) (snap[collection] ??= {})[id] = env\n }\n const frozenAt = new Date().toISOString()\n const body = JSON.stringify({ withdrawalId, frozenAt, by: opts.actorUserId, collections: snap })\n const sha = await sha256Hex(ENC.encode(body))\n // Write-once: expectedVersion 0 rejects an overwrite (idempotent resume).\n await adapter.put(\n vaultName,\n FROZEN_SNAPSHOTS_COLLECTION,\n withdrawalId,\n buildRecordEnvelope(\n { collection: FROZEN_SNAPSHOTS_COLLECTION, id: withdrawalId, by: opts.actorUserId, version: 1 },\n { ts: frozenAt, iv: '', data: body},\n ),\n 0,\n )\n // Hash-pin into the tamper-evident ledger — makes the snapshot provably unaltered.\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: opts.actorUserId, payloadHash: '',\n reason: `withdrawal-frozen-snapshot:${withdrawalId}:${sha}`,\n })\n return { withdrawalId, sha256: sha, recordCount: closure.length, frozenAt }\n}\n\n/**\n * Dispose of the source records for `collections`: optionally freeze a\n * write-once hash-pinned snapshot of the original ciphertext, then\n * delete-closure the live records. Returns the snapshot ref on freeze.\n *\n * Caller MUST have produced the portable bundle FIRST — this is destructive.\n * The delete is best-effort + idempotent (re-deleting an absent record is a\n * no-op) and the snapshot put is write-once (CAS expectedVersion 0), so a\n * crashed run re-run with the same `withdrawalId` is safe.\n */\nexport async function freezeAndDeleteClosure(\n vault: Vault,\n collections: readonly string[],\n opts: { disposition: 'delete' | 'freeze'; actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef | undefined> {\n // freeze: pin a write-once, hash-pinned snapshot BEFORE any delete. The\n // snapshot-only core is shared with FR-6 liberation (which never deletes).\n const snapshot = opts.disposition === 'freeze'\n ? await freezeSnapshotOnly(vault, collections, {\n actorUserId: opts.actorUserId,\n ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n : undefined\n\n // delete-closure — only after the snapshot is durable.\n const { name: vaultName, adapter } = vault._introspectState()\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) {\n await vault.collection(c).delete(id)\n }\n }\n\n return snapshot\n}\n\nexport async function withdrawAccessibleData(\n vault: Vault,\n opts: WithdrawAccessibleOptions,\n): Promise<WithdrawResult> {\n const { keyring } = vault._introspectState()\n const disposition = opts.disposition ?? 'delete'\n\n // Owner-class roles hold blanket authority — they use extractPartition.\n if (keyring.role === 'owner' || keyring.role === 'admin') {\n throw new ReadOnlyError(\n 'unilateralWithdrawal is the scoped self-service path; an owner/admin should use extractPartition',\n )\n }\n // FR-6: a custodian must NOT destructively SEVER the vault. It holds the DEKs\n // and operates fully, but ownership is claimed only through the audited\n // Liberate ceremony — never by a one-sided delete/freeze withdrawal. Fires\n // BEFORE the operator rw-scope path below (where a custodian would otherwise\n // be rejected with the wrong \"requires rw access\" message).\n if (keyring.role === 'custodian') {\n throw new ReadOnlyError(\n 'a custodian cannot destructively withdraw/sever; use vault.custody.liberate for an audited ownership claim',\n )\n }\n // client/viewer are read-only by construction (see hasWritePermission): a\n // destructive withdrawal they cannot self-serve — they use the two-party\n // requestWithdrawal flow where firm authority executes the delete-closure.\n if (keyring.role === 'client' || keyring.role === 'viewer') {\n throw new ReadOnlyError(\n 'read-only role cannot self-serve a destructive withdrawal — use requestWithdrawal (two-party)',\n )\n }\n // Operator path: destructive ops need rw on the whole scope.\n const collections = resolveAccessibleCollections(keyring, opts.scope, true)\n if (!collections || collections.length === 0) {\n throw new ReadOnlyError(\n 'unilateralWithdrawal requires rw access on the withdrawn collections — use requestWithdrawal for read-only scope',\n )\n }\n\n // 1. Produce the client's re-keyed portable copy FIRST (nothing destroyed yet).\n const bundle = await buildAccessibleBundle(vault, collections, opts.reKey)\n\n // 2. + 3. freeze (optional) then delete-closure.\n const snapshot = await freezeAndDeleteClosure(vault, collections, {\n disposition, actorUserId: keyring.userId, ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n\n // 4. audit\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: keyring.userId, payloadHash: '',\n reason: `user-unilateral-withdrawal:${keyring.userId}:${disposition}:${opts.legalBasis}`,\n })\n\n return snapshot ? { bundle, snapshot } : { bundle }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBO,IAAM,8BAA8B;AAC3C,IAAM,MAAM,IAAI,YAAY;AAGrB,SAAS,WAAmB;AACjC,QAAM,IAAI,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC9D,SAAO,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACtE;AAyCA,eAAsB,mBACpB,OACA,aACA,MAC4B;AAC5B,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAG5D,QAAM,UAAqD,CAAC;AAC5D,aAAW,KAAK,aAAa;AAC3B,eAAW,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,EAAG,SAAQ,KAAK,EAAE,YAAY,GAAG,GAAG,CAAC;AAAA,EACvF;AAEA,QAAM,eAAe,KAAK,gBAAgB,MAAM,SAAS,CAAC;AAC1D,QAAM,OAAgD,CAAC;AACvD,aAAW,EAAE,YAAY,GAAG,KAAK,SAAS;AACxC,UAAM,MAAM,MAAM,QAAQ,IAAI,WAAW,YAAY,EAAE;AACvD,QAAI,IAAK,EAAC,KAAK,UAAU,MAAM,CAAC,GAAG,EAAE,IAAI;AAAA,EAC3C;AACA,QAAM,YAAW,oBAAI,KAAK,GAAE,YAAY;AACxC,QAAM,OAAO,KAAK,UAAU,EAAE,cAAc,UAAU,IAAI,K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R;AAAA,IACF;AAAA,EACF;AAMA,MAAI,QAAQ,SAAS,aAAa;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAIA,MAAI,QAAQ,SAAS,YAAY,QAAQ,SAAS,UAAU;AAC1D,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,6BAA6B,SAAS,KAAK,OAAO,IAAI;AAC1E,MAAI,CAAC,eAAe,YAAY,WAAW,GAAG;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAGA,QAAM,SAAS,MAAM,sBAAsB,OAAO,aAAa,KAAK,KAAK;AAGzE,QAAM,WAAW,MAAM,uBAAuB,OAAO,aAAa;AAAA,IAChE;AAAA,IAAa,aAAa,QAAQ;AAAA,IAAQ,GAAI,KAAK,eAAe,EAAE,cAAc,KAAK,aAAa,IAAI,CAAC;AAAA,EAC3G,CAAC;AAGD,QAAM,MAAM,iBAAiB,GAAG,OAAO;AAAA,IACrC,IAAI;AAAA,IAAa,YAAY;AAAA,IAAI,IAAI;AAAA,IAAI,SAAS;AAAA,IAAG,OAAO,QAAQ;AAAA,IAAQ,aAAa;AAAA,IACzF,QAAQ,8BAA8B,QAAQ,MAAM,IAAI,WAAW,IAAI,KAAK,UAAU;AAAA,EACxF,CAAC;AAED,SAAO,WAAW,EAAE,QAAQ,SAAS,IAAI,EAAE,OAAO;AACpD;","names":[]}
@@ -1,66 +0,0 @@
1
- import {
2
- NOYDB_FORMAT_VERSION
3
- } from "./chunk-ODVPTDPK.js";
4
-
5
- // src/kernel/enclave/record-envelope.ts
6
- function buildRecordEnvelope(identity, body) {
7
- return {
8
- _noydb: NOYDB_FORMAT_VERSION,
9
- _v: identity.version,
10
- _ts: body.ts ?? (/* @__PURE__ */ new Date()).toISOString(),
11
- _iv: body.iv,
12
- _data: body.data,
13
- ...identity.by !== void 0 ? { _by: identity.by } : {},
14
- ...identity.tier !== void 0 && identity.tier > 0 ? { _tier: identity.tier } : {},
15
- ...body.cek !== void 0 ? { _cek: body.cek } : {},
16
- ...body.provenance !== void 0 ? { _source: body.provenance.source, _sourceTs: body.provenance.sourceTs } : {},
17
- ...body.extra ?? {}
18
- };
19
- }
20
- async function buildSealedRecordEnvelope(identity, seal, body) {
21
- const sealed = await seal(identity);
22
- return buildRecordEnvelope(identity, {
23
- ...body,
24
- iv: sealed._iv,
25
- data: sealed._data,
26
- cek: sealed._cek
27
- });
28
- }
29
-
30
- // src/kernel/enclave/record-keys/tombstone.ts
31
- function isTombstoneShape(envelope) {
32
- return envelope._data === "" && envelope._cek === void 0 && envelope._del !== true;
33
- }
34
- function isTombstone(envelope, encrypted) {
35
- if (!encrypted) return false;
36
- return isTombstoneShape(envelope);
37
- }
38
- function buildTombstone(ref, version, actor) {
39
- return buildRecordEnvelope(
40
- { ...ref, version, ...actor ? { by: actor } : {} },
41
- { iv: "", data: "" }
42
- );
43
- }
44
- function isDeleteMarker(envelope) {
45
- return envelope._del === true;
46
- }
47
- function buildDeleteMarker(ref, version, actor) {
48
- return {
49
- ...buildRecordEnvelope(
50
- { ...ref, version, ...actor ? { by: actor } : {} },
51
- { iv: "", data: "" }
52
- ),
53
- _del: true
54
- };
55
- }
56
-
57
- export {
58
- buildRecordEnvelope,
59
- buildSealedRecordEnvelope,
60
- isTombstoneShape,
61
- isTombstone,
62
- buildTombstone,
63
- isDeleteMarker,
64
- buildDeleteMarker
65
- };
66
- //# sourceMappingURL=chunk-SEE332EV.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kernel/enclave/record-envelope.ts","../src/kernel/enclave/record-keys/tombstone.ts"],"sourcesContent":["/**\n * The one place an `EncryptedEnvelope` is constructed (#1051).\n *\n * ## Why this exists\n *\n * 49 files built envelopes with an object literal, bypassing\n * `RecordCodec.buildEnvelope` (which had 4 callers). That is **writer\n * fan-out**: N independent places each had to know the envelope contract, and\n * nothing checked that they agreed.\n *\n * It only became load-bearing with #1041. Binding a record's identity into the\n * AEAD requires every writer to supply that identity — and a writer that\n * doesn't produces data the reader rejects. Reader fan-out you fix by threading\n * an argument through call sites; **writer fan-out cannot be migrated\n * incrementally**, because the first migrated writer emits envelopes the\n * unmigrated readers refuse.\n *\n * ## Why adopting it is safe\n *\n * `identity` is **required but not yet used**. Output is byte-identical to the\n * literals it replaces, so every producer can migrate independently and the\n * existing suite verifies each step. The behaviour change happens **once**,\n * when AAD is switched on here — by which point every writer already supplies\n * identity, and the compiler proved it.\n *\n * That ordering is deliberate: a required-but-unused parameter converts \"did\n * we find every writer?\" from a question into a compile error, the same trick\n * that made the `NOYDB_FORMAT_VERSION` single-sourcing safe in #1048.\n *\n * @packageDocumentation\n */\nimport { NOYDB_FORMAT_VERSION } from '../types.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport type { RecordIdentity } from './record-aad.js'\n\n/** The body an envelope carries, independent of who is writing it. */\nexport interface RecordEnvelopeBody {\n /** AES-GCM IV, base64. Empty string for a plaintext or tombstone envelope. */\n readonly iv: string\n /** Ciphertext (or plaintext JSON when the collection stores plaintext). */\n readonly data: string\n /** ISO timestamp. Defaults to now — pass it when the caller has a real one. */\n readonly ts?: string | undefined\n /** Wrapped per-record CEK, when the record has one. */\n readonly cek?: string | undefined\n readonly provenance?: { readonly source: string; readonly sourceTs: string } | undefined\n /**\n * Slots the envelope may additionally carry.\n *\n * `_tier`, `_by` and `_v` are deliberately NOT here — they come from\n * `identity`, which is the single source for all three. See\n * {@link buildRecordEnvelope}.\n */\n readonly extra?: Partial<Pick<EncryptedEnvelope, '_det' | '_sealed' | '_vdig' | '_bidx'>> | undefined\n}\n\n/**\n * Build an envelope for `identity`.\n *\n * ## `identity` is the SINGLE SOURCE for `_by`, `_tier` and `_v`\n *\n * All three are stamped from it, and `RecordEnvelopeBody` deliberately cannot\n * carry them. That is not tidiness — it is what makes the AAD binding safe.\n *\n * The caller encrypts the body under AAD derived from `{collection, id, tier,\n * by, version}`. A reader recomputes that AAD from the address it fetched from\n * plus `_tier`/`_by`/`_v` read back **off the envelope** (`recordAadFor`). So if the\n * identity a writer *declares* could differ from the fields it *stamps*, the\n * AAD would not reproduce and the record would be undecryptable — silently, at\n * write time, discoverable only on the next read, and invisible to every gate\n * because the envelope is perfectly well-formed.\n *\n * An earlier draft took both and asserted they agreed. The assertion fired 230\n * times on the existing tree, which is the argument against it: a rule that can\n * be violated is a rule someone must remember. Taking one source removes the\n * violation instead of reporting it.\n */\nexport function buildRecordEnvelope(\n identity: RecordIdentity,\n body: RecordEnvelopeBody,\n): EncryptedEnvelope {\n return {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: identity.version,\n _ts: body.ts ?? new Date().toISOString(),\n _iv: body.iv,\n _data: body.data,\n ...(identity.by !== undefined ? { _by: identity.by } : {}),\n ...(identity.tier !== undefined && identity.tier > 0 ? { _tier: identity.tier } : {}),\n ...(body.cek !== undefined ? { _cek: body.cek } : {}),\n ...(body.provenance !== undefined\n ? { _source: body.provenance.source, _sourceTs: body.provenance.sourceTs }\n : {}),\n ...(body.extra ?? {}),\n }\n}\n\n/**\n * Build an envelope from an already-sealed body — the output of\n * `writeEnvelopeBody` — **without the caller ever naming `_iv`/`_data`/`_cek`**.\n *\n * This exists because of a guard, and the guard was right. Migrating\n * `writeEnvelopeBody` callers to {@link buildRecordEnvelope} meant rewriting\n * `...body` (a spread, which names nothing) into `iv: body._iv, data:\n * body._data, cek: body._cek` — and `enclave-body-only` failed it: three new\n * protected-body accesses in files that previously had zero.\n *\n * That is the correct outcome rather than an obstacle. #1051 exists to move\n * knowledge of the envelope's shape *inward*; a migration that spreads the\n * protected field names outward to every caller would have defeated its own\n * purpose while looking like progress. The pairing belongs here.\n *\n * ## It takes a SEALER, not a sealed body — and that is load-bearing (#1041)\n *\n * The obvious shape is `(identity, alreadySealedBody, rest)`. That requires the\n * caller to name the identity TWICE — once for `writeEnvelopeBody` and once\n * here — and the two must agree byte for byte or the record is sealed under\n * AAD no reader can reproduce.\n *\n * They did not agree. `with-party/broker/seed.ts` sealed against\n * `{collection, id}` and stamped `{collection, id, by}`, so every broker seed\n * became unreadable the moment AAD switched on. Taking the sealer means the\n * identity is written once and handed to both — divergence stops being\n * possible rather than being something to remember.\n */\nexport async function buildSealedRecordEnvelope(\n identity: RecordIdentity,\n seal: (identity: RecordIdentity) => Promise<Pick<EncryptedEnvelope, '_iv' | '_data' | '_cek'>>,\n body: Omit<RecordEnvelopeBody, 'iv' | 'data' | 'cek'>,\n): Promise<EncryptedEnvelope> {\n const sealed = await seal(identity)\n return buildRecordEnvelope(identity, {\n ...body,\n iv: sealed._iv,\n data: sealed._data,\n cek: sealed._cek,\n })\n}\n","/**\n * Tombstone shape + predicate for the per-record-key (CEK) layer.\n *\n * A *tombstone* is the residue a GDPR crypto-shred (`vault.forget()`)\n * leaves on disk: the live envelope rewritten to `{ _noydb, _v, _ts, _by,\n * _iv:'', _data:'' }`, dropping `_iv`/`_data`/`_cek`/`_det`. With the wrapped\n * per-record CEK gone, the body — and every history version under the same\n * CEK — is permanently undecryptable, while the record KEY survives so the\n * version counter and \"record existed and was erased\" persist for the audit\n * ledger.\n *\n * These two helpers are the pure, collection-independent core of that\n * contract: {@link buildTombstone} mints the shape, {@link isTombstone}\n * recognises it on the read path. The orchestration that *writes* a tombstone\n * (`_writeTombstone`) and drives `vault.forget()` lives with the collection /\n * vault; it calls into these.\n */\nimport { type EncryptedEnvelope } from '../../types.js'\nimport { buildRecordEnvelope } from '../record-envelope.js'\nimport type { RecordRef } from '../record-aad.js'\n\n/**\n * Shape-only tombstone recognition for layers that have no per-collection\n * context (the sync engine, #590): a tombstone carries an empty `_data` and\n * no wrapped CEK. No live envelope can match — record bodies never serialize\n * to the empty string (the `_sync` meta envelope carries non-empty `_data`,\n * and legacy migration envelopes carry non-empty `_iv`/`_data`).\n */\nexport function isTombstoneShape(envelope: EncryptedEnvelope): boolean {\n return envelope._data === '' && envelope._cek === undefined && envelope._del !== true\n}\n\n/**\n * Is this envelope a crypto-shred tombstone?\n *\n * A tombstone carries no body (`_data` empty) and no wrapped CEK (`_cek`\n * absent) — decrypting it would call `decrypt('', '', dek)` → an AES-GCM\n * throw, so every read choke point must short-circuit to `null` instead.\n *\n * `encrypted` is the collection's encryption flag: on an unencrypted\n * collection there are no envelopes to shred, so nothing is ever a tombstone.\n * (Legacy migration envelopes carry non-empty `_iv`/`_data`, so they are not\n * tombstones and stay readable.)\n */\nexport function isTombstone(envelope: EncryptedEnvelope, encrypted: boolean): boolean {\n if (!encrypted) return false\n return isTombstoneShape(envelope)\n}\n\n/**\n * Mint a tombstone envelope from a record's live version + actor.\n *\n * Keeps `_v` (the displaced version) so the counter is monotonic across the\n * shred, stamps a fresh `_ts`, and records `_by` when an actor is supplied.\n * Deliberately omits `_iv`/`_data`/`_cek`/`_det` — that omission *is* the\n * erasure.\n */\nexport function buildTombstone(\n ref: RecordRef,\n version: number,\n actor: string,\n): EncryptedEnvelope {\n // `actor` rides on the IDENTITY, not the body — it is stamped as `_by` and\n // bound into the AAD from that one source (#1041).\n return buildRecordEnvelope(\n { ...ref, version, ...(actor ? { by: actor } : {}) },\n { iv: '', data: '' },\n )\n}\n\n/** #589: is this envelope an ordinary-delete marker (version-ordered, reads as absent)? */\nexport function isDeleteMarker(envelope: EncryptedEnvelope): boolean {\n return envelope._del === true\n}\n\n/**\n * Mint a delete marker from the deleted record's next version + actor (#589).\n * Minted at the NEXT version (`existing._v + 1`) — unlike `buildTombstone`, which\n * keeps the displaced `_v` — so it wins convergence over the pre-delete copy and a\n * re-create can still win over it at a higher version.\n */\nexport function buildDeleteMarker(\n ref: RecordRef,\n version: number,\n actor: string,\n): EncryptedEnvelope {\n // `_del` is not one of buildRecordEnvelope's declared slots — a delete marker\n // is a distinct envelope class, not a record body — so it is stamped here.\n return {\n ...buildRecordEnvelope(\n { ...ref, version, ...(actor ? { by: actor } : {}) },\n { iv: '', data: '' },\n ),\n _del: true,\n }\n}\n"],"mappings":";;;;;AA6EO,SAAS,oBACd,UACA,MACmB;AACnB,SAAO;A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AA,IACL,GAAG;AAAA,MACD,EAAE,GAAG,KAAK,SAAS,GAAI,QAAQ,EAAE,IAAI,MAAM,IAAI,CAAC,EAAG;AAAA,MACnD,EAAE,IAAI,IAAI,MAAM,GAAG;AAAA,IACrB;AAAA,IACA,MAAM;AAAA,EACR;AACF;","names":[]}
@@ -1,20 +0,0 @@
1
- import {
2
- dekKey
3
- } from "./chunk-JCN44NCY.js";
4
- import {
5
- TierNotGrantedError
6
- } from "./chunk-244VXYPG.js";
7
-
8
- // src/with-party/team/tiers.ts
9
- function assertTierAccess(keyring, collection, tier) {
10
- if (tier <= 0) return;
11
- if (keyring.role === "owner" || keyring.role === "admin" || keyring.role === "custodian") return;
12
- if (!keyring.deks.has(dekKey(collection, tier))) {
13
- throw new TierNotGrantedError(collection, tier);
14
- }
15
- }
16
-
17
- export {
18
- assertTierAccess
19
- };
20
- //# sourceMappingURL=chunk-SOIQ4MM4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-party/team/tiers.ts"],"sourcesContent":["/**\n * Hierarchical access — tier-aware keyring helpers.\n *\n * The keyring's existing `deks: Map<string, CryptoKey>` is keyed by\n * collection name. extends the key space:\n *\n * `'invoices'` — tier-0 DEK (unchanged from v0.x)\n * `'invoices#1'` — tier-1 DEK\n * `'invoices#2'` — tier-2 DEK\n *\n * Tier 0 keeps the bare collection name so any keyring written\n * before tiers existed loads without migration. Tiers ≥ 1 use `#N`\n * suffixes that\n * would be invalid as user-supplied collection names (see\n * `ReservedCollectionNameError` — `#` is reserved).\n *\n * @module\n */\n\nimport type { UnlockedKeyring } from './keyring.js'\nimport { TierNotGrantedError } from '../../kernel/errors.js'\n\n/** Canonical DEK key for a given collection + tier. Tier 0 → bare name. */\n// Moved to `kernel/tier-visibility.ts` (#1042): the kernel needs it to resolve\n// a pulled envelope's DEK, and `port-layering` forbids the spine importing a\n// `with-*` service. Re-exported so every existing importer is unchanged.\nimport { dekKey } from '../../kernel/tier-visibility.js'\nexport { dekKey }\n\n/**\n * Returns the user's effective clearance for a given collection: the\n * maximum tier for which their keyring holds a DEK. Falls back to 0\n * when the user has only the tier-0 DEK (or none — the getDEK caller\n * will raise separately).\n */\nexport function effectiveClearance(keyring: UnlockedKeyring, collection: string): number {\n let max = 0\n const prefix = `${collection}#`\n for (const key of keyring.deks.keys()) {\n if (!key.startsWith(prefix)) continue\n const suffix = key.slice(prefix.length)\n const n = Number.parseInt(suffix, 10)\n if (Number.isFinite(n) && n > max) max = n\n }\n return max\n}\n\n/**\n * Assert the caller is cleared for the requested tier. Owners and\n * admins always pass (they can mint any new tier DEK on demand);\n * other roles must already hold the tier DEK — via a prior grant or\n * an active delegation — otherwise this throws `TierNotGrantedError`.\n *\n * This gate runs BEFORE `getDEK()` on the mutation path so a\n * non-cleared operator never has the opportunity to silently\n * auto-create a tier DEK they shouldn't have.\n */\nexport function assertTierAccess(\n keyring: UnlockedKeyring,\n collection: string,\n tier: number,\n): void {\n if (tier <= 0) return\n // FR-6: custodian operates every collection at every tier (admin-level\n // operational authority), so it may mint a tier DEK on demand like admin.\n if (keyring.role === 'owner' || keyring.role === 'admin' || keyring.role === 'custodian') return\n if (!keyring.deks.has(dekKey(collection, tier))) {\n throw new TierNotGrantedError(collection, tier)\n }\n}\n"],"mappings":";;;;;;;;AAyDO,SAAS,iBACd,SACA,YACA,MACM;AACN,MAAI,QAAQ,EAAG;AAGf,MAAI,QAAQ,SAAS,WAAW,QAAQ,SAAS,WAAW,QAAQ,SAAS,YAAa;AAC1F,MAAI,CAAC,QAAQ,KAAK,IAAI,OAAO,YAAY,IAAI,CAAC,GAAG;AAC/C,UAAM,IAAI,oBAAoB,YAAY,IAAI;AAAA,EAChD;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-shape/manifest/types.ts","../src/with-shape/manifest/storage.ts","../src/with-shape/manifest/derive.ts"],"sourcesContent":["/**\n * The pod-wide **schema manifest** record type (#941).\n *\n * This is an INDEX, not a full-inline manifest: `SchemaManifest.collections`\n * carries per-collection *metadata* (generation / content hash / field ids),\n * never the JSON Schema body itself. The JSON Schema stays the source of\n * truth at `_schemas/<collection>`, encrypted under that collection's own\n * DEK (see `with-shape/persisted-schemas`). Inlining full schemas into one\n * pod-wide manifest record would either leak every collection's schema to a\n * principal scoped to a single collection, or force the manifest itself\n * onto a collection-DEK it has no business holding — the index preserves\n * per-collection DEK isolation while still giving a single place to answer\n * \"what schema generation is this pod at, and does collection X's stored\n * schema match its declared content hash.\"\n *\n * `aggregateHash` binds the whole per-collection index's content: it is\n * `sha256Hex(canonicalJson(collections))`, so any change to any collection's\n * entry (a new generation, a changed hash, added/renamed field ids) changes\n * `aggregateHash` too. Canonical JSON (sorted object keys, no whitespace)\n * makes the hash independent of the map's key insertion order.\n *\n * @module\n */\n\n/** Per-collection entry inside a {@link SchemaManifest}'s `collections` index. */\nexport interface SchemaManifestEntry {\n /** The vault-wide schema-fence generation this collection's schema was last written at. */\n readonly generation: number\n /** SHA-256 (hex) of the collection's canonicalised JSON Schema (see `persisted-schemas/derive.ts`). */\n readonly contentHash: string\n /** Stable per-field ids (#946), keyed by the field's current name. Absent when the collection has none. */\n readonly fieldIds?: Record<string, string>\n}\n\n/**\n * The pod-wide schema manifest — one record per pod, stored at\n * `_manifest/schema` (see `storage.ts`). An INDEX over the per-collection\n * `_schemas/<collection>` entries, not the schemas themselves.\n */\nexport interface SchemaManifest {\n readonly v: 1\n readonly kind: 'schema'\n /** Pod-wide schema-fence generation (`FenceDoc.currentSchemaVersion`) as of this manifest's derivation. */\n readonly generation: number\n /** Per-collection index: collection name → its manifest entry. */\n readonly collections: Record<string, SchemaManifestEntry>\n /** `sha256Hex(canonicalJson(collections))` — the pod-wide content binding over the index. */\n readonly aggregateHash: string\n}\n\n/** The record id the schema manifest is stored under inside `_manifest`. */\nexport const MANIFEST_SCHEMA_RECORD_ID = 'schema' as const\n","/**\n * Read / write the pod-wide `_manifest/schema` envelope.\n *\n * Mirrors `with-shape/persisted-schemas/storage.ts`'s shape: the same\n * standard noy-db record envelope, AES-GCM encrypted with a collection DEK\n * (here, the `_manifest` collection's own DEK — the manifest INDEX\n * discloses collection names + hashes + generations + field ids, metadata\n * rather than schema bodies, so it gets the same encryption grain as\n * `_schemas` itself).\n *\n * Storage layout:\n *\n * <vault>/_manifest/schema → EncryptedEnvelope\n *\n * Unlike `persisted-schemas/storage.ts` (which takes an already-resolved\n * `EnclaveKey`), these functions take a `getDEK` resolver and call\n * `getDEK(MANIFEST_COLLECTION)` themselves — there is exactly one manifest\n * record per pod, so there is no per-collection DEK the caller needs to\n * pick; resolving it here keeps every manifest call-site symmetric.\n *\n * @module\n */\n\nimport { buildSealedRecordEnvelope, openEnvelopeJson, writeEnvelopeBody, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { canonicalJson, sha256Hex } from '../../with-commit/history/ledger/index.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport { MANIFEST_COLLECTION } from './reserved-collections.js'\nimport { MANIFEST_SCHEMA_RECORD_ID, type SchemaManifest, type SchemaManifestEntry } from './types.js'\n\n/** A resolver for a collection's DEK — the same shape as `Vault`'s internal `getDEK`. */\nexport type GetManifestDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/**\n * A decrypted schema-manifest read paired with the wrapping envelope's `_v`\n * — the optimistic-concurrency token. Pass `version` back to\n * {@link saveSchemaManifest} (via `writeSchemaManifest`'s `expectedVersion`)\n * to make the write a strict CAS.\n */\nexport interface LoadedSchemaManifest {\n /** Wrapping envelope `_v`. */\n readonly version: number\n /** Decrypted schema manifest. */\n readonly manifest: SchemaManifest\n}\n\n/**\n * Read the `_manifest/schema` envelope together with its wrapping `_v`.\n * Returns `undefined` when no manifest has ever been written, when the\n * envelope fails to decrypt (wrong DEK), or when it doesn't parse as a\n * `v: 1, kind: 'schema'` manifest.\n */\nexport async function loadSchemaManifestEntry(\n store: NoydbStore,\n vault: string,\n getDEK: GetManifestDEK,\n): Promise<LoadedSchemaManifest | undefined> {\n const envelope = await store.get(vault, MANIFEST_COLLECTION, MANIFEST_SCHEMA_RECORD_ID)\n if (!envelope) return undefined\n const dek = await getDEK(MANIFEST_COLLECTION)\n try {\n const plaintext = await openEnvelopeJson({ collection: MANIFEST_COLLECTION, id: MANIFEST_SCHEMA_RECORD_ID }, envelope, dek)\n const parsed = JSON.parse(plaintext) as SchemaManifest\n if (parsed.v !== 1 || parsed.kind !== 'schema') return undefined\n return { version: envelope._v, manifest: parsed }\n } catch {\n return undefined\n }\n}\n\n/**\n * Encrypt and persist the schema manifest as a strict CAS write:\n * `expectedVersion` must match the stored envelope's `_v` (0 when no\n * envelope exists yet) or `store.put` throws `ConflictError` — surfaced by\n * `writer.ts`'s `writeSchemaManifest` as `ManifestConflictError` rather than\n * retried.\n */\nexport async function saveSchemaManifest(\n store: NoydbStore,\n vault: string,\n manifest: SchemaManifest,\n expectedVersion: number,\n getDEK: GetManifestDEK,\n): Promise<void> {\n const dek = await getDEK(MANIFEST_COLLECTION)\n const json = JSON.stringify(manifest)\n const env = await buildSealedRecordEnvelope(\n { collection: MANIFEST_COLLECTION, id: MANIFEST_SCHEMA_RECORD_ID, version: expectedVersion + 1 },\n (identity) => writeEnvelopeBody(identity, json, dek),\n {},\n )\n await store.put(vault, MANIFEST_COLLECTION, MANIFEST_SCHEMA_RECORD_ID, env, expectedVersion)\n}\n\n/**\n * `sha256Hex(canonicalJson(collections))` — the pod-wide content binding\n * over a schema manifest's per-collection index. Canonical JSON sorts\n * object keys at every depth, so the result is independent of the map's\n * key insertion order. Shared by the writer's tests and (#941 Task 3) the\n * derivation path, so the hash is computed identically everywhere.\n */\nexport async function computeAggregateHash(\n collections: Record<string, SchemaManifestEntry>,\n): Promise<string> {\n return sha256Hex(canonicalJson(collections))\n}\n","/**\n * Derive the pod-wide {@link SchemaManifest} from the per-collection\n * `_schemas/<collection>` records — the source of truth (#941 Task 3).\n *\n * The manifest is an INDEX, never a cache with independent state: every\n * field in a {@link SchemaManifestEntry} is a direct projection of the\n * matching `PersistedSchemaEnvelope` (`hash` → `contentHash`, `fieldIds` →\n * `fieldIds`, `generation` → `generation`, falling back to the live fence's\n * `currentSchemaVersion` for a legacy pre-#946 envelope that never got a\n * generation stamp). Re-running this function against the same stored state\n * always produces the same manifest — that's what makes round-trip identity\n * (AC #2: dump → restore → re-derive matches the original) hold for free,\n * with no special-cased restore logic.\n *\n * A collection whose `_schemas/<collection>` envelope decrypts successfully\n * but has no derivable content (`hash === null` — a stub envelope for a\n * non-Zod validator) is legitimately omitted from the index: there is no\n * content hash to bind.\n *\n * ## Scoped principals: \"cannot decrypt\" is NOT \"doesn't exist\"\n *\n * A `_schemas/<collection>` envelope is encrypted under **that data\n * collection's own DEK** — the same key its records use — NOT a shared\n * `_schemas`-wide key. In a team vault, a collection-scoped grantee (e.g.\n * `grant(..., { role: 'operator', permissions: { invoices: 'rw' } })`) holds\n * only the DEKs their `permissions` name, plus every system-prefixed (`_*`)\n * collection's DEK — `_manifest` included, by `grant()`'s \"propagate system\n * collections to every role\" rule (`keyring.ts`). So a member scoped to\n * `invoices` CAN decrypt `_manifest/schema` (the pod-wide index) but CANNOT\n * decrypt a sibling's `_schemas/customers` envelope — even though that\n * envelope is right there in `store.list(vault, SCHEMAS_COLLECTION)`.\n *\n * `lookupDEK` (the {@link LookupDEK} passed in) reflects this: it returns\n * `undefined` for a collection name whose DEK the caller does not hold —\n * deliberately NEVER minting a fresh one (see the module doc on\n * `LookupDEK` for why). This function distinguishes that case\n * (`undecodableCollections`) from \"the schema envelope legitimately has no\n * derivable content\" (`hash === null`) — the caller (`sync.ts`) MUST treat\n * an incomplete view differently: writing a manifest derived from a\n * partial view would silently drop every collection this principal can't\n * see. See `sync.ts`'s module doc for how the sync path handles this.\n *\n * @module\n */\n\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\nimport { loadFence } from '../schema-update/fence.js'\nimport { loadPersistedSchema, SCHEMAS_COLLECTION } from '../persisted-schemas/storage.js'\nimport { computeAggregateHash } from './storage.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { SchemaManifest, SchemaManifestEntry } from './types.js'\n\n/**\n * A NON-MINTING DEK lookup: returns the collection's DEK if the caller\n * already holds it, `undefined` otherwise. Deliberately distinct from\n * `storage.ts`'s `GetManifestDEK` (which mints+persists a fresh DEK for an\n * absent collection — correct for a caller about to WRITE that collection,\n * e.g. `_manifest` itself). `deriveSchemaManifest` only ever READS sibling\n * collections it never created and has no business minting keys for — an\n * absent DEK here means \"not my collection to see,\" never \"new collection\n * that needs a key.\" Minting here would be worse than a no-op: it would\n * silently persist a garbage DEK into the caller's OWN `_keyring/<user>`\n * file (via `ensureCollectionDEK`'s `persistKeyring` side effect) that\n * still can't decrypt anything — see `sync.ts` / `with-pod/open.ts`'s\n * fix notes (#941 review).\n */\nexport type LookupDEK = (collectionName: string) => Promise<EnclaveKey | undefined>\n\nexport interface DeriveSchemaManifestResult {\n /** The derived manifest — an index over every collection this principal could decrypt. */\n readonly manifest: SchemaManifest\n /**\n * Names present in `_schemas` (per `store.list`) whose envelope this\n * principal could NOT decrypt — either no DEK held for that collection,\n * or the DEK held failed to decrypt/parse it (treated the same: the\n * caller cannot verify what's there, so it cannot safely be omitted or\n * asserted). Empty for a principal with full visibility (typically the\n * owner/admin/custodian). Non-empty means `manifest.collections` is\n * DEFINITELY INCOMPLETE relative to the pod's true collection set —\n * see `sync.ts` for why that must gate whether the manifest gets written.\n */\n readonly undecodableCollections: readonly string[]\n}\n\n/**\n * Read the fence generation + every `_schemas/<collection>` envelope this\n * principal can decrypt, and project them into a fresh {@link SchemaManifest}.\n * `lookupDEK` is called once per collection found under `_schemas` (never\n * mints — see {@link LookupDEK}). Names whose DEK isn't held, or whose\n * envelope fails to decrypt/parse despite holding a DEK, are reported via\n * `undecodableCollections` rather than silently dropped from the result.\n */\nexport async function deriveSchemaManifest(\n store: NoydbStore,\n vault: string,\n lookupDEK: LookupDEK,\n): Promise<DeriveSchemaManifestResult> {\n const fence = await loadFence(store, vault)\n const collectionNames = await store.list(vault, SCHEMAS_COLLECTION)\n\n const collections: Record<string, SchemaManifestEntry> = {}\n const undecodableCollections: string[] = []\n for (const name of collectionNames) {\n const dek = await lookupDEK(name)\n if (dek === undefined) {\n undecodableCollections.push(name) // present in _schemas, but not decodable by this principal\n continue\n }\n\n const payload = await loadPersistedSchema(store, vault, name, dek)\n if (!payload) {\n // Held a DEK but still couldn't decrypt/parse — cannot distinguish\n // \"wrong key after all\" from real corruption from here; treat as\n // undecodable (never silently drop) rather than \"no content.\"\n undecodableCollections.push(name)\n continue\n }\n if (payload.hash === null) continue // legitimately no derivable content (stub envelope)\n\n const entry: SchemaManifestEntry = {\n generation: payload.generation ?? fence.currentSchemaVersion,\n contentHash: payload.hash,\n }\n collections[name] = payload.fieldIds !== undefined ? { ...entry, fieldIds: payload.fieldIds } : entry\n }\n\n const aggregateHash = await computeAggregateHash(collections)\n const manifest: SchemaManifest = { v: 1, kind: 'schema', generation: fence.currentSchemaVersion, collections, aggregateHash }\n return { manifest, undecodableCollections }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDO,IAAM,4BAA4B;;;ACAzC,eAAsB,wBACpB,OACA,OACA,QAC2C;AAC3C,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,qBAAqB,yBAAyB;AACtF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,MAAM,MAAM,OAAO,mBAAmB;AAC5C,MAAI;AACF,UAAM,YAAY,MAAM,iBAAiB,EAAE,YAAY,qBAAqB,IAAI,0BAA0B,GAAG,UAAU,GAAG;AAC1H,UAAM,SAAS,KAAK,MAAM,SAAS;AACnC,QAAI,OAAO,MAAM,KAAK,OAAO,SAAS,SAAU,QAAO;AACvD,WAAO,EAAE,SAAS,SAAS,IAAI,UAAU,OAAO;AAAA,EAClD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAsB,mBACpB,OACA,OACA,UACA,iBACA,QACe;AACf,QAAM,MAAM,MAAM,OAAO,mBAAmB;AAC5C,QAAM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