@noy-db/hub 0.3.0-pre.11 → 0.3.0-pre.13
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.
- package/dist/aggregate/index.js +4 -4
- package/dist/api-ZGS6LCOF.js +20 -0
- package/dist/as/index.js +11 -11
- package/dist/attestation/index.js +18 -18
- package/dist/{backup-XA5STIYQ.js → backup-BJ57IKAO.js} +28 -11
- package/dist/backup-BJ57IKAO.js.map +1 -0
- package/dist/blobs/index.js +12 -10
- package/dist/blobs/index.js.map +1 -1
- package/dist/broker/index.js +12 -12
- package/dist/bundle/index.js +25 -22
- package/dist/bundle/index.js.map +1 -1
- package/dist/by/index.js +2 -2
- package/dist/cargo/index.js +22 -22
- package/dist/{chunk-WGV4CUZT.js → chunk-2NVOWNI3.js} +4 -4
- package/dist/{chunk-WGV4CUZT.js.map → chunk-2NVOWNI3.js.map} +1 -1
- package/dist/{chunk-OFJ5GPNA.js → chunk-3B5VVCNY.js} +2 -2
- package/dist/{chunk-KPGX66PM.js → chunk-3LQ2YKO4.js} +2 -2
- package/dist/{chunk-D26JB3LZ.js → chunk-3QCRBHCY.js} +2 -2
- package/dist/{chunk-H6CZSDWK.js → chunk-454JXE57.js} +3 -3
- package/dist/{chunk-H6CZSDWK.js.map → chunk-454JXE57.js.map} +1 -1
- package/dist/{chunk-DGH65E7Q.js → chunk-4CTHCN4J.js} +24 -10
- package/dist/chunk-4CTHCN4J.js.map +1 -0
- package/dist/{chunk-4N5QFSNQ.js → chunk-4JBYV75E.js} +5 -5
- package/dist/{chunk-UTLEAJXC.js → chunk-4NXKCLLQ.js} +2 -2
- package/dist/{chunk-ARSAMO24.js → chunk-4VNQOLML.js} +2 -2
- package/dist/{chunk-X6CMGUAG.js → chunk-5M5DVGV7.js} +2 -2
- package/dist/{chunk-DJ3VKYFA.js → chunk-5O3XF4DV.js} +4 -4
- package/dist/chunk-5O3XF4DV.js.map +1 -0
- package/dist/{chunk-XHV25KBM.js → chunk-5YOLBEQ6.js} +2 -2
- package/dist/{chunk-CB25ONKC.js → chunk-6CRIV7DE.js} +2 -2
- package/dist/{chunk-BE7N3AXA.js → chunk-6JTIAGHD.js} +3 -3
- package/dist/{chunk-JOQ53DMI.js → chunk-6QTNZJBS.js} +3 -3
- package/dist/{chunk-BZO4WCJI.js → chunk-6T2SCQRU.js} +4 -4
- package/dist/{chunk-FQQF23MC.js → chunk-7DSTRQIJ.js} +2 -2
- package/dist/{chunk-IP2QBAGS.js → chunk-AUSTCW2X.js} +10 -10
- package/dist/{chunk-A2Y6YFVN.js → chunk-B3HJYUOF.js} +2 -2
- package/dist/{chunk-SRVQHVNX.js → chunk-BDVFPG6Y.js} +5 -5
- package/dist/{chunk-FH542DDY.js → chunk-BIOUI4HL.js} +50 -1
- package/dist/chunk-BIOUI4HL.js.map +1 -0
- package/dist/{chunk-YXOUQ2H7.js → chunk-CAF6WOK7.js} +2 -2
- package/dist/{chunk-H6HM6CVR.js → chunk-CDUQTA3Z.js} +114 -12
- package/dist/chunk-CDUQTA3Z.js.map +1 -0
- package/dist/{chunk-HUS3J5WM.js → chunk-CIE2BASH.js} +2 -2
- package/dist/{chunk-DIRRS7WP.js → chunk-CRI4OUV4.js} +2 -2
- package/dist/{chunk-FXK4X4BL.js → chunk-DLG74CNB.js} +4 -4
- package/dist/{chunk-WTUNZACT.js → chunk-E5ZQT5KX.js} +2 -2
- package/dist/{chunk-DMFNPHCX.js → chunk-EQO2UVP4.js} +6 -6
- package/dist/{chunk-MCEKIAO4.js → chunk-ERJ7FU55.js} +3 -3
- package/dist/{chunk-6QILBDZU.js → chunk-EVVGJDRQ.js} +3 -3
- package/dist/{chunk-7VSGW5KJ.js → chunk-EVX47VBM.js} +2 -2
- package/dist/{chunk-D3EFFFOL.js → chunk-EXK7QRWF.js} +5 -5
- package/dist/{chunk-5JB73NMC.js → chunk-EYZ6IQ6X.js} +5 -5
- package/dist/{chunk-BCYQA5BK.js → chunk-F64IRYG3.js} +2 -2
- package/dist/{chunk-K62IUKOD.js → chunk-FHS2HQSH.js} +5 -5
- package/dist/{chunk-2JMMY7HZ.js → chunk-FM3G3NOY.js} +27 -9
- package/dist/chunk-FM3G3NOY.js.map +1 -0
- package/dist/{chunk-67TNU77I.js → chunk-FUG4SFN3.js} +2 -2
- package/dist/{chunk-ZP5PL65C.js → chunk-GKEWXIV5.js} +2 -2
- package/dist/{chunk-RKRGDAS7.js → chunk-GTGPO5KW.js} +5 -5
- package/dist/{chunk-MSPNM2OM.js → chunk-HB3RFQSC.js} +3 -3
- package/dist/{chunk-W5D62AQD.js → chunk-HDMEGAQE.js} +20 -7
- package/dist/chunk-HDMEGAQE.js.map +1 -0
- package/dist/chunk-HDQIIUPH.js +135 -0
- package/dist/chunk-HDQIIUPH.js.map +1 -0
- package/dist/{chunk-7QIXUSDQ.js → chunk-HTJQYHZP.js} +15 -12
- package/dist/chunk-HTJQYHZP.js.map +1 -0
- package/dist/{chunk-OOLO4LQG.js → chunk-I6GALP6E.js} +6 -6
- package/dist/{chunk-57V5S7PW.js → chunk-IL6POWCW.js} +6 -6
- package/dist/{chunk-7NS43EXZ.js → chunk-IU6SNYX6.js} +5 -5
- package/dist/{chunk-5ZOSG3RJ.js → chunk-J2ZX2XUV.js} +5 -5
- package/dist/{chunk-L2SNBIV7.js → chunk-JIF24JPM.js} +57 -15
- package/dist/chunk-JIF24JPM.js.map +1 -0
- package/dist/{chunk-SYMS4546.js → chunk-JKJOGPZN.js} +2 -2
- package/dist/{chunk-CKZW6P5V.js → chunk-JNAI2HN2.js} +1 -1
- package/dist/chunk-JNAI2HN2.js.map +1 -0
- package/dist/{chunk-AWB5JZW6.js → chunk-JZUV47FZ.js} +2 -2
- package/dist/{chunk-ODJWBC5I.js → chunk-K5IMOGHB.js} +2 -2
- package/dist/{chunk-3G4KMVUN.js → chunk-KSKBRKGJ.js} +3 -3
- package/dist/{chunk-HFJIGWJC.js → chunk-LASZKVMO.js} +3 -3
- package/dist/{chunk-IGJHJYM6.js → chunk-LXEXBTKL.js} +4 -4
- package/dist/{chunk-3CNQ7FQ3.js → chunk-M4CV6BRT.js} +119 -25
- package/dist/chunk-M4CV6BRT.js.map +1 -0
- package/dist/{chunk-H44ZE4IE.js → chunk-MEFJPTZ4.js} +33 -17
- package/dist/chunk-MEFJPTZ4.js.map +1 -0
- package/dist/{chunk-PR5LC5YX.js → chunk-MV43JSJF.js} +4 -4
- package/dist/{chunk-ELNBMFOS.js → chunk-NJ4EOKMB.js} +4 -4
- package/dist/{chunk-PXWVF7MC.js → chunk-NR5LT5RY.js} +7 -7
- package/dist/{chunk-QYPKGVT4.js → chunk-NWSGI5C7.js} +3 -3
- package/dist/{chunk-P5RY4ZWD.js → chunk-OSDB5WW3.js} +92 -15
- package/dist/chunk-OSDB5WW3.js.map +1 -0
- package/dist/chunk-PN2XMATY.js +37 -0
- package/dist/chunk-PN2XMATY.js.map +1 -0
- package/dist/{chunk-25NDNMQ7.js → chunk-Q5VNKNE5.js} +3 -3
- package/dist/{chunk-CIKY6I4W.js → chunk-QLWMEXCT.js} +2 -2
- package/dist/{chunk-VA4ZWLFY.js → chunk-QRB7NAOJ.js} +2 -2
- package/dist/{chunk-3MSQLQNZ.js → chunk-R4ROFEYC.js} +2 -2
- package/dist/{chunk-BEIRE5K4.js → chunk-RCVJZMFE.js} +4 -4
- package/dist/{chunk-VR24ILCR.js → chunk-RIX4V2TB.js} +3 -3
- package/dist/{chunk-Q3XSMOZM.js → chunk-RYCTDFUX.js} +2 -2
- package/dist/{chunk-7E67FJ33.js → chunk-RZ5SVOYR.js} +2 -2
- package/dist/{chunk-IDIV5NVH.js → chunk-SLFHQTTW.js} +5 -5
- package/dist/chunk-SNZ6URZZ.js +2782 -0
- package/dist/chunk-SNZ6URZZ.js.map +1 -0
- package/dist/{chunk-C3YH34IL.js → chunk-T2FFWNPK.js} +3 -3
- package/dist/{chunk-O2DYPAZY.js → chunk-UNFPPVNI.js} +2 -2
- package/dist/{chunk-MELR46EF.js → chunk-VFUPHI2Z.js} +63 -10
- package/dist/chunk-VFUPHI2Z.js.map +1 -0
- package/dist/{chunk-GA2QHD6P.js → chunk-VLFCJYTL.js} +9 -9
- package/dist/{chunk-YSXEFGND.js → chunk-VN3DBQAU.js} +2 -2
- package/dist/{chunk-C7NTK5I3.js → chunk-VZRODIM3.js} +4 -4
- package/dist/{chunk-QLLKLFE2.js → chunk-W22IKJE2.js} +2 -2
- package/dist/{chunk-5XIPOCQC.js → chunk-X3YYQWOQ.js} +3 -3
- package/dist/{chunk-A2QF4JUE.js → chunk-X7QBD67R.js} +625 -293
- package/dist/chunk-X7QBD67R.js.map +1 -0
- package/dist/{chunk-QQJXBZCO.js → chunk-XDYREZWE.js} +82 -10
- package/dist/chunk-XDYREZWE.js.map +1 -0
- package/dist/{chunk-OEAATWH5.js → chunk-XWZVFISC.js} +40 -6
- package/dist/{chunk-OEAATWH5.js.map → chunk-XWZVFISC.js.map} +1 -1
- package/dist/{chunk-XFXUTFWQ.js → chunk-YFXZEAYK.js} +6 -6
- package/dist/{chunk-7ITPJFGC.js → chunk-ZAJAVEXY.js} +2 -2
- package/dist/{chunk-4R4Q64W5.js → chunk-ZICD77GM.js} +2 -2
- package/dist/{chunk-45ZZLTFH.js → chunk-ZJ2AK4V7.js} +2 -2
- package/dist/{chunk-UFILRICG.js → chunk-ZUODRVHY.js} +2 -2
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-LQWWQNIJ.js → classified-marker-CZKA6ITE.js} +8 -4
- package/dist/classified-marker-CZKA6ITE.js.map +1 -0
- package/dist/collection-facade-TLWIPI76.js +44 -0
- package/dist/{computed-W6MVAMWZ.js → computed-ZIQTYTDI.js} +3 -3
- package/dist/consent/index.js +9 -9
- package/dist/{dead-filter-4KXZEB3X.js → dead-filter-ESOBZZP5.js} +2 -2
- package/dist/delegation-W7ZV2322.js +25 -0
- package/dist/derivations/index.js +12 -12
- package/dist/derive-H2BJTLUI.js +21 -0
- package/dist/{enclave-VXAQD4XJ.js → enclave-AP3I5W7O.js} +15 -9
- package/dist/executor-KGWTNEQD.js +9 -0
- package/dist/executor-OVEXR6RT.js +9 -0
- package/dist/executor-UNEH5ZYH.js +25 -0
- package/dist/export-accessible-PCMXSUZS.js +23 -0
- package/dist/extract-partition-SWHFSYJO.js +38 -0
- package/dist/{fanout-sidecar-CKYFH33E.js → fanout-sidecar-A765THMX.js} +9 -9
- package/dist/find-N6345CNT.js +11 -0
- package/dist/forget/index.js +9 -9
- package/dist/guards/index.js +3 -3
- package/dist/history/index.js +14 -11
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -14
- package/dist/index.d.ts +5 -1
- package/dist/index.js +108 -89
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +5 -5
- package/dist/indexing/index.js.map +1 -1
- package/dist/issue-5OKB6I2R.js +19 -0
- package/dist/kernel/best-effort-revert.d.ts +52 -0
- package/dist/kernel/collection-config.d.ts +28 -0
- package/dist/kernel/collection.d.ts +49 -32
- package/dist/kernel/enclave/classify/verify.d.ts +3 -0
- package/dist/kernel/enclave/index.d.ts +2 -1
- package/dist/kernel/enclave/record-keys/deterministic.d.ts +1 -0
- package/dist/kernel/enclave/record-keys/lifecycle.d.ts +50 -0
- package/dist/kernel/enclave/record-keys/record-codec.d.ts +27 -0
- package/dist/kernel/errors.d.ts +75 -1
- package/dist/kernel/lazy-count.d.ts +13 -0
- package/dist/kernel/noydb.d.ts +8 -0
- package/dist/kernel/tier-visibility.d.ts +54 -0
- package/dist/kernel/types.d.ts +92 -0
- package/dist/kernel/vault.d.ts +23 -6
- package/dist/kernel/via/dispatch.d.ts +10 -0
- package/dist/kernel/via/graph.d.ts +2 -1
- package/dist/{ledger-FU6GH5EH.js → ledger-GFBKVPV4.js} +11 -11
- package/dist/legacy/bundle.d.ts +1 -1
- package/dist/liberate-3VDOT4KO.js +24 -0
- package/dist/{link-set-MNADSH5M.js → link-set-Z7Q2ASFX.js} +11 -11
- package/dist/materialized-views/index.js +18 -18
- package/dist/noydb-ZCJOYBDI.js +68 -0
- package/dist/on/index.js +9 -9
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +12 -12
- package/dist/pod/index.js +11 -11
- package/dist/{policy-JTFOPPUU.js → policy-Z3RUAIY2.js} +5 -5
- package/dist/port/with/blob-strategy.d.ts +17 -0
- package/dist/port/with/lookup-strategy.d.ts +2 -1
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-HAWO3O7O.js → post-register-JTH76BLY.js} +12 -7
- package/dist/post-register-JTH76BLY.js.map +1 -0
- package/dist/{public-envelope-NJVB7LPA.js → public-envelope-B4KNWVUA.js} +4 -4
- package/dist/query/index.js +5 -5
- package/dist/register-VAHONCID.js +23 -0
- package/dist/registry-7MLVD3VO.js +19 -0
- package/dist/registry-EPKPD5SM.js +18 -0
- package/dist/registry-P5T7PS2U.js +9 -0
- package/dist/request-withdrawal-TI3A5WPS.js +31 -0
- package/dist/{reveal-BOY7XYFH.js → reveal-DIBHLUZX.js} +7 -7
- package/dist/reveal-DIBHLUZX.js.map +1 -0
- package/dist/revoke-FDRD6GRW.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/sealed-record/index.js +12 -12
- package/dist/{seed-4RRXT42N.js → seed-Q6M2IZFL.js} +11 -11
- package/dist/session/index.js +9 -9
- package/dist/shadow/index.js +2 -2
- package/dist/signer-MUWEIUI6.js +25 -0
- package/dist/snapshots/index.js +10 -10
- package/dist/stale-OSQ7J3AA.js +29 -0
- package/dist/storage-MVFCGEQE.js +23 -0
- package/dist/{store-coordination-provider-HPYVFJCV.js → store-coordination-provider-64OEZFGS.js} +3 -3
- package/dist/sync/index.js +9 -9
- package/dist/team/index.js +15 -15
- package/dist/tiers/index.js +14 -10
- package/dist/to/index.js +1 -1
- package/dist/tx/index.js +3 -3
- package/dist/util/index.js +1 -1
- package/dist/{verify-66RHOW7N.js → verify-ZASTRNPR.js} +9 -8
- package/dist/verify-ZASTRNPR.js.map +1 -0
- package/dist/via/lookup/registry.d.ts +9 -0
- package/dist/via/money/where.d.ts +27 -6
- package/dist/{walk-2RWEOCAS.js → walk-SVNDIZ62.js} +11 -11
- package/dist/with/index.js +11 -11
- package/dist/with-audit/forget/strategy.d.ts +22 -0
- package/dist/with-audit/tiers/index.d.ts +275 -3
- package/dist/with-audit/tiers/strategy.d.ts +5 -4
- package/dist/with-cargo/describe-extraction.d.ts +9 -1
- package/dist/with-cargo/extract-partition.d.ts +9 -1
- package/dist/with-cargo/walk-closure.d.ts +32 -3
- package/dist/with-commit/history/history.d.ts +46 -0
- package/dist/with-commit/history/ledger/store.d.ts +21 -0
- package/dist/with-commit/history/strategy.d.ts +10 -0
- package/dist/with-commit/history/time-machine.d.ts +23 -0
- package/dist/with-commit/tx/elevated-handle.d.ts +2 -1
- package/dist/with-commit/tx/transaction.d.ts +5 -0
- package/dist/with-formula/materialized-views/executor.d.ts +9 -0
- package/dist/with-formula/materialized-views/stale.d.ts +52 -1
- package/dist/with-lookup/embeddings/index.d.ts +1 -0
- package/dist/with-lookup/embeddings/vec-id.d.ts +47 -0
- package/dist/with-lookup/indexing/collection-facade.d.ts +38 -1
- package/dist/with-lookup/indexing/lazy-builder.d.ts +35 -2
- package/dist/with-lookup/indexing/persisted-indexes.d.ts +44 -1
- package/dist/with-lookup/search/collection-facade.d.ts +40 -0
- package/dist/with-lookup/search/persisted-index-store.d.ts +82 -2
- package/dist/with-lookup/search/strategy.d.ts +4 -0
- package/dist/with-party/team/sync.d.ts +9 -0
- package/dist/with-shape/blobs/blob-intent.d.ts +153 -0
- package/dist/with-shape/blobs/blob-set.d.ts +949 -5
- package/dist/with-shape/satellites/fanout.d.ts +5 -4
- package/dist/with-shape/satellites/migrate-cek.d.ts +26 -0
- package/dist/with-shape/satellites/types.d.ts +11 -0
- package/dist/withdraw-accessible-WZIEVWSR.js +28 -0
- package/package.json +3 -3
- package/dist/api-YGMINAET.js +0 -20
- package/dist/backup-XA5STIYQ.js.map +0 -1
- package/dist/chunk-2JMMY7HZ.js.map +0 -1
- package/dist/chunk-3CNQ7FQ3.js.map +0 -1
- package/dist/chunk-7QIXUSDQ.js.map +0 -1
- package/dist/chunk-A2QF4JUE.js.map +0 -1
- package/dist/chunk-AOVDSIL3.js +0 -1221
- package/dist/chunk-AOVDSIL3.js.map +0 -1
- package/dist/chunk-CKZW6P5V.js.map +0 -1
- package/dist/chunk-DGH65E7Q.js.map +0 -1
- package/dist/chunk-DJ3VKYFA.js.map +0 -1
- package/dist/chunk-FH542DDY.js.map +0 -1
- package/dist/chunk-H44ZE4IE.js.map +0 -1
- package/dist/chunk-H6HM6CVR.js.map +0 -1
- package/dist/chunk-L2SNBIV7.js.map +0 -1
- package/dist/chunk-MELR46EF.js.map +0 -1
- package/dist/chunk-P5RY4ZWD.js.map +0 -1
- package/dist/chunk-QQJXBZCO.js.map +0 -1
- package/dist/chunk-TPH5EO6L.js +0 -54
- package/dist/chunk-TPH5EO6L.js.map +0 -1
- package/dist/chunk-W5D62AQD.js.map +0 -1
- package/dist/classified-marker-LQWWQNIJ.js.map +0 -1
- package/dist/collection-facade-YE2O4J4O.js +0 -39
- package/dist/delegation-OPUU3R2E.js +0 -25
- package/dist/derive-BGUHU663.js +0 -21
- package/dist/executor-GTVSUUBX.js +0 -25
- package/dist/executor-GZWMTOXB.js +0 -9
- package/dist/executor-XXGS4S3K.js +0 -9
- package/dist/export-accessible-BMULIOYB.js +0 -23
- package/dist/extract-partition-JUQTWDXR.js +0 -36
- package/dist/find-XRGCNGNN.js +0 -11
- package/dist/issue-UB6AA5M6.js +0 -19
- package/dist/liberate-YUN7W5QG.js +0 -24
- package/dist/noydb-6JLBZU4U.js +0 -67
- package/dist/post-register-HAWO3O7O.js.map +0 -1
- package/dist/register-VCKOBWKT.js +0 -23
- package/dist/registry-72UKJ2L4.js +0 -9
- package/dist/registry-BZFLJNEH.js +0 -18
- package/dist/registry-YJEYSYI5.js +0 -19
- package/dist/request-withdrawal-6MJRMFHF.js +0 -31
- package/dist/reveal-BOY7XYFH.js.map +0 -1
- package/dist/revoke-4KUNSVJC.js +0 -24
- package/dist/signer-DDDXP5JD.js +0 -25
- package/dist/stale-NXPT56JA.js +0 -14
- package/dist/storage-IR6EEAV2.js +0 -23
- package/dist/verify-66RHOW7N.js.map +0 -1
- package/dist/withdraw-accessible-CLMZEHQT.js +0 -28
- /package/dist/{api-YGMINAET.js.map → api-ZGS6LCOF.js.map} +0 -0
- /package/dist/{chunk-OFJ5GPNA.js.map → chunk-3B5VVCNY.js.map} +0 -0
- /package/dist/{chunk-KPGX66PM.js.map → chunk-3LQ2YKO4.js.map} +0 -0
- /package/dist/{chunk-D26JB3LZ.js.map → chunk-3QCRBHCY.js.map} +0 -0
- /package/dist/{chunk-4N5QFSNQ.js.map → chunk-4JBYV75E.js.map} +0 -0
- /package/dist/{chunk-UTLEAJXC.js.map → chunk-4NXKCLLQ.js.map} +0 -0
- /package/dist/{chunk-ARSAMO24.js.map → chunk-4VNQOLML.js.map} +0 -0
- /package/dist/{chunk-X6CMGUAG.js.map → chunk-5M5DVGV7.js.map} +0 -0
- /package/dist/{chunk-XHV25KBM.js.map → chunk-5YOLBEQ6.js.map} +0 -0
- /package/dist/{chunk-CB25ONKC.js.map → chunk-6CRIV7DE.js.map} +0 -0
- /package/dist/{chunk-BE7N3AXA.js.map → chunk-6JTIAGHD.js.map} +0 -0
- /package/dist/{chunk-JOQ53DMI.js.map → chunk-6QTNZJBS.js.map} +0 -0
- /package/dist/{chunk-BZO4WCJI.js.map → chunk-6T2SCQRU.js.map} +0 -0
- /package/dist/{chunk-FQQF23MC.js.map → chunk-7DSTRQIJ.js.map} +0 -0
- /package/dist/{chunk-IP2QBAGS.js.map → chunk-AUSTCW2X.js.map} +0 -0
- /package/dist/{chunk-A2Y6YFVN.js.map → chunk-B3HJYUOF.js.map} +0 -0
- /package/dist/{chunk-SRVQHVNX.js.map → chunk-BDVFPG6Y.js.map} +0 -0
- /package/dist/{chunk-YXOUQ2H7.js.map → chunk-CAF6WOK7.js.map} +0 -0
- /package/dist/{chunk-HUS3J5WM.js.map → chunk-CIE2BASH.js.map} +0 -0
- /package/dist/{chunk-DIRRS7WP.js.map → chunk-CRI4OUV4.js.map} +0 -0
- /package/dist/{chunk-FXK4X4BL.js.map → chunk-DLG74CNB.js.map} +0 -0
- /package/dist/{chunk-WTUNZACT.js.map → chunk-E5ZQT5KX.js.map} +0 -0
- /package/dist/{chunk-DMFNPHCX.js.map → chunk-EQO2UVP4.js.map} +0 -0
- /package/dist/{chunk-MCEKIAO4.js.map → chunk-ERJ7FU55.js.map} +0 -0
- /package/dist/{chunk-6QILBDZU.js.map → chunk-EVVGJDRQ.js.map} +0 -0
- /package/dist/{chunk-7VSGW5KJ.js.map → chunk-EVX47VBM.js.map} +0 -0
- /package/dist/{chunk-D3EFFFOL.js.map → chunk-EXK7QRWF.js.map} +0 -0
- /package/dist/{chunk-5JB73NMC.js.map → chunk-EYZ6IQ6X.js.map} +0 -0
- /package/dist/{chunk-BCYQA5BK.js.map → chunk-F64IRYG3.js.map} +0 -0
- /package/dist/{chunk-K62IUKOD.js.map → chunk-FHS2HQSH.js.map} +0 -0
- /package/dist/{chunk-67TNU77I.js.map → chunk-FUG4SFN3.js.map} +0 -0
- /package/dist/{chunk-ZP5PL65C.js.map → chunk-GKEWXIV5.js.map} +0 -0
- /package/dist/{chunk-RKRGDAS7.js.map → chunk-GTGPO5KW.js.map} +0 -0
- /package/dist/{chunk-MSPNM2OM.js.map → chunk-HB3RFQSC.js.map} +0 -0
- /package/dist/{chunk-OOLO4LQG.js.map → chunk-I6GALP6E.js.map} +0 -0
- /package/dist/{chunk-57V5S7PW.js.map → chunk-IL6POWCW.js.map} +0 -0
- /package/dist/{chunk-7NS43EXZ.js.map → chunk-IU6SNYX6.js.map} +0 -0
- /package/dist/{chunk-5ZOSG3RJ.js.map → chunk-J2ZX2XUV.js.map} +0 -0
- /package/dist/{chunk-SYMS4546.js.map → chunk-JKJOGPZN.js.map} +0 -0
- /package/dist/{chunk-AWB5JZW6.js.map → chunk-JZUV47FZ.js.map} +0 -0
- /package/dist/{chunk-ODJWBC5I.js.map → chunk-K5IMOGHB.js.map} +0 -0
- /package/dist/{chunk-3G4KMVUN.js.map → chunk-KSKBRKGJ.js.map} +0 -0
- /package/dist/{chunk-HFJIGWJC.js.map → chunk-LASZKVMO.js.map} +0 -0
- /package/dist/{chunk-IGJHJYM6.js.map → chunk-LXEXBTKL.js.map} +0 -0
- /package/dist/{chunk-PR5LC5YX.js.map → chunk-MV43JSJF.js.map} +0 -0
- /package/dist/{chunk-ELNBMFOS.js.map → chunk-NJ4EOKMB.js.map} +0 -0
- /package/dist/{chunk-PXWVF7MC.js.map → chunk-NR5LT5RY.js.map} +0 -0
- /package/dist/{chunk-QYPKGVT4.js.map → chunk-NWSGI5C7.js.map} +0 -0
- /package/dist/{chunk-25NDNMQ7.js.map → chunk-Q5VNKNE5.js.map} +0 -0
- /package/dist/{chunk-CIKY6I4W.js.map → chunk-QLWMEXCT.js.map} +0 -0
- /package/dist/{chunk-VA4ZWLFY.js.map → chunk-QRB7NAOJ.js.map} +0 -0
- /package/dist/{chunk-3MSQLQNZ.js.map → chunk-R4ROFEYC.js.map} +0 -0
- /package/dist/{chunk-BEIRE5K4.js.map → chunk-RCVJZMFE.js.map} +0 -0
- /package/dist/{chunk-VR24ILCR.js.map → chunk-RIX4V2TB.js.map} +0 -0
- /package/dist/{chunk-Q3XSMOZM.js.map → chunk-RYCTDFUX.js.map} +0 -0
- /package/dist/{chunk-7E67FJ33.js.map → chunk-RZ5SVOYR.js.map} +0 -0
- /package/dist/{chunk-IDIV5NVH.js.map → chunk-SLFHQTTW.js.map} +0 -0
- /package/dist/{chunk-C3YH34IL.js.map → chunk-T2FFWNPK.js.map} +0 -0
- /package/dist/{chunk-O2DYPAZY.js.map → chunk-UNFPPVNI.js.map} +0 -0
- /package/dist/{chunk-GA2QHD6P.js.map → chunk-VLFCJYTL.js.map} +0 -0
- /package/dist/{chunk-YSXEFGND.js.map → chunk-VN3DBQAU.js.map} +0 -0
- /package/dist/{chunk-C7NTK5I3.js.map → chunk-VZRODIM3.js.map} +0 -0
- /package/dist/{chunk-QLLKLFE2.js.map → chunk-W22IKJE2.js.map} +0 -0
- /package/dist/{chunk-5XIPOCQC.js.map → chunk-X3YYQWOQ.js.map} +0 -0
- /package/dist/{chunk-XFXUTFWQ.js.map → chunk-YFXZEAYK.js.map} +0 -0
- /package/dist/{chunk-7ITPJFGC.js.map → chunk-ZAJAVEXY.js.map} +0 -0
- /package/dist/{chunk-4R4Q64W5.js.map → chunk-ZICD77GM.js.map} +0 -0
- /package/dist/{chunk-45ZZLTFH.js.map → chunk-ZJ2AK4V7.js.map} +0 -0
- /package/dist/{chunk-UFILRICG.js.map → chunk-ZUODRVHY.js.map} +0 -0
- /package/dist/{collection-facade-YE2O4J4O.js.map → collection-facade-TLWIPI76.js.map} +0 -0
- /package/dist/{computed-W6MVAMWZ.js.map → computed-ZIQTYTDI.js.map} +0 -0
- /package/dist/{dead-filter-4KXZEB3X.js.map → dead-filter-ESOBZZP5.js.map} +0 -0
- /package/dist/{delegation-OPUU3R2E.js.map → delegation-W7ZV2322.js.map} +0 -0
- /package/dist/{derive-BGUHU663.js.map → derive-H2BJTLUI.js.map} +0 -0
- /package/dist/{enclave-VXAQD4XJ.js.map → enclave-AP3I5W7O.js.map} +0 -0
- /package/dist/{executor-GTVSUUBX.js.map → executor-KGWTNEQD.js.map} +0 -0
- /package/dist/{executor-GZWMTOXB.js.map → executor-OVEXR6RT.js.map} +0 -0
- /package/dist/{executor-XXGS4S3K.js.map → executor-UNEH5ZYH.js.map} +0 -0
- /package/dist/{export-accessible-BMULIOYB.js.map → export-accessible-PCMXSUZS.js.map} +0 -0
- /package/dist/{extract-partition-JUQTWDXR.js.map → extract-partition-SWHFSYJO.js.map} +0 -0
- /package/dist/{fanout-sidecar-CKYFH33E.js.map → fanout-sidecar-A765THMX.js.map} +0 -0
- /package/dist/{find-XRGCNGNN.js.map → find-N6345CNT.js.map} +0 -0
- /package/dist/{issue-UB6AA5M6.js.map → issue-5OKB6I2R.js.map} +0 -0
- /package/dist/{ledger-FU6GH5EH.js.map → ledger-GFBKVPV4.js.map} +0 -0
- /package/dist/{liberate-YUN7W5QG.js.map → liberate-3VDOT4KO.js.map} +0 -0
- /package/dist/{link-set-MNADSH5M.js.map → link-set-Z7Q2ASFX.js.map} +0 -0
- /package/dist/{noydb-6JLBZU4U.js.map → noydb-ZCJOYBDI.js.map} +0 -0
- /package/dist/{policy-JTFOPPUU.js.map → policy-Z3RUAIY2.js.map} +0 -0
- /package/dist/{public-envelope-NJVB7LPA.js.map → public-envelope-B4KNWVUA.js.map} +0 -0
- /package/dist/{register-VCKOBWKT.js.map → register-VAHONCID.js.map} +0 -0
- /package/dist/{registry-72UKJ2L4.js.map → registry-7MLVD3VO.js.map} +0 -0
- /package/dist/{registry-BZFLJNEH.js.map → registry-EPKPD5SM.js.map} +0 -0
- /package/dist/{registry-YJEYSYI5.js.map → registry-P5T7PS2U.js.map} +0 -0
- /package/dist/{request-withdrawal-6MJRMFHF.js.map → request-withdrawal-TI3A5WPS.js.map} +0 -0
- /package/dist/{revoke-4KUNSVJC.js.map → revoke-FDRD6GRW.js.map} +0 -0
- /package/dist/{seed-4RRXT42N.js.map → seed-Q6M2IZFL.js.map} +0 -0
- /package/dist/{signer-DDDXP5JD.js.map → signer-MUWEIUI6.js.map} +0 -0
- /package/dist/{stale-NXPT56JA.js.map → stale-OSQ7J3AA.js.map} +0 -0
- /package/dist/{storage-IR6EEAV2.js.map → storage-MVFCGEQE.js.map} +0 -0
- /package/dist/{store-coordination-provider-HPYVFJCV.js.map → store-coordination-provider-64OEZFGS.js.map} +0 -0
- /package/dist/{walk-2RWEOCAS.js.map → walk-SVNDIZ62.js.map} +0 -0
- /package/dist/{withdraw-accessible-CLMZEHQT.js.map → withdraw-accessible-WZIEVWSR.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kernel/types.ts"],"sourcesContent":["/**\n * Core types — the {@link NoydbStore} interface, envelope format, roles, and\n * all configuration shapes consumed by {@link createNoydb}.\n *\n * ## What lives here\n *\n * - **{@link NoydbStore}** — the 6-method contract every backend must implement\n * (`get`, `put`, `delete`, `list`, `loadAll`, `saveAll`).\n * - **{@link EncryptedEnvelope}** — the wire format stored by backends:\n * `{ _noydb, _v, _ts, _iv, _data }`. Backends only ever see this shape.\n * - **{@link Role} / {@link Permission}** — the access-control vocabulary\n * (`owner`, `admin`, `operator`, `viewer`, `client`).\n * - **{@link NoydbOptions}** — the full configuration object passed to\n * {@link createNoydb}.\n *\n * ## Extending the store interface\n *\n * All optional store capabilities (`ping`, `listPage`, `listSince`,\n * `presencePublish`, `presenceSubscribe`, `listVaults`) are additive extensions\n * discovered via `'method' in store`. Implementing them unlocks features but\n * is never required — core always falls back to the 6-method baseline.\n *\n * @module\n */\n\nimport type { StandardSchemaV1 } from './schema.js'\nimport type { DeferredNumberingConfig } from '../with-commit/numbering/descriptor.js'\nimport type { SyncPolicy } from './sync-policy.js'\nimport type { BlobStrategy } from '../port/with/blob-strategy.js'\nimport type { ArchiveStrategy } from '../with-fork/archive/index.js'\nimport type { IndexStrategy } from '../with-lookup/indexing/strategy.js'\nimport type { AggregateStrategy } from '../with-lookup/aggregate/strategy.js'\nimport type { ConsentStrategy } from '../with-audit/consent/strategy.js'\nimport type { PeriodsStrategy } from '../with-audit/periods/strategy.js'\nimport type { ShadowStrategy } from '../with-fork/shadow/strategy.js'\nimport type { TxStrategy } from '../with-commit/tx/strategy.js'\nimport type { HistoryStrategy } from '../with-commit/history/strategy.js'\nimport type { ForgetStrategy } from '../with-audit/forget/strategy.js'\nimport type { SnapshotStrategy } from '../with-fork/snapshots/strategy.js'\nimport type { DerivationSkippedFrozen } from './via/dispatch.js'\nimport type { AttestationStrategy } from '../with-audit/attestation/strategy.js'\nimport type { ClassifiedStrategy } from '../port/with/classified-strategy.js'\nimport type { TiersStrategy } from '../with-audit/tiers/strategy.js'\nimport type { SealedRecordStrategy } from '../with-audit/sealed-record/strategy.js'\nimport type { PortabilityStrategy } from '../with-audit/portability/strategy.js'\nimport type { SequenceStrategy } from '../with-commit/sequence/strategy.js'\nimport type { CustodyStrategy } from '../with-party/custody/strategy.js'\nimport type { TeamStrategy } from '../port/with/team-strategy.js'\nimport type { BrokerStrategy } from '../port/with/broker-strategy.js'\nimport type { LazyStrategy } from '../port/with/lazy-strategy.js'\nimport type { SearchStrategy } from '../with-lookup/search/strategy.js'\nimport type { CargoStrategy } from '../with-cargo/strategy.js'\nimport type { Layer, I18nStrategy } from '../port/with/i18n-strategy.js'\nimport type { SessionStrategy } from '../with-party/session/strategy.js'\nimport type { SyncStrategy } from '../with-party/team/sync-strategy.js'\nimport type { GuardStrategyHandleAny } from '../with-audit/guards/types.js'\nimport type { DerivationStrategyHandle } from '../with-formula/derivations/types.js'\nimport type { UnlockedKeyring } from '../with-party/team/keyring.js'\nimport type { PassphrasePolicy } from './validation.js'\nimport type { PublicEnvelopeSchema } from '../with-party/directory/public-envelope/types.js'\nimport type { MaterializedViewStrategyHandle } from '../with-formula/materialized-views/types.js'\nimport type { OverlayedViewStrategyHandle } from '../with-formula/overlay-views/types.js'\nimport type { SealingKeyProvider, RecipientHint } from '../with-party/team/managed-passphrase.js'\nimport type { ShamirRecoveryProvider } from '../with-party/team/shamir-recovery-provider.js'\nimport type { ObjectProjection } from '../with-shape/blobs/object-projection.js'\nimport type { CoordinationProvider } from '../port/by/types.js'\nimport type { ScriptWarning } from '../port/with/i18n-strategy.js'\nimport type { ViaDescriptor } from './via/index.js'\nimport type { EnclaveKey } from './enclave/index.js'\n\n/** Format version for encrypted record envelopes. */\nexport const NOYDB_FORMAT_VERSION = 1 as const\n\n/** Format version for keyring files. */\nexport const NOYDB_KEYRING_VERSION = 1 as const\n\n/** Format version for backup files. */\nexport const NOYDB_BACKUP_VERSION = 1 as const\n\n/** Format version for sync metadata. */\nexport const NOYDB_SYNC_VERSION = 1 as const\n\n// ─── Roles & Permissions ───────────────────────────────────────────────\n\n/**\n * Access role assigned to a user within a vault.\n *\n * Roles control both the operations a user can perform and which DEKs\n * they receive in their keyring:\n *\n * | Role | Collections | Can grant/revoke | Can export |\n * |-------------|-----------------|:----------------:|:----------:|\n * | `owner` | all (rw) | Yes (all roles) | Yes |\n * | `admin` | all (rw) | Yes (≤ admin) | Yes |\n * | `custodian` | all (rw) | No (see below) | Yes |\n * | `operator` | explicit (rw) | No | ACL-scoped |\n * | `viewer` | all (ro) | No | Yes |\n * | `client` | explicit (ro) | No | ACL-scoped |\n *\n * **`custodian` (FR-6 sovereign custody).** Operationally admin-rank —\n * rw + access on every collection, receives all collection DEKs on grant\n * — but is *provably non-owning*: it CANNOT grant, revoke, rotate keys,\n * destructively withdraw/sever, or extract-and-sever a partition (rotate is\n * blocked in `rotateKeys`, sever in `withdrawAccessibleData`, and extract in\n * `extractPartition`). Only the (sealed Deed) **owner** may\n * mint or remove a custodian; an admin cannot. This is the inalienability\n * floor — a custodian can run the vault day-to-day yet never escalate to\n * the owner credential.\n */\nexport type Role = 'owner' | 'admin' | 'custodian' | 'operator' | 'viewer' | 'client'\n\n/**\n * Read-write or read-only access on a collection.\n * Stored per-collection in the user's keyring.\n */\nexport type Permission = 'rw' | 'ro'\n\n/**\n * Map of collection name → permission level for a user's keyring entry.\n * `'*'` is the wildcard collection matching all collections in the vault.\n */\nexport type Permissions = Record<string, Permission>\n\n// ─── Encrypted Envelope ────────────────────────────────────────────────\n\n/** The encrypted wrapper stored by stores. Stores only ever see this. */\nexport interface EncryptedEnvelope {\n readonly _noydb: typeof NOYDB_FORMAT_VERSION\n readonly _v: number\n readonly _ts: string\n readonly _iv: string\n readonly _data: string\n /** User who created this version (unencrypted metadata). */\n readonly _by?: string\n /**\n * Opaque provenance source id — which party/registry wrote this version.\n * Unencrypted; present only when the collection opts into `provenance: true`\n * and a `source` is supplied to `put()`. Off by default (zero cost).\n */\n readonly _source?: string\n /** ISO-8601 timestamp the provenance source was recorded. Present alongside `_source`. */\n readonly _sourceTs?: string\n /**\n * Hierarchical access tier. Omitted → tier 0.\n *\n * Unencrypted on purpose — the store reads it to route the envelope\n * to the right DEK slot without having to try-decrypt against every\n * tier. Only leaks the tier of each record, not any value\n * equivalence.\n */\n readonly _tier?: number\n /**\n * User id who last elevated this record. Used by\n * `demote()` to gate the reverse operation: only the original\n * elevator or an owner can demote a record back down. Cleared on\n * every successful demote so a later re-elevate requires the new\n * actor to own the demotion right.\n */\n readonly _elevatedBy?: string\n /**\n * Deterministic-encryption index. Map of field name →\n * base64 deterministic ciphertext. Present only when the collection\n * declares `deterministicFields` and the feature is acknowledged. The\n * field names are unencrypted (they're the index keys); the values\n * are AES-GCM ciphertext with an HKDF-derived deterministic IV.\n *\n * Enables blind equality search (`collection.findByDet(field,\n * value)`) without decrypting every record. Leaks equality as a known\n * side channel.\n */\n readonly _det?: Record<string, string>\n /**\n * Structural group-encryption. Map of sensitive field name →\n * per-field sealed ciphertext in `iv:data` form (same shape as a `_det`\n * slot). Present only when the collection declares `sensitive` fields and\n * at least one is present on the record. Each field is encrypted under its\n * own HKDF-derived per-field key (`deriveSealedFieldKey`, domain-separated\n * by `<collection>/sealed/<field>`), and is kept OUT of the open `_data`\n * blob — so a reader who can open `_data` still cannot see sealed fields\n * without re-deriving each field key. With no sensitive fields declared the\n * map is absent and `_data` is unchanged (byte-identical to legacy output).\n */\n readonly _sealed?: Record<string, string>\n /**\n * Verify-digest slots (classified stage 2). Map of digest-only field name →\n * AES-256-GCM `iv:data` blob sealed under the HKDF(CEK) vdig slot key with\n * AAD ['noydb-classify-vdig', collection, recordId, field]. The store sees\n * only ciphertext; only the enclave verify path can read the digest. At most\n * one of `_sealed[field]` / `_vdig[field]` exists per field (I4).\n */\n readonly _vdig?: Record<string, string>\n /**\n * Equatable blind-index tags (classified slice 2b). Map of digest-only field\n * name → base64 33-byte tag (1-byte cost/version discriminator ‖ 32-byte keyed\n * MAC), CURRENT VALUE ONLY (the _vdig ring is never indexed). This is the ONLY\n * store-visible classified artifact: a keyed MAC, comparable without a key\n * ceremony, with NO inline cryptographic integrity by construction. Invariant:\n * _bidx[field] present ⇒ _vdig[field] present. Confirm-by-verify (findByDigest)\n * makes any read-side orphan/splice unreturnable.\n */\n readonly _bidx?: Record<string, string>\n /**\n * Per-record content-encryption key (CEK), base64 AES-KW-wrapped under\n * the collection (or tier) DEK. Present only on records written by a\n * collection opened with `perRecordKeys: true`. When present, the body\n * (`_iv`/`_data`) is encrypted under the unwrapped CEK rather than the\n * collection DEK directly.\n *\n * Presence is the format discriminant: `_cek` absent → legacy body\n * keyed off the collection DEK (read unchanged); `_cek` present →\n * unwrap under the collection DEK, then decrypt the body under the CEK.\n *\n * The CEK is stable across every version of a record (insert mints it;\n * updates and history snapshots reuse it), so all `_history` envelopes\n * for a record carry the same `_cek`. This is the foundation for\n * per-record erasure and record-scoped sealing.\n *\n * `_det` slots are deliberately NOT keyed off the CEK — they remain\n * keyed to the collection DEK so blind-equality search keeps working\n * across records.\n */\n readonly _cek?: string\n /**\n * Debug-plaintext marker. Present only on records written by a vault opened\n * with `debugPlaintext: true` (which requires `encrypt: false`). When set,\n * the record's own fields are inlined as top-level keys on this envelope\n * (beside the reserved `_`-prefixed metadata) and `_data` is empty — so\n * native store tooling (jq, S3 console) reads the record directly. The read\n * path reconstructs the record from the non-`_` keys; the marker makes a\n * debug envelope self-describing, so a classic plaintext reader handles it too.\n */\n readonly _debug?: typeof NOYDB_FORMAT_VERSION\n /**\n * #589: this envelope is a delete marker (ordinary `collection.delete()` under\n * sync). Empty `_data`, no `_cek`, but version-ordered — a higher-`_v` re-create\n * resurrects the id. Distinct from a forget crypto-shred tombstone, which is\n * terminal. Reads treat it as absent.\n */\n readonly _del?: true\n}\n\n/** Spine policy for one digest-only classified field — the enclave-consumable\n * projection of a ClassifiedFieldSpec (the enclave never imports with-*). */\nexport interface VdigFieldPolicy {\n readonly normalize: 'password' | 'secret-answer'\n /** Ring size for reuse refusal; 0 = no ring. Cap 8 (spec Q4). */\n readonly notLastN: number\n readonly rotateDays?: number\n /** default false — refused unless the double door is open (R8) */\n readonly equatable: boolean\n}\n\n/**\n * The persisted classified-fields config marker (C-A / R10). Reuses the\n * stage-2 persisted-schema record; this is the shape of the marker stored\n * there.\n */\nexport interface ClassifiedMarker {\n /** field names declared digest-only (have _vdig); non-empty ⇒ writes need the classified codec */\n readonly digestOnly: readonly string[]\n /** field names additionally declared equatable (have _bidx when covered) */\n readonly equatable: readonly string[]\n}\n\n/** Verdict-only egress of the enclave oracle (spec §3). */\nexport interface ClassifiedVerdict {\n readonly ok: boolean\n /** I1: present ONLY when ok === true — never computed for a false verdict. */\n readonly mustRotate?: true\n}\n\n/**\n * Opaque access gate for a sealed (`sensitive`) field returned by a public\n * read (the access layer). The handle carries only the per-field\n * **ciphertext** — the plaintext is never materialised into the working-set\n * cache. Call {@link Sealed.reveal} to decrypt the value on demand.\n *\n * A handle is intentionally NOT usable as `V`: it serialises to a non-leaking\n * marker (`JSON.stringify` / structured logging emit `'[sealed]'`, never the\n * value) and exposes no synchronous accessor.\n */\nexport interface Sealed<V> {\n /** Discriminant — always `true`, lets callers narrow a field to a handle. */\n readonly sealed: true\n /** Decrypt and return the underlying value. */\n reveal(): Promise<V>\n}\n\n/**\n * The shape a public read returns for a collection that declares `sensitive`\n * fields `S`: every sealed field becomes an opaque {@link Sealed} handle while\n * the rest of the record is unchanged. The `[S] extends [never]` guard collapses\n * `SealedView<T, never>` to exactly `T`, so collections with no sensitive fields\n * are unaffected — a plain `Omit<T, never>` is *not* a faithful identity for\n * generic intersection record types (it can degrade intersection-only members to\n * `unknown`), which would break consumers like the derivation/MV `_derivedFrom` /\n * `_materializedFrom` reads.\n */\nexport type SealedView<T, S extends keyof T> = [S] extends [never]\n ? T\n : Omit<T, S> & {\n readonly [K in S]: Sealed<T[K]>\n }\n\n/**\n * The type of a field-name argument to the query/scan DSL (`where`, `orderBy`,\n * …) for a collection whose sealed (`sensitive`) fields are `S`.\n *\n * Guarded so the common case is unchanged: with **no** sensitive fields\n * (`S = never`) it is exactly `string` — collections that don't opt into\n * `sensitive` keep today's permissive DSL, zero churn. Once a field is\n * declared `sensitive`, the DSL narrows to the non-sensitive field names, so\n * `where('ssn', …)` becomes a compile error. TypeScript cannot subtract a\n * literal from `string`, so refusing a sensitive name necessarily means\n * narrowing to the known field-name union — this is intentional and only\n * affects collections that opted in.\n *\n * When `Q` (the indexed-field set) is given, `where()` is additionally\n * restricted to `Q` minus any sensitive fields — the escape hatch for\n * non-indexed filters is `scan()`. `Q = never` (the default) preserves the\n * existing 2-param behaviour exactly (zero churn).\n */\nexport type QueryField<T, S extends keyof T = never, Q extends keyof T & string = never> =\n [Q] extends [never]\n ? ([S] extends [never] ? string : Exclude<keyof T & string, S>)\n : Exclude<Q, S>\n\n/**\n * The type of a field-name reference in a collection's index-declaration\n * options (`indexes`, `deterministicFields`, `textIndexes`). Same guarded\n * narrowing as {@link QueryField}: permissive `string` until a field is\n * declared `sensitive`, then the sensitive names are refused (a plaintext\n * secondary index over a sealed field defeats non-residency). Kept distinct\n * from `QueryField` so the two DSL surfaces can diverge later without coupling.\n *\n * When `Q` (the indexed-field set) is given, the `indexes` option is\n * additionally restricted to `Q` minus any sensitive fields — declaring `Q`\n * but listing a different field in `indexes` becomes a compile error.\n * `Q = never` (the default) preserves the existing 2-param behaviour.\n */\nexport type IndexFieldName<T, S extends keyof T = never, Q extends keyof T & string = never> =\n [Q] extends [never]\n ? ([S] extends [never] ? string : Exclude<keyof T & string, S>)\n : Exclude<Q, S>\n\n/**\n * Generic form of the runtime `IndexDef` (see `indexing/eager-indexes.ts`)\n * parameterised by the allowed field-name set `F`. Used to refuse `sensitive`\n * fields in the `indexes` collection option at compile time while leaving the\n * runtime `IndexDef` (string-based) untouched. `IndexDefFor<string>` is\n * structurally identical to `IndexDef`, which is why `vault.collection` can cast\n * the narrowed public option to `IndexDef[]` at the runtime boundary (through\n * `unknown`, solely to drop the `readonly`).\n * **Keep this in sync with `IndexDef`** — if `IndexDef` gains a new union member,\n * add it here too, or that boundary cast will silently admit shapes the runtime\n * machinery does not narrow.\n */\nexport type IndexDefFor<F extends string> =\n | F\n | { readonly fields: readonly F[]; readonly unique?: boolean }\n | readonly F[]\n\n/**\n * The type of the `sensitive` collection option, conditional on whether the\n * caller opted into compile-time refusal via an explicit second generic.\n * With no 2nd generic (`S = never`) it accepts any field array — runtime\n * sealing only, no compile refusal, non-breaking. With `S` given, it is\n * `readonly S[]`, which ties the runtime array to the declared sensitive\n * union so the two cannot drift.\n */\nexport type SensitiveOpt<T, S extends keyof T> = [S] extends [never]\n ? readonly (keyof T & string)[]\n : readonly S[]\n\n/**\n * The type of the `moneyFields` collection option, conditional on whether the\n * caller opted into compile-time money-field typing via the 4th generic `M`.\n * Typed against the opaque {@link ViaDescriptor} marker rather than the\n * concrete `MoneyDescriptor` — the kernel never inspects a Via feature's\n * descriptor shape, only its declaring service does.\n * A `money()` descriptor structurally satisfies `ViaDescriptor` (it carries\n * `_viaBrand: 'money'`), so this stays publicly assignable from `money()`\n * call sites. With no `M` (`M = never`) it accepts any\n * `Record<string, ViaDescriptor>` — runtime money only, no compile-level\n * narrowing, non-breaking. With `M` given, it is `Record<M, ViaDescriptor>`,\n * tying the runtime map to the declared money-field union so the two cannot\n * drift.\n */\nexport type MoneyFieldsOpt<T, M extends keyof T & string = never> =\n [M] extends [never] ? Record<string, ViaDescriptor> : Record<M, ViaDescriptor>\n\n/**\n * Concrete {@link Sealed} handle. Holds the reveal closure (which captures the\n * field's ciphertext blob and the unseal routine) in a private field, so it is\n * invisible to `JSON.stringify`, `util.inspect`, and `Object.keys`. `toJSON`\n * returns the marker `'[sealed]'` — a handle can never leak its value through\n * serialisation or logging because the plaintext is not stored on it at all.\n */\nexport class SealedHandle<V> implements Sealed<V> {\n readonly sealed = true as const\n readonly #reveal: () => Promise<V>\n\n constructor(reveal: () => Promise<V>) {\n this.#reveal = reveal\n }\n\n reveal(): Promise<V> {\n return this.#reveal()\n }\n\n /** Non-leaking serialisation marker — never the underlying value. */\n toJSON(): string {\n return '[sealed]'\n }\n}\n\n/**\n * Handover-capable provider. Implemented additionally by asymmetric/granted\n * providers (cloud-KMS asymmetric, Azure RSA Key Vault, AWS KMS with grant).\n * Self-only providers (macOS Keychain, env-var, WebAuthn-PRF) do NOT\n * implement this — the §11.2 capability matrix lives in the type system.\n *\n * Per foundation §11.4. A function that requires recipient-target sealing\n * takes `RecipientSealer`, not `SealingKeyProvider` — the compiler rejects\n * passing a self-only provider at the spec site.\n */\nexport interface RecipientSealer {\n readonly id: string\n /** Produce hint material a sender uses to seal-for-this-recipient. */\n publishRecipientHint(): Promise<RecipientHint>\n /**\n * Seal plaintext for the recipient described by `hint`. Returns opaque\n * bytes — same contract as `SealingKeyProvider.seal()`. The bundle\n * layer base64-encodes the bytes into `SealedAutoUnlockEntry.sealed`\n * without inspecting them.\n */\n sealForRecipient(plaintext: Uint8Array, hint: RecipientHint): Promise<Uint8Array>\n}\n\n/**\n * Thin delivery envelope persisted at\n * `_sealed_cek/<collection>/<id>/<pid>`. The grantor writes one per\n * (record, recipient host) pair. `payload` is the base64 of the bytes returned\n * by {@link RecipientSealer.sealForRecipient} over a UTF-8\n * `JSON.stringify({@link SealedCekBinding})`.\n *\n * `expiresAt` is duplicated here for a cheap pre-unseal reject, but is NOT\n * authoritative — the binding inside `payload` carries the expiry the host\n * verifies after unsealing, so a tampered delivery envelope cannot extend a\n * grant.\n */\nexport interface SealedCekDeliveryEnvelope {\n /** Envelope schema version. */\n readonly v: 1\n /** Magic marker for forensics + format detection. */\n readonly _noydb_sealed_cek: 1\n /** Recipient host provider id; matches the sealer's `.id` / hint `pid`. */\n readonly pid: string\n /** base64 of the sealed {@link SealedCekBinding} bytes. */\n readonly payload: string\n /** Fast-path expiry hint (ISO 8601). Authoritative copy is inside `payload`. */\n readonly expiresAt: string\n}\n\n/**\n * The plaintext struct sealed for the recipient host. After the host unseals\n * `SealedCekDeliveryEnvelope.payload` it parses this and MUST verify:\n * - `collection` + `id` match the record envelope it is decrypting, and\n * - `expiresAt` has not passed (authoritative expiry check).\n *\n * `cek` is the base64 of the raw 32-byte AES-256-GCM record CEK.\n */\nexport interface SealedCekBinding {\n /** Collection the CEK belongs to. */\n readonly collection: string\n /** Record id the CEK belongs to. */\n readonly id: string\n /** base64 of the raw AES-256-GCM CEK bytes. */\n readonly cek: string\n /** Authoritative expiry (ISO 8601). */\n readonly expiresAt: string\n}\n\n/**\n * Placeholder returned by `getAtTier()` in `'ghost'` mode when a\n * record is at a tier the caller cannot decrypt. Record existence is\n * advertised — the id and tier are visible — but contents are\n * withheld. `canElevateFrom` lists user ids authorized to elevate\n * access for this caller when known; absent when the workflow is\n * not configured.\n */\nexport interface GhostRecord {\n readonly _ghost: true\n readonly _tier: number\n readonly canElevateFrom?: readonly string[]\n}\n\n/** Control what lower-tier reads see above their clearance. */\nexport type TierMode = 'invisibility' | 'ghost'\n\n/**\n * Event emitted when a record at a tier above the caller's inherent\n * clearance is read or written successfully (via elevation or\n * delegation). Always written to the ledger; subscribers get a\n * real-time feed.\n */\nexport interface CrossTierAccessEvent {\n readonly actor: string\n readonly collection: string\n readonly id: string\n readonly tier: number\n /** How the caller gained tier access: they elevated it, or a delegation is active. */\n readonly authorization: 'elevation' | 'delegation' | 'inherent'\n readonly op: 'get' | 'put' | 'elevate' | 'demote'\n readonly ts: string\n /**\n * When `authorization === 'elevation'`, the audit reason string the\n * caller passed to `vault.elevate(...)`. Empty for inherent /\n * delegation paths.\n */\n readonly reason?: string\n /**\n * When `authorization === 'elevation'`, the tier the caller's\n * keyring effectively held BEFORE elevation. Useful for audit\n * dashboards distinguishing \"operator elevating to 2\" from\n * \"inherent tier-2 write.\"\n */\n readonly elevatedFrom?: number\n}\n\n/**\n * A single deterministic-ciphertext index slot on an envelope. Stored\n * as `iv:data` (both base64, colon-separated) so a single string per\n * field keeps the envelope compact.\n */\nexport type DeterministicCipher = string\n\n// ─── Vault Snapshot ──────────────────────────────────────────────\n\n/** All records across all collections for a compartment. */\nexport type VaultSnapshot = Record<string, Record<string, EncryptedEnvelope>>\n\n/**\n * Result of a single page fetch via the optional `listPage` adapter extension.\n *\n * `items` carries the actual encrypted envelopes (not just ids) so the\n * caller can decrypt and emit a single record without an extra `get()`\n * round-trip per id. `nextCursor` is `null` on the final page.\n */\nexport interface ListPageResult {\n /** Encrypted envelopes for this page, in adapter-defined order. */\n items: Array<{ id: string; envelope: EncryptedEnvelope }>\n /** Opaque cursor for the next page, or `null` if this was the last page. */\n nextCursor: string | null\n}\n\n// ─── Store Interface ───────────────────────────────────────────────────\n\nexport interface NoydbStore {\n /**\n * Optional human-readable store name (e.g. 'memory', 'file', 'dynamo').\n * Used in diagnostic messages and the listPage fallback warning. Stores\n * are encouraged to set this so logs are clearer about which backend is\n * involved when something goes wrong.\n */\n name?: string\n\n /**\n * Optional declared store capabilities (CAS atomicity, native tx, blob\n * size limits, auth). Consumers that require a capability — e.g.\n * `vault.sequence().next()` needs `casAtomic` — read it here.\n */\n capabilities?: StoreCapabilities\n\n /** Get a single record. Returns null if not found. */\n get(vault: string, collection: string, id: string): Promise<EncryptedEnvelope | null>\n\n /** Put a record. Throws ConflictError if expectedVersion doesn't match. */\n put(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n expectedVersion?: number,\n ): Promise<void>\n\n /** Delete a record. */\n delete(vault: string, collection: string, id: string): Promise<void>\n\n /** List all record IDs in a collection. */\n list(vault: string, collection: string): Promise<string[]>\n\n /** Load all records for a vault (initial hydration). */\n loadAll(vault: string): Promise<VaultSnapshot>\n\n /** Save all records for a vault (bulk write / restore). */\n saveAll(vault: string, data: VaultSnapshot): Promise<void>\n\n /** Optional connectivity check for sync engine. */\n ping?(): Promise<boolean>\n\n /**\n * The store's authoritative time as a bounded-uncertainty interval.\n * Present iff `capabilities.serverWriteTime` is true. Monotonic\n * non-decreasing across calls on a single store.\n */\n getStoreTime?(): Promise<StoreTime>\n\n /**\n * Optional: list record IDs in a collection that have `_ts` after `since`.\n * Used by partial sync (`pull({ modifiedSince })`). Stores that omit this\n * fall back to a full `loadAll` + client-side timestamp filter.\n */\n listSince?(vault: string, collection: string, since: string): Promise<string[]>\n\n /**\n * Optional pagination extension. Stores that implement `listPage` get\n * the streaming `Collection.scan()` fast path; stores that don't are\n * silently fallen back to a full `loadAll()` + slice (with a one-time\n * console.warn).\n *\n * `cursor` is opaque to the core — each store encodes its own paging\n * state (DynamoDB: base64 LastEvaluatedKey JSON; S3: ContinuationToken;\n * memory/file/browser: numeric offset of a sorted id list). Pass\n * `undefined` to start from the beginning.\n *\n * `limit` is a soft upper bound on `items.length`. Stores MAY return\n * fewer items even when more exist (e.g. if the underlying store has\n * its own page size cap), and MUST signal \"no more pages\" by returning\n * `nextCursor: null`.\n *\n * The 6-method core contract is unchanged — this is an additive\n * extension discovered via `'listPage' in adapter`.\n */\n listPage?(\n vault: string,\n collection: string,\n cursor?: string,\n limit?: number,\n ): Promise<ListPageResult>\n\n /**\n * Optional pub/sub for real-time presence.\n * Publish an encrypted payload to a presence channel.\n * Falls back to storage-based polling when absent.\n */\n presencePublish?(channel: string, payload: string): Promise<void>\n\n /**\n * Optional pub/sub for real-time presence.\n * Subscribe to a presence channel. Returns an unsubscribe function.\n * Falls back to storage-based polling when absent.\n */\n presenceSubscribe?(channel: string, callback: (payload: string) => void): () => void\n\n /**\n * Optional cross-vault enumeration extension.\n *\n * Returns the names of every top-level vault the store\n * currently stores. Used by `Noydb.listAccessibleVaults()` to\n * enumerate the universe of vaults before filtering down to\n * the ones the calling principal can actually unwrap.\n *\n * **Why this is optional:** the storage shape of compartments\n * differs across backends. Memory and file stores store\n * vaults as top-level keys / directories and can enumerate\n * them in O(1) calls. DynamoDB stores everything in a single table\n * keyed by `(compartment#collection, id)` — enumerating compartments\n * requires either a Scan (expensive, eventually consistent, leaks\n * ciphertext metadata) or a dedicated GSI that the consumer\n * provisioned. S3 needs a prefix list (cheap if enabled, ACL-sensitive\n * otherwise). Browser localStorage can scan keys by prefix.\n *\n * Stores that cannot implement `listVaults` cheaply or\n * cleanly should omit it. Core surfaces a `StoreCapabilityError`\n * with a clear message when a caller invokes\n * `listAccessibleVaults()` against a store that doesn't\n * provide this method, so consumers know to either upgrade their\n * store, provide a candidate list explicitly to `queryAcross()`,\n * or fall back to maintaining the compartment index out of band.\n *\n * **Privacy note:** `listVaults` returns *every* compartment\n * the store has, not just the ones the caller can access. The\n * existence-leak filtering (returning only compartments whose\n * keyring the caller can unwrap) happens in core, not in the\n * store. The store is trusted to know its own contents — that\n * is not a leak in the threat model. The leak the API guards\n * against is the *return value* of `listAccessibleVaults()`\n * exposing existence to a downstream observer who only sees that\n * function's output.\n *\n * The 6-method core contract is unchanged — this is an additive\n * extension discovered via `'listVaults' in store`.\n */\n listVaults?(): Promise<string[]>\n\n /**\n * Optional: generate a presigned URL for direct client download.\n * Only meaningful for object stores (S3, GCS) that support URL signing.\n * Returns a time-limited URL that fetches the encrypted envelope directly.\n * The caller must decrypt client-side (the URL returns ciphertext).\n */\n presignUrl?(vault: string, collection: string, id: string, expiresInSeconds?: number): Promise<string>\n\n /**\n * Optional: estimate current storage usage.\n * Returns `{ usedBytes, quotaBytes }` or null if the store cannot estimate.\n * Used by quota-aware routing to detect overflow conditions.\n */\n estimateUsage?(): Promise<{ usedBytes: number; quotaBytes: number } | null>\n\n /**\n * Optional multi-record atomic write.\n *\n * When present, `db.transaction(async (tx) => { ... })` uses this to\n * commit every staged op in one storage-layer transaction — either\n * all ops land or none do, regardless of which records they touch.\n * Every `TxOp.expectedVersion` (when set) must be honored atomically\n * alongside the write; any violation throws `ConflictError` and the\n * whole batch fails.\n *\n * Stores that omit this fall through to the hub's per-record OCC\n * fallback: pre-flight CAS check, then sequential `put`/`delete`\n * with best-effort unwind on mid-batch failure (see\n * `runTransaction` for the exact semantics and crash window).\n *\n * Native implementations: `to-memory` (single Map mutation),\n * `to-dynamo` (`TransactWriteItems`), `to-browser-idb` (one\n * `readwrite` transaction). File / S3 cannot implement this\n * atomically and should omit the method.\n */\n tx?(ops: readonly TxOp[]): Promise<void>\n}\n\n/**\n * A single staged operation inside a `db.transaction(fn)` commit. The\n * hub assembles `TxOp[]` from the user's `tx.collection().put/delete`\n * calls, encrypts any `record` values into `envelope`, and hands the\n * array to `NoydbStore.tx()` when the store supports atomic batch\n * writes. Stores that implement `tx()` MUST honor every\n * `expectedVersion` atomically against the stored envelope version.\n */\nexport interface TxOp {\n readonly type: 'put' | 'delete'\n readonly vault: string\n readonly collection: string\n readonly id: string\n /** Populated for `type: 'put'` — the encrypted envelope to write. */\n readonly envelope?: EncryptedEnvelope\n /** Optional per-record CAS. Mismatch must throw `ConflictError`. */\n readonly expectedVersion?: number\n}\n\n// ─── Store Factory Helper ──────────────────────────────────────────────\n\n/** Type-safe helper for creating store factories. */\nexport function createStore<TOptions>(\n factory: (options: TOptions) => NoydbStore,\n): (options: TOptions) => NoydbStore {\n return factory\n}\n\n// ─── Keyring ───────────────────────────────────────────────────────────\n\n/**\n * Interchange formats `@noy-db/as-*` packages can produce. `'*'` is a\n * wildcard granting every current + future plaintext format.\n */\nexport type ExportFormat =\n | 'xlsx'\n | 'csv'\n | 'json'\n | 'ndjson'\n | 'xml'\n | 'sql'\n | 'pdf'\n | 'blob'\n | 'zip'\n | '*'\n\n/**\n * Owner-granted export capability on a keyring.\n *\n * Two independent dimensions:\n *\n * - `plaintext` — per-format allowlist for record formatters + blob\n * extractors that emit plaintext bytes (`as-xlsx`, `as-csv`,\n * `as-blob`, `as-zip`, …). **Defaults to empty** for every role;\n * the owner/admin must positively grant per-format (or `'*'`).\n * - `bundle` — boolean for `.noydb` encrypted container export\n * (`as-noydb`). **Default policy: on for owner/admin, off for\n * operator/viewer/client** — applied when the field is absent or\n * undefined (see `hasExportCapability`).\n */\nexport interface ExportCapability {\n readonly plaintext?: readonly ExportFormat[]\n readonly bundle?: boolean\n}\n\n/**\n * Owner-granted import capability on a keyring (sibling of\n * `ExportCapability`, issue ).\n *\n * Two independent dimensions:\n *\n * - `plaintext` — per-format allowlist for `as-*` readers that ingest\n * plaintext bytes (`as-csv`, `as-json`, `as-ndjson`, `as-zip`, …).\n * Defaults to empty for every role; the owner/admin must positively\n * grant per-format (or `'*'`).\n * - `bundle` — boolean gate for `.noydb` bundle import. **Defaults to\n * `false` for every role**, including owner/admin. Import is more\n * dangerous than export (corrupts vs leaks), so the policy is\n * default-closed across the board — the owner explicitly opts a\n * keyring in via `db.grant({ importCapability: { bundle: true } })`.\n */\nexport interface ImportCapability {\n readonly plaintext?: readonly ExportFormat[]\n readonly bundle?: boolean\n}\n\n/**\n * Forward-declared on-disk shape for `VaultPolicy` — the actual policy\n * model is declared further down in this file (#9), see {@link VaultPolicy}.\n * Declared here as an `unknown`-typed map (rather than `VaultPolicy` itself)\n * so the `KeyringFile.policy` field can still round-trip foreign/older\n * documents that don't strictly satisfy the current shape.\n *\n * @internal\n */\nexport type VaultPolicyOnDisk = Record<string, unknown>\n\n/**\n * Recovery profile enrolled at vault creation.\n *\n * - `paper` — `on-recovery` codes (the standard end-to-end profile).\n * - `shamir` / `multi-channel` / `admin-mediated` — API surface ships;\n * per-profile dispatch lands in follow-up issues. Calling\n * `db.recoverPassphrase` against these throws\n * {@link RecoveryProfileNotImplementedError}.\n */\nexport type RecoveryEnrollment =\n | {\n readonly profile: 'paper'\n /** Number of single-use codes to print at enrollment. */\n readonly codes: number\n }\n | {\n readonly profile: 'shamir'\n readonly k: number\n readonly n: number\n readonly trustees: ReadonlyArray<string>\n }\n | {\n readonly profile: 'multi-channel'\n readonly email?: string\n readonly pin?: boolean\n readonly paperCodes?: number\n }\n | {\n readonly profile: 'admin-mediated'\n readonly grantorUserId: string\n }\n\n/**\n * One tier-2 authenticator slot inside a keyring file. Each slot\n * independently wraps the SAME KEK under a method-specific derived key\n * (LUKS pattern). Adding or removing a slot is a constant-time keyring\n * write — no DEK re-keying required.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Tier 2 — Authenticate (multi-slot)\n */\n/**\n * Shared fields across all authenticator slot variants. The variant\n * (`KeyringAuthenticatorWrappingKEK` vs `KeyringAuthenticatorWrappingDEKs`)\n * carries the actual wrapped material; everything below is identity +\n * metadata only.\n */\ninterface KeyringAuthenticatorBase {\n /** Caller-chosen identifier — e.g. `'webauthn-yubikey-blue'`, `'oidc-google'`, `'password'`. */\n readonly id: string\n /** Method family — selects which `@noy-db/on-*` package handles unlock. */\n readonly method: 'webauthn' | 'oidc' | 'password'\n /** ISO-8601 timestamp at which the slot was added. */\n readonly enrolled_at: string\n /**\n * Which session tier ENROLLED this slot. Tier 1 enrolls a fresh slot;\n * tier 2 may add a sibling slot when the active policy permits.\n */\n readonly enrolled_via_tier: 1 | 2\n /**\n * Method-specific metadata: WebAuthn cred id, OIDC issuer/sub, PBKDF2\n * salt for `on-password`, etc. The schema is open by design — the\n * `@noy-db/on-*` package owns the contents.\n */\n readonly meta: Record<string, unknown>\n}\n\n/**\n * Slot that wraps the KEK directly under a method-derived AES-KW key.\n * Used by ceremonies where the on-* package can produce/recover an\n * extractable KEK from its own credential — WebAuthn (PRF-derived\n * wrapping key) and split-key OIDC.\n *\n * `wrapKind` is optional/absent on older slots — those\n * legacy slots are treated as wrap-KEK by default at unlock time.\n */\nexport interface KeyringAuthenticatorWrappingKEK extends KeyringAuthenticatorBase {\n readonly wrapKind?: 'kek'\n /** Base64 wrapped-KEK ciphertext under the method-derived key. */\n readonly wrapped_kek: string\n /** XOR guard — wrap-KEK slots must NOT carry wrap-DEKs material. */\n readonly wrapped_deks?: never\n /** XOR guard — wrap-KEK slots must NOT carry wrap-DEKs material. */\n readonly iv?: never\n}\n\n/**\n * Slot that wraps the DEK set (not the KEK) under a method-derived\n * AES-GCM key — sidesteps the non-extractable-KEK constraint by\n * encrypting the serialized `{ deks: { collection: rawDekBase64 } }`\n * directly. Mirrors the format used by `mintPaperRecoveryEntry`\n * (`PaperRecoveryEntry`) and `@noy-db/on-pin`'s `PinResumeState` —\n * the unified wrap-DEKs primitive across tier-0 / tier-2 / tier-3.\n *\n * Trade-off: a slot of this kind reconstructs `UnlockedKeyring` with\n * `kek: null` after unlock. That is semantically correct for tier-2\n * (sensitive ops like `enrollAuthenticator` / `rotatePassphrase`\n * require a tier-1 unlock anyway) and matches how `@noy-db/on-pin`\n * already behaves at tier 3.\n *\n * @see `mintPaperRecoveryEntry` in `team/recovery.ts` — same shape on\n * a different on-disk path (`_meta/recovery-paper`).\n */\nexport interface KeyringAuthenticatorWrappingDEKs extends KeyringAuthenticatorBase {\n readonly wrapKind: 'deks'\n /** Base64 AES-GCM ciphertext of `{ deks: { collection: base64rawDek } }`. */\n readonly wrapped_deks: string\n /** Base64 AES-GCM IV used for the `wrapped_deks` ciphertext. */\n readonly iv: string\n /** XOR guard — wrap-DEKs slots must NOT carry wrap-KEK material. */\n readonly wrapped_kek?: never\n}\n\n/**\n * Discriminated union over the two wrap-format variants. Reads from\n * disk should always go through this type so the variant is preserved.\n *\n * Discriminator: `wrapKind`. Absent → wrap-KEK (legacy / WebAuthn /\n * OIDC). Present and `'deks'` → wrap-DEKs (password / future on-* that\n * want to sidestep extractable-KEK).\n *\n * The type-level XOR enforces \"exactly one of `wrapped_kek` /\n * `wrapped_deks` is present\" — a structural guarantee that the runtime\n * dispatch is safe.\n */\nexport type KeyringAuthenticator =\n | KeyringAuthenticatorWrappingKEK\n | KeyringAuthenticatorWrappingDEKs\n\nexport interface KeyringFile {\n readonly _noydb_keyring: typeof NOYDB_KEYRING_VERSION\n readonly user_id: string\n readonly display_name: string\n readonly role: Role\n readonly permissions: Permissions\n readonly deks: Record<string, string>\n readonly salt: string\n readonly created_at: string\n readonly granted_by: string\n /**\n * Passphrase canary — base64 AES-KW-wrapped form of a known constant\n * 256-bit value, wrapped under the keyring's KEK.\n *\n * Optional: older keyrings load with no canary and fall back to\n * the multi-DEK corruption heuristic. Newer keyrings\n * carry one and let `loadKeyring` distinguish wrong-passphrase\n * from corruption even when ALL DEKs (including a single-DEK keyring's\n * sole DEK) are corrupted.\n *\n * AES-KW is deterministic — every write site mints fresh on each\n * persist; same KEK + same constant input always produces the same\n * ciphertext, so this round-trips without state.\n */\n readonly canary?: string\n /**\n * Tier-2 authenticator slots (multi-slot keyring extension).\n * Optional / append-only: keyring files written before the\n * extension load with an empty list. Each slot independently wraps\n * the same KEK; any one of them unlocks.\n *\n * @see KeyringAuthenticator\n */\n readonly authenticators?: readonly KeyringAuthenticator[]\n /**\n * Per-keyring policy override (reserved). The on-disk format\n * accepts the field for forward compatibility with the Option C\n * merge engine deferred to a later release; v1.0 reads only the\n * vault-level `_meta/policy` document, so this field is parsed and\n * round-tripped but never enforced.\n */\n readonly policy?: VaultPolicyOnDisk\n /**\n * Optional — authorization spec capability bits. Absent on keyrings written\n * before the RFC implementation. Loading falls back to role-based\n * defaults (owner/admin get bundle-on, everyone else off).\n */\n readonly export_capability?: ExportCapability\n /**\n * Optional bundle-slot expiry. ISO-8601 timestamp; past\n * the cutoff `loadKeyring` throws `KeyringExpiredError` before any\n * DEK unwrap is attempted. Useful for time-boxed audit access:\n * \"this slot works for 30 days then becomes opaque to its holder.\"\n *\n * Absent on live keyrings written via `db.grant()` — the field is\n * meaningful for `BundleRecipient` slots produced by\n * `writePod({ recipients: [...] })`. Setting it on a live\n * keyring is allowed but unusual.\n */\n readonly expires_at?: string\n /**\n * Optional — issue import-capability bits. Absent on keyrings\n * written before landed. Loading falls back to default-closed\n * for every role and every format.\n */\n readonly import_capability?: ImportCapability\n /**\n * hierarchical access clearance. Absent → 0 (advisory;\n * the real check is whether the DEK map carries a `collection#tier`\n * entry for the requested tier). Owners and admins default to the\n * highest tier they have DEKs for at grant time.\n */\n readonly clearance?: number\n}\n\n// ─── Backup ────────────────────────────────────────────────────────────\n\nexport interface VaultBackup {\n readonly _noydb_backup: typeof NOYDB_BACKUP_VERSION\n readonly _compartment: string\n readonly _exported_at: string\n readonly _exported_by: string\n readonly keyrings: Record<string, KeyringFile>\n readonly collections: VaultSnapshot\n /**\n * Internal collections (`_ledger`, `_ledger_deltas`, `_history`, `_sync`, …)\n * captured alongside the data collections. Optional for backwards\n * compat with backups, which only stored data collections —\n * loading a backup leaves the ledger empty (and `verifyBackupIntegrity`\n * skips the chain check, surfacing only a console warning).\n */\n readonly _internal?: VaultSnapshot\n /**\n * Verifiable-backup metadata. Embeds the ledger head at\n * dump time so `load()` can cross-check that the loaded chain matches\n * exactly what was exported. A backup whose chain has been tampered\n * with — either by modifying ledger entries or by modifying data\n * envelopes that the chain references — fails this check.\n *\n * Optional for backwards compat with backups; missing means\n * \"legacy backup, load with a warning, no integrity check\".\n */\n readonly ledgerHead?: {\n /** Hex sha256 of the canonical JSON of the last ledger entry. */\n readonly hash: string\n /** Sequential index of the last ledger entry. */\n readonly index: number\n /** ISO timestamp captured at dump time. */\n readonly ts: string\n }\n}\n\n// ─── Export ────────────────────────────────────────────────────────────\n\n/**\n * Options for `Vault.exportStream()` and `Vault.exportJSON()`.\n *\n * The defaults match the most common consumer pattern: one chunk per\n * collection, no ledger metadata. Per-record streaming and ledger-head\n * inclusion are opt-in because both add structure most consumers don't\n * need.\n */\nexport interface ExportStreamOptions {\n /**\n * `'collection'` (default) yields one chunk per collection with all\n * records bundled in `chunk.records`. `'record'` yields one chunk per\n * record, useful for arbitrarily large collections that should never\n * be materialized as a single array.\n */\n readonly granularity?: 'collection' | 'record'\n\n /**\n * When `true`, every chunk includes the current compartment ledger\n * head under `chunk.ledgerHead`. The value is identical across every\n * chunk in a single export (one ledger per compartment). Forward-\n * compatible with future partition work where the head would become\n * per-partition. Default: `false`.\n */\n readonly withLedgerHead?: boolean\n /**\n * Export locale (BCP 47, e.g. `'th'`). When set, records are read at this\n * locale through the **`export` layer**: `i18nText` fields collapse to\n * the locale string (honoring each field's `export`-layer `onMissing` policy)\n * and `dictKey`/`staticDict` `<field>Label`s are resolved — a single-locale\n * export. The raw `dictionaries` snapshot is then redundant and omitted. This\n * applies to BOTH `exportStream()` and `exportJSON()`.\n *\n * Default: `undefined` — raw `{locale}` maps + the `_dictionaries` snapshot\n * (a full, all-locale backup; format packages apply their own locale strategy).\n */\n readonly resolveLabels?: string\n}\n\n/**\n * One chunk yielded by `Vault.exportStream()`.\n *\n * `granularity: 'collection'` yields one chunk per collection with the\n * full record array in `records`. `granularity: 'record'` yields one\n * chunk per record with `records` containing exactly one element — the\n * `schema` and `refs` metadata is repeated on every chunk so consumers\n * doing per-record streaming don't have to thread state across yields.\n */\nexport interface ExportChunk<T = unknown> {\n /** Collection name (no leading underscore — internal collections are filtered out). */\n readonly collection: string\n\n /**\n * Standard Schema validator attached to the collection at `collection()`\n * construction time, or `null` if no schema was provided. Surfaced so\n * downstream serializers (`@noy-db/as-*` packages, custom\n * exporters) can produce schema-aware output (typed CSV headers, XSD\n * generation, etc.) without poking at collection internals.\n */\n readonly schema: StandardSchemaV1<unknown, T> | null\n\n /**\n * Foreign-key references declared on the collection via the `refs`\n * option, as the `{ field → { target, mode } }` map produced by\n * `RefRegistry.getOutbound`. Empty object when no refs were declared.\n */\n readonly refs: Record<string, { readonly target: string; readonly mode: 'strict' | 'warn' | 'cascade' }>\n\n /**\n * Decrypted, ACL-scoped, schema-validated records. Length 1 in\n * `granularity: 'record'` mode, full collection in `granularity: 'collection'`\n * mode. Records are returned by reference from the collection's eager\n * cache where applicable — consumers must treat them as immutable.\n */\n readonly records: T[]\n\n /**\n * Dictionary snapshots for every `dictKey` field declared on this\n * collection. Captured once at stream-start and held\n * constant across all chunks within the same export — a rename\n * mid-export does not change the snapshot. `undefined` when the\n * collection has no `dictKeyFields`.\n *\n * Shape: `{ [fieldName]: { [stableKey]: { [locale]: label } } }`\n *\n * @example\n * ```ts\n * chunk.dictionaries?.status?.paid?.th // → 'ชำระแล้ว'\n * ```\n */\n readonly dictionaries?: Record<\n string, // field name\n Record<string, Record<string, string>> // stable key → locale → label\n >\n\n /**\n * Vault ledger head at export time. Present only when\n * `exportStream({ withLedgerHead: true })` was called. Identical\n * across every chunk in the same export — included on every chunk\n * for forward-compatibility with future per-partition ledgers, where\n * the value will differ per chunk.\n */\n readonly ledgerHead?: {\n readonly hash: string\n readonly index: number\n readonly ts: string\n }\n}\n\n// ─── Sync ──────────────────────────────────────────────────────────────\n\nexport interface DirtyEntry {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly action: 'put' | 'delete'\n readonly version: number\n readonly timestamp: string\n}\n\nexport interface SyncMetadata {\n readonly _noydb_sync: typeof NOYDB_SYNC_VERSION\n readonly last_push: string | null\n readonly last_pull: string | null\n readonly dirty: DirtyEntry[]\n}\n\nexport interface Conflict {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly local: EncryptedEnvelope\n readonly remote: EncryptedEnvelope\n readonly localVersion: number\n readonly remoteVersion: number\n /**\n * Present only when the collection uses `conflictPolicy: 'manual'`.\n * Call `resolve(winner)` to commit the winning envelope, or\n * `resolve(null)` to defer (conflict stays queued for the next sync).\n * Called synchronously inside the `sync:conflict` event handler.\n */\n readonly resolve?: (winner: EncryptedEnvelope | null) => void\n}\n\n/**\n * #590: sync suppressed a live envelope because a crypto-shred tombstone is\n * terminal for its record id. Reported on push/pull results (`erasures`) and\n * via the `'sync:erasure'` event; conflict resolvers are never consulted for\n * tombstone pairs.\n */\nexport interface ErasureEnforcement {\n readonly vault: string\n readonly collection: string\n readonly id: string\n /** The winning tombstone (as stored after enforcement). */\n readonly tombstone: EncryptedEnvelope\n /** The live envelope that lost: a suppressed dirty local edit, or the remote copy destroyed by re-assertion. */\n readonly suppressed: EncryptedEnvelope\n readonly direction: 'pull' | 'push'\n}\n\n/**\n * A same-device cross-tab write conflict: another tab overwrote a\n * document this tab had written, having diverged from an older base. Records\n * are decrypted (cross-tab handlers reconcile in plaintext). `base` is the\n * common ancestor from history, or null when history is unavailable.\n */\nexport interface WriteConflict {\n readonly vault: string\n readonly collection: string\n readonly docId: string\n readonly local: unknown\n readonly remote: unknown\n readonly base: unknown\n readonly localVersion: number\n readonly remoteVersion: number\n readonly baseVersion: number\n}\n\nexport type ConflictStrategy =\n | 'local-wins'\n | 'remote-wins'\n | 'version'\n | ((conflict: Conflict) => 'local' | 'remote')\n\n/**\n * Collection-level conflict policy.\n * Overrides the db-level `conflict` option for the specific collection.\n *\n * - `'last-writer-wins'` — higher `_ts` wins (timestamp LWW).\n * - `'first-writer-wins'` — lower `_v` wins (earlier version is preserved).\n * - `'manual'` — emits `sync:conflict` with a `resolve` callback. Call\n * `resolve(winner)` synchronously to commit or `resolve(null)` to defer.\n * - Custom fn — synchronous `(local: T, remote: T) => T`. Must be pure.\n *\n * **Delete-vs-edit caveat:** `'last-writer-wins'`, `'first-writer-wins'`,\n * and `'manual'` compare/hand over raw envelopes, so an edit CAN win over\n * a delete marker (a later `_ts`, an earlier `_v`, or the app's own\n * `resolve()` choice). A custom fn, and the CRDT merge modes `'lww-map'`/\n * `'rga'` (`crdtStrategy`), CANNOT: their shared resolver wrapper decrypts\n * both sides first and short-circuits to whichever side is the\n * shredded/tombstoned one *before* the merge function (or CRDT merge)\n * ever runs — delete unconditionally wins. CRDT mode `'yjs'` is the\n * exception among CRDT modes: it never decrypts and falls back to a\n * plain higher-`_v`-wins compare, so an edit can beat a delete there too.\n */\nexport type ConflictPolicy<T> =\n | 'last-writer-wins'\n | 'first-writer-wins'\n | 'manual'\n | ((local: T, remote: T) => T)\n\n/**\n * Envelope-level resolver registered per collection with the SyncEngine.\n * Receives the `id` of the conflicting record and both envelopes.\n * Returns the winning envelope, or `null` to defer resolution.\n * @internal\n */\nexport type CollectionConflictResolver = (\n id: string,\n local: EncryptedEnvelope,\n remote: EncryptedEnvelope,\n) => Promise<EncryptedEnvelope | null>\n\n/** Options for targeted push operations. */\nexport interface PushOptions {\n /** Only push records belonging to these collections. Omit to push all dirty. */\n collections?: string[]\n}\n\n/** Options for targeted pull operations. */\nexport interface PullOptions {\n /** Only pull these collections. Omit to pull all. */\n collections?: string[]\n /**\n * Only pull records with `_ts` strictly after this ISO timestamp.\n * Stores that implement `listSince` use it directly; others fall back\n * to a full scan with client-side filtering.\n */\n modifiedSince?: string\n}\n\nexport interface PushResult {\n readonly pushed: number\n readonly conflicts: Conflict[]\n readonly errors: Error[]\n /** #590: tombstone enforcements applied during this run (never resolver-visible). */\n readonly erasures?: ErasureEnforcement[]\n}\n\nexport interface PullResult {\n readonly pulled: number\n readonly conflicts: Conflict[]\n readonly errors: Error[]\n /** #590: tombstone enforcements applied during this run (never resolver-visible). */\n readonly erasures?: ErasureEnforcement[]\n}\n\n/** Result of a sync transaction commit. */\nexport interface SyncTransactionResult {\n readonly status: 'committed' | 'conflict'\n readonly pushed: number\n readonly conflicts: Conflict[]\n /** #590: staged writes suppressed by tombstone enforcement during commit. */\n readonly erasures?: ErasureEnforcement[]\n}\n\nexport interface SyncStatus {\n readonly dirty: number\n readonly lastPush: string | null\n readonly lastPull: string | null\n readonly online: boolean\n}\n\n// ─── Sync Target ─────────────────────────────────────────\n\nexport type SyncTargetRole = 'sync-peer' | 'backup' | 'archive'\n\n/**\n * A sync target with role and optional per-target policy.\n *\n * | Role | Direction | Conflict resolution | Typical use |\n * |-------------|---------------|---------------------|--------------------------|\n * | `sync-peer` | Bidirectional | ConflictStrategy | DynamoDB live sync |\n * | `backup` | Push-only | N/A (receives merged)| S3 dump, Google Drive |\n * | `archive` | Push-only | N/A | IPFS, Git tags, S3 Lock |\n */\nexport interface SyncTarget {\n /** The store to sync with. */\n readonly store: NoydbStore\n /** Role determines sync direction and conflict handling. */\n readonly role: SyncTargetRole\n /** Per-target sync policy. Inherits store-category default when absent. */\n readonly policy?: SyncPolicy\n /** Human-readable label for DevTools and audit logs. */\n readonly label?: string\n}\n\n// ─── Events ────────────────────────────────────────────────────────────\n\nexport interface ChangeEvent {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly action: 'put' | 'delete'\n}\n\nexport interface NoydbEventMap {\n 'change': ChangeEvent\n 'error': Error\n /**\n * Same-instance signal that this vault's schema-fence state changed.\n * For UI integration. Cross-client coordination goes\n * through the store, not this event.\n */\n 'schema:fence-changed': { vault: string; currentSchemaVersion: number; fenceState: 'normal' | 'draining' | 'migrating' | 'complete' }\n 'sync:push': PushResult\n 'sync:pull': PullResult\n 'sync:erasure': ErasureEnforcement\n 'sync:conflict': Conflict\n 'write:conflict': WriteConflict\n 'sync:online': void\n 'sync:offline': void\n 'sync:backup-error': { vault: string; target: string; error: Error }\n 'history:save': { vault: string; collection: string; id: string; version: number }\n 'history:prune': { vault: string; collection: string; id: string; pruned: number }\n /**\n * A non-fatal i18n script violation under `onScriptViolation: 'warn' | 'filter'`.\n * 'warn' stored the value as-is; 'filter' stripped disallowed characters\n * (the event is the only signal the stored data was mutated). 'reject'\n * throws `ScriptViolationError` and emits nothing.\n */\n 'i18n:script-violation': {\n vault: string\n collection: string\n id: string\n mode: 'warn' | 'filter'\n warning: ScriptWarning\n }\n /**\n * Emitted when a persisted-index side-car put/delete fails after the\n * main record write already succeeded. The main record is durable; the\n * index mirror may have drifted. Operators reconcile via\n * `collection.reconcileIndex(field)`.\n */\n 'index:write-partial': {\n vault: string\n collection: string\n id: string\n action: 'put' | 'delete'\n error: Error\n }\n /**\n * emitted by `Collection.ensurePersistedIndexesLoaded()`\n * once per field on first lazy-mode query when\n * `reconcileOnOpen: 'auto' | 'dry-run'` is configured. `applied` is\n * `0` in `'dry-run'` mode. `skipped` is reserved for a future\n * drift-stamp optimization that short-circuits the reconcile when\n * the mirror version matches what's on disk — currently always\n * `false` (the full reconcile runs every session).\n */\n 'index:reconciled': {\n vault: string\n collection: string\n field: string\n missing: readonly string[]\n stale: readonly string[]\n applied: number\n skipped: boolean\n }\n /**\n * #638 Task 5 — a dispatch-driven derivation/rollup/MV output write targeted a row whose\n * period is closed. The write is SKIPPED (the historical value stands); the SOURCE write\n * that triggered the recompute still succeeded. See `kernel/via/dispatch.ts#putDerivedOutput`.\n * `source.id` may be a non-record sentinel (e.g. `'refreshView'`) for manual bulk-refresh-\n * triggered skips, not a real source record id.\n */\n 'derivation:skipped-frozen': DerivationSkippedFrozen\n /**\n * #654 — an ordinary-delete lookup-ref `cascade`/`nullify` propagation edge whose compare-key\n * could not be resolved from the backing row (matrix custom-key row unreadable — corruption\n * class). The delete itself proceeds (only `restrict` edges fail closed, via\n * `RestrictRefUnresolvableError`); this edge's propagation is skipped and reported here instead\n * of silently dropped — the ordinary-delete counterpart of the forget path's\n * `ForgetResult.lookupReferencesResidue` channel. `residue` entries are `backing:key:\n * collection.field`, one per un-propagated edge (see `VaultLinks.applyLookupRefsPropagation`).\n */\n 'lookup:propagation-residue': { vault: string; dimension: string; key: string; residue: readonly string[] }\n /**\n * #640 rider (#644 item 3) — the sync/cutover/restore dispatch wave's per-id recompute failed\n * (a genuine decrypt failure, a derive()/executor bug, a schema violation on the output, ...).\n * ADDITIVE to the existing `console.warn` in `runGraphDispatchWave` — never replaces it, so no\n * listener-dependent silence. One event per failed (collection, id); the wave still isolates\n * the failure to just that one record. See `kernel/via/dispatch.ts#runGraphDispatchWave`.\n */\n 'derivation:wave-error': { collection: string; id: string; error: unknown }\n}\n\n// ─── Grant / Revoke ────────────────────────────────────────────────────\n\nexport interface GrantOptions {\n readonly userId: string\n readonly displayName: string\n readonly role: Role\n readonly passphrase: string\n readonly permissions?: Permissions\n /**\n * Optional `@noy-db/as-*` export capability. Omit or\n * leave undefined to apply role-based defaults (see\n * `hasExportCapability` and `ExportCapability`).\n */\n readonly exportCapability?: ExportCapability\n /**\n * Optional `@noy-db/as-*` import capability (issue ). Omit or\n * leave undefined for default-closed semantics — no plaintext format\n * is grantable until positively listed; bundle import is denied.\n */\n readonly importCapability?: ImportCapability\n /**\n * Skip phrase-format strength validation (issue #7). Defaults to\n * false — `grant()` rejects phrases that don't meet the configured\n * `PassphrasePolicy`. Test fixtures and CLI scripts pass `true`.\n */\n readonly allowWeakPassphrase?: boolean\n /**\n * Initial user-envelope payload for the new principal. Sealed under\n * the same vault DEK (the reserved `_users` collection's DEK) and\n * persisted alongside the keyring during grant.\n *\n * **Bootstrap-only.** Once the new user activates and writes their\n * own envelope, the own-only write rule kicks in — admins cannot\n * edit a teammate's envelope after activation. Use this field for\n * pre-fill at invite time (e.g. \"displayName: Bob, locale: en-US\")\n * and let the user take over from there.\n *\n * Hub does not introspect the payload; it is JSON-serialized and\n * encrypted opaquely. Apps own the schema.\n *\n * @see docs/superpowers/specs/2026-05-05-user-envelope-design.md → Lifecycle\n */\n readonly initialProfile?: unknown\n}\n\n/**\n * Caller payload for `db.updateUser`. Mutate one or more\n * identity fields on an existing keyring without rotating any keys.\n *\n * `role`, `displayName`, and `permissions` live in the plaintext header\n * of `_keyring/<userId>` (the sync engine reads them without keys).\n * Mutating them is a JSON header swap — no DEK rewrap, no KEK\n * required, no authenticator slots touched. Tier-2 slots and recovery\n * enrollments survive unchanged. Last-write-wins through the existing\n * keyring put (same concurrency story as `db.grant` / `db.revoke`).\n *\n * Top-level fields are partial-merge: absent fields are not modified.\n * `null` on `displayName` clears the field (stored as the empty string;\n * UI consumers typically render the empty case by falling back to the\n * user id). `undefined` / absent leaves the field untouched. Mirrors\n * the `null`-as-clear convention `UserApi.updateMe` uses.\n *\n * `permissions`, however, is a **full replacement** at the map level —\n * passing `{ invoices: 'rw' }` REPLACES the entire permissions map,\n * silently dropping any other entries. To partially update, read the\n * current keyring and merge: `permissions: { ...current, invoices: 'rw' }`.\n * To clear all permissions, pass `permissions: {}` explicitly.\n *\n * Role-elevation guard: the same hierarchy as `db.grant`. Admins can\n * change `admin` / `operator` / `viewer` / `client` to and from each\n * other; admins cannot promote to or demote from `owner`. Owners can\n * do anything. Non-admin callers (operator/viewer/client) cannot call\n * `db.updateUser` at all — for self-displayName changes, use\n * `vault.user.updateMe` (the user-envelope API).\n */\nexport interface UpdateUserOptions {\n readonly userId: string\n readonly role?: Role\n readonly displayName?: string | null\n readonly permissions?: Permissions\n}\n\nexport interface RevokeOptions {\n readonly userId: string\n readonly rotateKeys?: boolean\n\n /**\n * Cascade behavior when the revoked user is an admin who has granted\n * other admins.\n *\n * - `'strict'` (default) — recursively revoke every admin that the\n * target (transitively) granted. The cascade walks the\n * `granted_by` field on each keyring file and stops at non-admin\n * leaves. All affected collections are accumulated and rotated in\n * a single pass at the end, so cascade cost is O(records in\n * affected collections), not O(records × cascade depth).\n *\n * - `'warn'` — leave the descendant admins in place but emit a\n * `console.warn` listing them. Useful for diagnostic dry runs and\n * for environments where the operator wants to clean up the\n * delegation tree manually.\n *\n * No effect when the target is not an admin (operators, viewers, and\n * clients cannot grant other users, so they have no delegation\n * subtree to cascade through). Defaults to `'strict'`.\n */\n readonly cascade?: 'strict' | 'warn'\n}\n\n// ─── Cross-vault queries ──────────────────────────────\n\n/**\n * One entry returned by `Noydb.listAccessibleVaults()`. Carries\n * the compartment id and the role the calling principal holds in it,\n * so the consumer can decide how to fan out without re-checking\n * permissions per vault.\n */\nexport interface AccessibleVault {\n readonly id: string\n readonly role: Role\n}\n\n/**\n * Options for `Noydb.listAccessibleVaults()`.\n */\nexport interface ListAccessibleVaultsOptions {\n /**\n * Minimum role the caller must hold to include a vault in the\n * result. Vaults where the caller's role is strictly *below*\n * this threshold are silently excluded. Defaults to `'client'`,\n * which means \"every vault I can unwrap is returned.\" Set to\n * `'admin'` for \"vaults where I can grant/revoke,\" or\n * `'owner'` for \"vaults I own.\"\n *\n * The privilege ordering used:\n * `client (1) < viewer (2) < operator (3) < admin (4) < owner (5)`\n *\n * Note: `viewer` and `client` are conceptually peers in the ACL\n * (neither can grant), but `viewer` has read-all access while\n * `client` has only explicit-collection read. The numeric order\n * reflects \"how much can this principal see,\" not \"how much can\n * this principal modify.\"\n */\n readonly minRole?: Role\n}\n\n/**\n * Options for `Noydb.queryAcross()`.\n */\nexport interface QueryAcrossOptions {\n /**\n * Maximum number of compartments to process in parallel. Defaults\n * to `1` (sequential) — conservative because the per-compartment\n * callback typically does its own I/O and an unbounded fan-out can\n * exhaust adapter connections (DynamoDB throughput, S3 socket\n * limits, browser fetch concurrency).\n *\n * Set to `4` or `8` for cloud-backed compartments where parallelism\n * is the whole point of fanning out. Set to `1` (default) for local\n * adapters where the disk I/O serializes anyway.\n */\n readonly concurrency?: number\n /**\n * Open shards non-creatingly — a missing grant throws instead of\n * self-provisioning. Default: `true` (create iff the vault has no\n * `_keyring/*`). Pass `false` for strict open-existing semantics\n * (e.g. federation read fan-out where shards are pre-provisioned\n * and an absent grant should fail closed).\n */\n readonly create?: boolean\n}\n\n/**\n * One entry in the array returned by `Noydb.queryAcross()`. Either\n * `result` is set (callback succeeded for this compartment) or\n * `error` is set (callback threw, or compartment failed to open).\n *\n * Per-compartment errors do **not** abort the overall fan-out — every\n * compartment is given a chance to run its callback, and the\n * partition between success and failure is exposed in the return\n * value. Consumers that want fail-fast semantics can check\n * `r.error !== undefined` and short-circuit themselves.\n */\nexport type QueryAcrossResult<T> =\n | { readonly vault: string; readonly result: T; readonly error?: undefined }\n | { readonly vault: string; readonly result?: undefined; readonly error: Error }\n\n// ─── User Info ─────────────────────────────────────────────────────────\n\nexport interface UserInfo {\n readonly userId: string\n readonly displayName: string\n readonly role: Role\n readonly permissions: Permissions\n readonly createdAt: string\n readonly grantedBy: string\n}\n\n// ─── Session ───────────────────────────────────────────────\n\n/**\n * Operations that a session policy can require re-authentication for.\n * Passed as the `requireReAuthFor` array in `SessionPolicy`.\n */\nexport type ReAuthOperation = 'export' | 'grant' | 'revoke' | 'rotate' | 'changeSecret'\n\n/**\n * Session policy controlling lifetime, re-auth requirements, and\n * background-lock behavior.\n *\n * All timeout values are in milliseconds. `undefined` means \"no limit.\"\n * The policy is evaluated lazily — it does not start timers itself;\n * enforcement happens at the Noydb call site.\n */\nexport interface SessionPolicy {\n /**\n * Idle timeout in ms. If no NOYDB operation is performed for this\n * duration, the session is revoked on the next operation attempt\n * (which will throw `SessionExpiredError`). The idle clock resets\n * on every successful operation.\n *\n * Default: `undefined` (no idle timeout).\n */\n readonly idleTimeoutMs?: number\n\n /**\n * Absolute timeout in ms from session creation. After this duration\n * the session is unconditionally revoked regardless of activity.\n *\n * Default: `undefined` (no absolute timeout).\n */\n readonly absoluteTimeoutMs?: number\n\n /**\n * Operations that require the user to re-authenticate (re-enter their\n * passphrase or perform a fresh WebAuthn assertion) before proceeding,\n * even if the session is still alive.\n *\n * Common pattern: `requireReAuthFor: ['export', 'grant']` — allow\n * read/write operations in the background but demand a fresh credential\n * for high-risk mutations.\n *\n * Default: `[]` (no extra re-auth requirements).\n */\n readonly requireReAuthFor?: readonly ReAuthOperation[]\n\n /**\n * If `true`, the session is revoked when the page goes to the background\n * (visibilitychange event, `document.hidden === true`). Useful for\n * high-sensitivity deployments where leaving the tab is treated as\n * a session boundary.\n *\n * No-op in non-browser environments (Node.js, workers without document).\n * Default: `false`.\n */\n readonly lockOnBackground?: boolean\n}\n\n// ─── i18n / Locale ─────────────────────────────────────\n\n/**\n * Locale-aware read options. Pass to `Collection.get()`, `list()`,\n * `query()`, and `scan()` to trigger per-record locale resolution for\n * `dictKey` and `i18nText` fields.\n *\n * - **`locale: 'raw'`** — skip resolution for `i18nText` fields and\n * return the full `{ [locale]: string }` map. Dict key fields still\n * return the stable key (no `<field>Label` added).\n * - **`fallback`** — single locale code or ordered list. Use `'any'` as\n * the last element to fall back to any present translation.\n *\n * When neither the call-level locale nor the compartment's default locale\n * is set, reading a record with `i18nText` fields throws\n * `LocaleNotSpecifiedError`.\n */\nexport interface LocaleReadOptions {\n /**\n * The target locale code (e.g. `'th'`), or `'raw'` to return the full\n * language map without resolution.\n */\n readonly locale?: string\n /**\n * Fallback locale or ordered fallback chain. Use `'any'` as the last\n * element to fall back to any present translation.\n */\n readonly fallback?: string | readonly string[]\n /**\n * @internal — the resolution layer this read belongs to (`'read'` by\n * default). Threaded by layer-tagged read facades (guard / derivation)\n * so `applyI18nLocale` and dictKey `resolvePolicy` select that layer's\n * `onMissing` policy instead of the `'read'` policy. Not part of the\n * public read API — callers select policy via the field's `onMissing`\n * map, not by setting this.\n */\n readonly _layer?: Layer\n}\n\n// ─── plaintextTranslator hook ──────────────────────────────\n\n/**\n * Context passed to the consumer-supplied `plaintextTranslator` function.\n * The hook receives the source text plus enough metadata to route it to the\n * right translation service and record what it did.\n */\nexport interface PlaintextTranslatorContext {\n /** The plaintext string to translate. */\n readonly text: string\n /** BCP 47 source locale (the locale the text is written in). */\n readonly from: string\n /** BCP 47 target locale to translate into. */\n readonly to: string\n /** The schema field name that triggered the translation. */\n readonly field: string\n /** The collection the record is being put into. */\n readonly collection: string\n}\n\n/**\n * A consumer-supplied async function that translates a single string\n * from one locale to another. noy-db ships no built-in translator.\n *\n * **Security:** this function receives plaintext. The consumer is\n * responsible for the data policy of whatever service it calls. See\n * `NOYDB_SPEC.md § Zero-Knowledge Storage` and the `plaintextTranslator`\n * JSDoc on `NoydbOptions` for the full invariant statement.\n */\nexport type PlaintextTranslatorFn = (\n ctx: PlaintextTranslatorContext,\n) => Promise<string>\n\n/**\n * One entry in the in-process translator audit log. Cleared when\n * `db.close()` is called — same lifetime as the KEK and DEKs.\n *\n * Deliberately omits any content hash or translated-text fingerprint\n * to prevent correlation attacks on the audit trail.\n */\nexport interface TranslatorAuditEntry {\n readonly type: 'translator-invocation'\n /** Schema field name that was translated. */\n readonly field: string\n /** Collection the record belongs to. */\n readonly collection: string\n /** Source locale. */\n readonly fromLocale: string\n /** Target locale. */\n readonly toLocale: string\n /**\n * Consumer-provided translator name from\n * `NoydbOptions.plaintextTranslatorName`. Defaults to `'anonymous'`\n * when not supplied.\n */\n readonly translatorName: string\n /** ISO 8601 timestamp of the invocation. */\n readonly timestamp: string\n /**\n * `true` when the result was served from the in-process cache rather\n * than by calling the translator function. Present only on cache hits\n * so the absence of the field also communicates a cache miss.\n */\n readonly cached?: true\n}\n\n// ─── Presence ─────────────────────────────────────────────\n\n/**\n * A presence peer entry. `lastSeen` is an ISO timestamp set by core on each\n * `update()` call. Stale entries (lastSeen older than `staleMs`) are filtered\n * before delivering to the subscriber callback.\n */\nexport interface PresencePeer<P> {\n readonly userId: string\n readonly payload: P\n readonly lastSeen: string\n}\n\n// ─── CRDT ─────────────────────────────────────────────────\n\n/** Per-collection CRDT mode. */\nexport type CrdtMode = 'lww-map' | 'rga' | 'yjs'\n\n// Hoisted from with-commit/crdt/crdt.ts (C3 — #667: breaks the\n// types.ts ↔ crdt.ts cycle by making crdt.ts's re-export of these\n// three types leaf-ward only). crdt.ts re-exports them from here so\n// existing importers of that module are unaffected.\n\n/**\n * Per-field last-write-wins registers.\n * Each field carries its latest value and the ISO timestamp of the last write.\n * Merge: for each field, keep the entry with the lexicographically higher `ts`.\n */\nexport interface LwwMapState {\n readonly _crdt: 'lww-map'\n readonly fields: Record<string, { readonly v: unknown; readonly ts: string }>\n}\n\n/**\n * Simplified Replicated Growable Array.\n * Items are assigned stable NID (noy-db id) strings on first insertion.\n * Deleted items are tracked as tombstones so concurrent removals commute.\n *\n * The resolved snapshot is the ordered list of non-tombstoned `v` values.\n */\nexport interface RgaState {\n readonly _crdt: 'rga'\n readonly items: ReadonlyArray<{ readonly nid: string; readonly v: unknown }>\n readonly tombstones: readonly string[]\n}\n\n/**\n * Yjs binary state marker. `update` is base64(Y.encodeStateAsUpdate()).\n * Core stores and retrieves the blob opaquely. `@noy-db/yjs` is responsible\n * for encoding, decoding, and merging via `Y.mergeUpdates`.\n * Core falls back to last-write-wins (higher `_v`) for conflict resolution.\n */\nexport interface YjsState {\n readonly _crdt: 'yjs'\n /** base64-encoded Y.encodeStateAsUpdate() bytes. */\n readonly update: string\n}\n\nexport type CrdtState = LwwMapState | RgaState | YjsState\n\n/**\n * Seam interface. `@internal`.\n *\n * @internal\n */\nexport interface CrdtStrategy {\n buildLwwMapState(\n record: Record<string, unknown>,\n previous: LwwMapState | undefined,\n now: string,\n ): LwwMapState\n buildRgaState(\n items: readonly unknown[],\n previous: RgaState | undefined,\n idGen: () => string,\n ): RgaState\n mergeCrdtStates(local: CrdtState, remote: CrdtState): CrdtState\n resolveCrdtSnapshot(state: CrdtState): unknown\n}\n\n// ─── Blob / Attachment Store ────────────────────────\n\n/**\n * Second store shape for blob-store backends (Drive, WebDAV, Git, iCloud)\n * that operate on whole-vault bundles rather than per-record KV.\n *\n * Implement `readBundle` / `writeBundle` instead of the six-method KV\n * contract. Use `wrapBundleStore()` from `@noy-db/hub` to convert to a\n * `NoydbStore` that the rest of the API consumes transparently.\n *\n * Named `NoydbPodStore` (not `NoydbBundleAdapter`) for consistency\n * with the hub / to-* / in-* rename. Concrete implementations ship\n * in `@noy-db/to-*` packages starting in.\n */\nexport interface NoydbPodStore {\n /** Discriminant for engine auto-detection of store shape. */\n readonly kind: 'bundle'\n /** Human-readable name for diagnostics (e.g. `'drive'`, `'webdav'`). */\n readonly name?: string\n /**\n * Read the entire vault as raw bytes. Returns `null` if no bundle exists\n * yet (first open of a brand-new vault).\n */\n readBundle(vaultId: string): Promise<{ bytes: Uint8Array; version: string } | null>\n /**\n * Write the entire vault as raw bytes. `expectedVersion` is the version\n * token from the last `readBundle` (or `null` for a first write).\n * Implementations MUST reject the write if the stored version has advanced\n * past `expectedVersion` — throw `PodVersionConflictError`.\n * Returns the new version token on success.\n */\n writeBundle(\n vaultId: string,\n bytes: Uint8Array,\n expectedVersion: string | null,\n ): Promise<{ version: string }>\n /** Delete a vault bundle. Idempotent — no-op if the bundle does not exist. */\n deleteBundle(vaultId: string): Promise<void>\n /** List all vault bundles managed by this store. */\n listBundles(): Promise<Array<{ vaultId: string; version: string; size: number }>>\n}\n\n/** @deprecated Use `NoydbPodStore`. */\nexport type NoydbBundleStore = NoydbPodStore\n\n/**\n * Content-addressed blob object stored in the vault-level blob index.\n * Identified by HMAC-SHA-256(blobDEK, plaintext) — opaque to the store.\n *\n * Shared across all collections within a vault for deduplication: two\n * records that attach identical byte content reference the same `eTag`\n * and share a single set of encrypted chunks in `_blob_chunks`.\n */\nexport interface BlobObject {\n /** HMAC-SHA-256 hex of the original plaintext bytes, keyed by `_blob` DEK. */\n readonly eTag: string\n /** Original uncompressed size in bytes. */\n readonly size: number\n /** Compressed size in bytes (the payload that is actually encrypted and chunked). */\n readonly compressedSize: number\n /** Compression algorithm applied before encryption. */\n readonly compression: 'gzip' | 'none'\n /** Raw chunk size in bytes used at write time. Readers MUST use this value. */\n readonly chunkSize: number\n /** Total number of chunks written. Reader expects exactly this many. */\n readonly chunkCount: number\n /** MIME type if provided or auto-detected at upload time. */\n readonly mimeType?: string\n /** ISO timestamp of first upload. */\n readonly createdAt: string\n /** Live reference count — slots + published versions pointing to this blob. */\n readonly refCount: number\n /**\n * Base64 AES-KW-wrapped per-blob **content CEK** (wrapped under the `_blob`\n * DEK). Present on erasable-collection blobs (`perRecordKeys`): the chunks\n * are encrypted under this content CEK rather than directly under the `_blob`\n * DEK, so deleting this BlobObject at `refCount → 0` crypto-shreds the chunks\n * (they become permanently undecryptable). Absent → legacy blob, chunks\n * decrypt directly under the `_blob` DEK (read unchanged). See\n * docs/superpowers/specs/2026-06-13-per-blob-cek-design.md.\n */\n readonly _cek?: string\n /**\n * Transient migration marker. Present only while a legacy\n * blob is being migrated to a content CEK: it holds the wrapped content CEK\n * BEFORE the chunks have been re-encrypted under it. Readers **ignore**\n * `_cekPending` (they key off `_cek`), so the blob stays readable under the\n * `_blob` DEK during migration AND the content CEK survives a crash → a\n * re-run resumes and promotes `_cekPending` → `_cek`. Never set on a settled blob.\n */\n readonly _cekPending?: string\n /**\n * Hint indicating which store holds the chunk data.\n * Used by `routeStore` size-tiered routing: `'default'` for small blobs\n * stored inline (e.g. DynamoDB), `'blobs'` for large blobs in the overflow\n * store (e.g. S3). Absent when no routing is configured.\n */\n readonly storeHint?: 'default' | 'blobs'\n}\n\n/**\n * Slot record — mutable metadata linking a named slot on a record\n * to a `BlobObject` via its eTag.\n *\n * Multiple slots (even across different records) may reference the same\n * `eTag` — the underlying chunks are shared. Updating metadata creates\n * a new envelope version (`_v++`) while the blob data is unchanged.\n */\nexport interface SlotRecord {\n /**\n * Reference to the `BlobObject` in `_blob_index` (chunk-based blobs).\n * Empty string (`''`) for an `external` slot, whose bytes live in the\n * `ObjectProjection` rather than `_blob_chunks` — read `external` instead.\n */\n readonly eTag: string\n /**\n * External-projection reference. Present when the blob field is declared\n * `external`: the raw bytes live in the vault's `ObjectProjection` at `key`\n * (unencrypted), not in `_blob_chunks`. This slot record (in the encrypted\n * collection) remains the catalog entry — the anchoring invariant.\n */\n readonly external?: {\n readonly key: string\n readonly contentType?: string\n readonly public?: boolean\n /** Opaque-token backlink stamped on the object (when `backlink:'opaque-token'`). */\n readonly backlink?: string\n /**\n * Secondary metadata store synced from the object / its processing pipeline\n * (e.g. video `duration`, image `width`/`height`, arbitrary metatags).\n * Populated via `BlobSet.setExternalMeta()` — typically an AWS-side callback.\n */\n readonly meta?: Record<string, unknown>\n }\n /** User-visible filename for the slot. */\n readonly filename: string\n /** Original uncompressed size in bytes (denormalized from `BlobObject`). */\n readonly size: number\n /** MIME type. Takes precedence over the MIME type stored in `BlobObject`. */\n readonly mimeType?: string\n /** ISO timestamp of the upload that set this slot. */\n readonly uploadedAt: string\n /** User ID of the uploader, if available. */\n readonly uploadedBy?: string\n}\n\n/** Result of `BlobSet.list()` — slot record plus its named slot key. */\nexport interface SlotInfo extends SlotRecord {\n /** The slot name (key in the record's slot map). */\n readonly name: string\n}\n\n/**\n * Explicitly published version snapshot — an independent reference to a\n * blob at a specific point in time.\n */\nexport interface VersionRecord {\n /** User-defined label (e.g. `'issued-2025-01'`, `'amendment-2025-02'`). */\n readonly label: string\n /** eTag of the blob snapshot at publish time — independent of the current slot. */\n readonly eTag: string\n /** ISO timestamp when the version was published. */\n readonly publishedAt: string\n /** User ID of the publisher, if available. */\n readonly publishedBy?: string\n}\n\n/** Options for `BlobSet.put()`. */\nexport interface BlobPutOptions {\n /** MIME type hint. If omitted, auto-detected from magic bytes. */\n mimeType?: string\n /**\n * Raw chunk size in bytes. Priority: this value > store.maxBlobBytes > 256 KB.\n */\n chunkSize?: number\n /**\n * Whether to gzip-compress bytes before encrypting. Default: `true`.\n * Auto-set to `false` for pre-compressed MIME types (JPEG, PNG, ZIP, etc.).\n */\n compress?: boolean\n /** User ID to record as `uploadedBy`. Defaults to the Noydb session user. */\n uploadedBy?: string\n /**\n * User-visible filename to store on the slot. Defaults to the slot name.\n * Differs from the slot name when the caller wants a display/download name\n * (e.g. slot `attachment` holding `invoice-2024.pdf`); this is the value\n * that the L1 lexical index tokenizes for blob fields.\n */\n filename?: string\n}\n\n/** Options for `BlobSet.response()` and `BlobSet.responseVersion()`. */\nexport interface BlobResponseOptions {\n /**\n * When `true`, sets `Content-Disposition: inline; filename=\"...\"` so\n * the browser renders the file in the tab. Default (`false`) sets\n * `attachment; filename=\"...\"` which triggers a download.\n */\n inline?: boolean\n /** Override the filename in the Content-Disposition header. */\n filename?: string\n}\n\n// ─── Store Capabilities ─────────────────────────────\n\nexport type StoreAuthKind =\n | 'none'\n | 'filesystem'\n | 'api-key'\n | 'iam'\n | 'oauth'\n | 'kerberos'\n | 'browser-origin'\n\nexport interface StoreAuth {\n kind: StoreAuthKind | StoreAuthKind[]\n required: boolean\n flow: 'static' | 'oauth' | 'kerberos' | 'implicit'\n}\n\n/** Vendor-neutral short-lived store credentials. `kind` is the credential-PAYLOAD\n * discriminator — orthogonal to StoreAuthKind ('iam'|'api-key'|…), which is unchanged. */\nexport type StoreCredentials =\n | { readonly kind: 'aws'\n readonly accessKeyId: string\n readonly secretAccessKey: string\n readonly sessionToken?: string\n readonly expiresAt?: string } // ISO 8601\n | { readonly kind: 'token' // postgres/turso/supabase/webdav/bearer — a LATER slice\n readonly token: string\n readonly expiresAt?: string }\n\n/** Refresh hook a store calls when it has no credentials or they are near expiry. */\nexport type StoreCredentialSource = () => Promise<StoreCredentials>\n\n/**\n * The store's authoritative clock as a bounded-uncertainty interval\n * (Spanner TrueTime model). True time is provably within [earliest, latest];\n * `latest - earliest` is the clock-uncertainty bound ε. Used by deferred\n * numbering to order records by store-commit-time and to commit-wait. Never\n * the client wall clock.\n */\nexport interface StoreTime {\n readonly earliest: number\n readonly latest: number\n}\n\nexport interface StoreCapabilities {\n /**\n * true — the store's expectedVersion check and write are atomic at the\n * storage layer. Two concurrent puts with the same expectedVersion will\n * produce exactly one success and one ConflictError.\n * false — check and write are separate operations with a race window.\n */\n casAtomic: boolean\n /**\n * true — the store exposes an authoritative {@link NoydbStore.getStoreTime}\n * clock and records are ordered by store-commit-time. Required for\n * `withDeferredNumbering`. Absent/false — the store cannot back deferred\n * numbering (use CAS `sequence().next()` or per-series).\n */\n serverWriteTime?: boolean\n /**\n * Advisory geographic region this store serves (e.g. `'eu'`, `'us'`).\n * Purely declarative — no behavior change for stores that omit it. The\n * federation data-residency guard compares this against a\n * `sharding.regionOf(record)` to refuse non-compliant shard placement.\n */\n region?: string\n auth: StoreAuth\n /**\n * true — the store implements {@link NoydbStore.tx} and commits\n * every op atomically at the storage layer. The hub's\n * `db.transaction(fn)` will delegate to `tx(ops)` and surface a\n * single pass/fail outcome. false (or absent) — no native\n * multi-record atomicity; the hub falls back to per-record OCC\n * with best-effort unwind on partial failure.\n */\n txAtomic?: boolean\n /**\n * Maximum raw bytes per blob chunk record.\n * `undefined` — no limit (S3, file, IDB); blob stored as single chunk.\n * `256 * 1024` — DynamoDB (400 KB item limit minus envelope overhead).\n * `5 * 1024 * 1024` — localStorage quota safety.\n */\n maxBlobBytes?: number\n /**\n * true — the store is a tiered router (`routeStore`) with a cold route,\n * so `compact(vault, { before })` can relocate records hot → cold and\n * reads fall through to cold. `vault.archivePeriod()` requires this.\n */\n coldArchival?: boolean\n}\n\n// ─── Factory Options ───────────────────────────────────────────────────\n\nexport interface NoydbOptions {\n /** The ciphertext store. Optional — defaults to the built-in `memoryStore()` (non-persistent). */\n readonly store?: NoydbStore\n /**\n * tree-shake seam — optional blob strategy. Pass `withBlobs()`\n * from `@noy-db/hub/blobs` to enable `collection.blob(id)` storage.\n * When omitted, hub's blob machinery stays out of the bundle (ESM\n * tree-shaking) and `collection.blob(id)` throws with a pointer at\n * the subpath. `BlobStrategy` is `@internal` — users only construct\n * it via the subpath factory.\n *\n * @internal\n */\n readonly blobStrategy?: BlobStrategy\n /**\n * Cold-storage archival target. `withArchive({ store })` designates a\n * second store that holds archived record envelopes. Enables\n * `vault.archive()` / `vault.restore()` / `vault.listArchived()`.\n */\n readonly archiveStrategy?: ArchiveStrategy\n /**\n * tree-shake seam — optional indexing strategy. Pass\n * `withIndexing()` from `@noy-db/hub/indexing` to enable eager-mode\n * `==/in` fast-paths, lazy-mode `.lazyQuery()`, rebuild/reconcile,\n * and auto-reconcile. When omitted, indexing code never reaches the\n * bundle; `.lazyQuery()` throws with a pointer at the subpath, and\n * eager-mode collections fall back to linear scans regardless of\n * `indexes: [...]` declarations. `IndexStrategy` is `@internal` —\n * users only construct it via the subpath factory.\n *\n * @internal\n */\n readonly indexStrategy?: IndexStrategy\n /**\n * tree-shake seam — optional aggregate strategy. Pass\n * `withAggregate()` from `@noy-db/hub/aggregate` to enable\n * `.aggregate()` and `.groupBy()` on Query. When omitted, those\n * methods throw with a pointer at the subpath; the ~886 LOC of\n * Aggregation + GroupedQuery machinery never reaches the bundle.\n * Streaming `scan().aggregate()` works independently of this\n * strategy — it doesn't use the `Aggregation` class.\n *\n * @internal\n */\n readonly aggregateStrategy?: AggregateStrategy\n /**\n * tree-shake seam — optional CRDT strategy. Required when\n * any collection is declared with `crdt: 'lww-map' | 'rga' | 'yjs'`;\n * otherwise the first put/sync-merge hitting the CRDT path throws.\n * When omitted, ~221 LOC of LWW-Map / RGA / merge helpers never\n * reach the bundle.\n *\n * @internal\n */\n readonly crdtStrategy?: CrdtStrategy\n /**\n * tree-shake seam — strategy for the collection-level hierarchical-tier\n * operations. Pass `withTiers()` from `@noy-db/hub/tiers` to enable\n * `putAtTier`/`getAtTier`/`listAtTier`/`elevate`/`demote` on collections\n * declared with `{ tiers: [...] }`. When omitted, all five throw\n * `TiersNotEnabledError` and the tier read/write/re-key engine never\n * reaches the bundle.\n *\n * @internal\n */\n readonly tiersStrategy?: TiersStrategy\n /**\n * tree-shake seam — optional consent-audit strategy. Pass\n * `withConsent()` from `@noy-db/hub/consent` to enable per-op audit\n * writes into `_consent_audit` when a consent scope is active.\n * When omitted, `vault.consentAudit()` returns `[]` and writes are\n * no-ops; the consent module's ~194 LOC never reaches the bundle.\n *\n * @internal\n */\n readonly consentStrategy?: ConsentStrategy\n /**\n * tree-shake seam — optional periods strategy. Pass\n * `withPeriods()` from `@noy-db/hub/periods` to enable\n * `vault.closePeriod()` / `.openPeriod()` / write-guard on closed\n * periods. When omitted, `vault.listPeriods()` returns `[]` and\n * the write-guard is a no-op; the ~363 LOC of period validation +\n * ledger appending stay out of the bundle.\n *\n * @internal\n */\n readonly periodsStrategy?: PeriodsStrategy\n /**\n * tree-shake seam — optional VaultFrame strategy. Pass\n * `withShadow()` from `@noy-db/hub/shadow` to enable\n * `vault.frame()`. Without it, calling `vault.frame()` throws.\n *\n * @internal\n */\n readonly shadowStrategy?: ShadowStrategy\n /**\n * tree-shake seam — optional multi-record transactions. Pass\n * `withTransactions()` from `@noy-db/hub/tx` to enable\n * `db.transaction(fn)`. Without it, calling the method throws.\n *\n * @internal\n */\n readonly txStrategy?: TxStrategy\n /**\n * tree-shake seam — optional history + ledger + time-machine.\n * Pass `withHistory()` from `@noy-db/hub/history` to enable\n * per-record version snapshots, the hash-chained audit ledger, JSON\n * Patch deltas, `vault.ledger()`, `vault.at()`, and the\n * `collection.history()` / `getVersion()` / `revert()` / `diff()` /\n * `clearHistory()` / `pruneRecordHistory()` read APIs. When omitted,\n * snapshots/prune/clear are silent no-ops, the read APIs throw with\n * a pointer at the subpath, and ~1,880 LOC stay out of the bundle.\n *\n * @internal\n */\n readonly historyStrategy?: HistoryStrategy\n /**\n * GDPR right-to-erasure. Pass `withForgetCascade({ subjects })`\n * from `@noy-db/hub/forget` to declare which collections carry erasable\n * subject data and the record field naming the data subject. Enables\n * `vault.forget(subjectId)` crypto-shred (rewrite-to-tombstone of the live\n * record + every history version → body permanently undecryptable, single\n * `op:'forget'` ledger entry, chain still verifies). Each declared\n * collection is forced to `perRecordKeys: true`. When omitted (the\n * `NO_FORGET` default), `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` and no subject-index write hooks run.\n * Requires `historyStrategy` (the ledger) for the erasure-proof entry.\n */\n readonly forgetStrategy?: ForgetStrategy\n /**\n * tree-shake seam — optional i18n strategy. Pass `withI18n()`\n * from `@noy-db/hub/i18n` to enable `i18nText`/`dictKey` field\n * resolution on reads, `i18nText` validation on writes, and\n * `vault.dictionary(name)`. When omitted, locale resolution is the\n * identity (raw values returned), the validators throw with a\n * pointer to the subpath, and ~854 LOC of dictionary + locale\n * machinery stay out of the bundle.\n *\n * @internal\n */\n readonly i18nStrategy?: I18nStrategy\n /**\n * tree-shake seam — optional session-policy strategy. Pass\n * `withSession()` from `@noy-db/hub/session` to enable\n * `sessionPolicy` validation, `PolicyEnforcer` lifecycle (idle /\n * absolute timeouts, lockOnBackground), and global session-token\n * revocation. When omitted, setting `sessionPolicy` throws at\n * `createNoydb()` time, and ~495 LOC of policy + token machinery\n * stay out of the bundle.\n *\n * @internal\n */\n readonly sessionStrategy?: SessionStrategy\n /**\n * tree-shake seam — optional sync engine + presence strategy.\n * Pass `withSync()` from `@noy-db/hub/sync` to enable\n * `db.push()` / `pull()` / replication, `db.transaction(vault)`\n * for sync-aware transactions, and `collection.presence()`. When\n * omitted, configuring `sync` / calling these surfaces throws with\n * a pointer at the subpath, and ~856 LOC of replication + presence\n * machinery stay out of the bundle. Keyring stays core; grant/\n * revoke/magic-link/delegation tree-shake via direct imports.\n *\n * @internal\n */\n readonly syncStrategy?: SyncStrategy\n /**\n * Tree-shake seam — optional snapshot-lifecycle service. Pass\n * `withSnapshots({ store })` from `@noy-db/hub/snapshots` to enable\n * `db.snapshot()`, `db.listSnapshots()`, and `db.restoreSnapshot()`.\n * When omitted, all three methods throw with a pointer at the subpath.\n */\n readonly snapshotStrategy?: SnapshotStrategy\n /**\n * Tree-shake seam — optional attestation capability. Pass\n * `withAttestation()` from `@noy-db/hub/attestation` to enable\n * `vault.issueAttestation()`, `vault.getDocumentSigningPublicKey()`,\n * `vault.revokeAttestation()`, `vault.unrevokeAttestation()`,\n * `vault.getRevokedDocIds()`, and `vault.publishRevocationList()`. When\n * omitted, all six throw `AttestationNotEnabledError` and the issue/revoke/\n * signer engines are tree-shaken out.\n */\n readonly attestationStrategy?: AttestationStrategy\n /**\n * Tree-shake seam — optional classified-field capability. Pass\n * `withClassified()` from `@noy-db/hub/classified` to enable\n * `collection.reveal()`. When omitted, `reveal()` throws\n * `ClassifiedNotEnabledError` and the reveal engine is tree-shaken out.\n */\n readonly classifiedStrategy?: ClassifiedStrategy\n /**\n * Tree-shake seam — optional sealed-record (grantor-side) capability. Pass\n * `withSealedRecord()` from `@noy-db/hub/sealed-record` to enable\n * `vault.sealRecordToHost()`, `vault.revokeSealedRecord()`, and\n * `vault.rotateRecordCek()`. When omitted, all three throw\n * `SealedRecordNotEnabledError` and the record-keys grantor engine is reached\n * only via opt-in. The host-side `openSealedRecord` opener stays ungated.\n */\n readonly sealedRecordStrategy?: SealedRecordStrategy\n /**\n * Tree-shake seam — optional portability (data-sovereignty) capability. Pass\n * `withPortability()` from `@noy-db/hub/portability` to enable the\n * `vault.user.*` export/withdrawal surface (`exportMyAccessibleData`,\n * `unilateralWithdrawal`, `requestWithdrawal`, `listWithdrawalRequests`,\n * `approveWithdrawal`, `rejectWithdrawal`). When omitted, all six throw\n * `PortabilityNotEnabledError` and the export/withdraw/request engines are\n * reached only via opt-in.\n */\n readonly portabilityStrategy?: PortabilityStrategy\n /**\n * Tree-shake seam — optional atomic-sequence capability. Pass\n * `withSequence()` from `@noy-db/hub` to enable `vault.sequence(name)`\n * (`.next()` / `.peek()` / `.seedTo()`). When omitted, `vault.sequence()`\n * throws `SequenceNotEnabledError` and the CAS `SequenceStore` engine is\n * reached only via opt-in. Deferred-numbering series (`numbering:\n * [withDeferredNumbering(...)]`) are a separate capability and stay live.\n */\n readonly sequenceStrategy?: SequenceStrategy\n /**\n * Tree-shake seam — optional sovereign-custody (FR-6) capability. Pass\n * `withCustody()` from `@noy-db/hub` to enable minting / removing a\n * `custodian` (`db.grantCustodian` / `db.revokeCustodian` and the\n * `vault.custody.*` facade) plus the `vault.custody.liberate()` ceremony.\n * When omitted, those throw `CustodyNotEnabledError` and the liberate engine\n * is reached only via opt-in. The lower-level `liberateVault` free function\n * stays ungated (it has no createNoydb instance to gate against).\n */\n readonly custodyStrategy?: CustodyStrategy\n /**\n * Tree-shake seam — optional multi-user team capability (#267\n * keyring-grant → team split). Pass `withTeam()` from `@noy-db/hub/team`\n * to enable `db.grant` / `db.revoke` / `db.rotate`. When omitted, those\n * throw `TeamNotEnabledError` and the keyring grant/revoke/rotate engines\n * are reached only via opt-in — the always-on floor is single-user.\n * Single-user primitives (owner keyring, unlock, `listUsers`,\n * `updateUser`, passphrase rotate/recover) stay ungated, as does the\n * `createDeedOwner` free function (no createNoydb instance to gate\n * against).\n */\n readonly teamStrategy?: TeamStrategy\n /**\n * Tree-shake seam — optional credential-broker capability (#479). Pass\n * `brokerStrategy: withBroker(config)` from `@noy-db/hub/broker` to\n * enable `vault.broker()` (`.enroll()` / `.rotate()` /\n * `.credentialSource(profile?)`). When omitted, `vault.broker()` throws\n * `BrokerNotEnabledError` and the seed lifecycle + network/cache engine\n * are reached only via opt-in.\n */\n readonly brokerStrategy?: BrokerStrategy\n /**\n * Opt-in seam — the `lazy` service (#267). Pass `withLazy()` from\n * `@noy-db/hub/lazy` to explicitly enable lazy mode's bounded-LRU\n * working set for collections declared with `prefetch: false`. When\n * omitted, `prefetch: false` still works via the deprecated implicit\n * back-compat path (identical behavior, one-time deprecation warn);\n * the implicit path will be removed at 1.0.\n */\n readonly lazyStrategy?: LazyStrategy\n /**\n * Tree-shake seam — optional search / retrieval capability. Pass\n * `withSearch()` from `@noy-db/hub` to enable a collection's `search`\n * / `retrieve` / `similarTo` / `warmIndex` / `flushIndex` methods and the\n * put()-time embedding-vector compute for collections declaring `embeddings`.\n * When omitted, those throw `SearchNotEnabledError` and the search/retrieval\n * engine is reached only via opt-in. Embedding compute is paired with search\n * (a vector no gated retrieval could read would be dead weight).\n */\n readonly searchStrategy?: SearchStrategy\n /**\n * Tree-shake seam — optional cargo (partition extraction) capability\n * (FR-6/FR-7). Pass `withCargo()` from `@noy-db/hub/cargo` to enable the\n * source-side `extractPartition(vault, …)` free function. When omitted, it\n * throws `CargoNotEnabledError` and the extraction crypto is reached only via\n * opt-in. The recipient-side `adoptPartition` / `decryptExtractedPartition`\n * free functions — and `diffVault` (shared import/merge infra) — operate\n * without a gated source instance and stay ungated.\n */\n readonly cargoStrategy?: CargoStrategy\n /**\n * Optional guard strategies — collection-level write guards. Each\n * handle is the output of `withGuard()` from `@noy-db/hub/guards`.\n * Multiple guards per collection are allowed; they are dispatched\n * in registration order on `collection.put()`.\n */\n readonly guardStrategies?: ReadonlyArray<GuardStrategyHandleAny>\n /**\n * Deferred-numbering series declared via `withDeferredNumbering(...)`.\n * `vault.sequence(series).next({ for })` then assigns gap-free serials at a\n * numbering pass (`vault.runNumberingPass(series)`) instead of via CAS.\n */\n readonly numbering?: ReadonlyArray<DeferredNumberingConfig>\n /**\n * Optional derivation strategies — source-to-output projections that\n * fire on `collection.put()`. Each handle is the output of\n * `withDerivation()` from `@noy-db/hub/derivations`. The vault\n * validates the derivation graph for cycles on `openVault`; a cyclic\n * graph throws `DerivationCycleError`.\n */\n readonly derivationStrategies?: ReadonlyArray<DerivationStrategyHandle>\n /**\n * Optional materialized-view strategies.\n * Each handle returned by `withMaterializedView()` from\n * `@noy-db/hub/materialized-views`. The vault runs unified cycle\n * detection across the MV + derivation graphs at `openVault`; a\n * cyclic graph throws `MaterializedViewCycleError`.\n */\n readonly materializedViewStrategies?: ReadonlyArray<MaterializedViewStrategyHandle>\n /**\n * Optional overlay strategies. Each handle returned by\n * `withOverlayedView()` from `@noy-db/hub/overlay-views`. The vault\n * validates name uniqueness + base concreteness + overlay\n * availability at `openVault`; a clash throws one of the\n * `Overlay*Error` family.\n */\n readonly overlayedViewStrategies?: ReadonlyArray<OverlayedViewStrategyHandle>\n /** Optional remote store(s) for sync. Accepts a single store, a SyncTarget, or an array. */\n readonly sync?: NoydbStore | SyncTarget | SyncTarget[]\n /** User identifier. */\n readonly user: string\n /** Passphrase for key derivation. Required unless encrypt is false or `getKeyring` is provided. */\n readonly secret?: string\n /**\n * Optional callback that returns an unlocked keyring for a given vault.\n * Use this to plug in WebAuthn / OIDC / Shamir / any unlock path that\n * produces an `UnlockedKeyring` outside the passphrase model.\n *\n * When set, `secret` MUST NOT also be set — `createNoydb` throws if both\n * are supplied. When neither is set (and `encrypt !== false`), `createNoydb`\n * also throws.\n *\n * The callback is called lazily, on the first operation that needs the\n * keyring for a given vault. Noydb caches the returned keyring per-vault\n * for the lifetime of the instance, so the callback is invoked at most\n * once per `(instance, vault)` pair (assuming the callback resolves\n * successfully). If the callback rejects, the rejection surfaces from the\n * first vault operation that triggered the unlock; subsequent operations\n * will retry the callback.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { unlockWebAuthn } from '@noy-db/on-webauthn'\n *\n * const enrollment = await loadEnrollment()\n * const db = await createNoydb({\n * store,\n * user: 'alice',\n * getKeyring: (vault) => unlockWebAuthn(enrollment),\n * })\n * ```\n *\n * Note: this callback is responsible for both the \"open existing vault\"\n * and the \"create new vault\" cases. Unlike the passphrase path, there is\n * no automatic `NoAccessError` → `createOwnerKeyring` fallback, because\n * the callback owner has the UI context to decide which path to run.\n * For first-time bootstrap, use a passphrase or recovery code, enroll\n * WebAuthn from the unlocked keyring, then swap to `getKeyring` on\n * subsequent sessions.\n */\n readonly getKeyring?: (vault: string) => Promise<UnlockedKeyring>\n /**\n * Passphrase mode. Default `'standard'`.\n *\n * - `'standard'` — the legacy flow. `secret` supplies the\n * plaintext passphrase, the user knows it, and the policy gate\n * `rotate-passphrase` is enabled.\n * - `'managed'` — rubber-hose-resistant mode. Hub generates a\n * 256-bit random passphrase at first open and seals it under\n * the provided `sealingKey`. The user never sees or types the\n * passphrase, defeating the $5-wrench attack. Mutually\n * exclusive with `secret` and `getKeyring`.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Managed-passphrase mode\n */\n readonly passphraseMode?: 'standard' | 'managed'\n /**\n * Provider that seals/unseals the auto-generated managed-mode\n * passphrase. Required when `passphraseMode === 'managed'`; ignored\n * otherwise. Implementations live in per-platform packages\n * (`@noy-db/seal-macos-keychain`, `@noy-db/seal-wincred`,\n * `@noy-db/seal-libsecret`, `@noy-db/seal-aws-kms`, …).\n */\n readonly sealingKey?: SealingKeyProvider\n /** Required to use `profile: 'shamir'` recovery. Pass\n * `shamirRecoveryProvider()` from `@noy-db/on-shamir`. */\n readonly shamirRecovery?: ShamirRecoveryProvider\n /** Auth method. Default: 'passphrase'. */\n readonly auth?: 'passphrase' | 'biometric'\n /** Enable encryption. Default: true. */\n readonly encrypt?: boolean\n /**\n * Debug-only: lay plaintext records out as directly-inspectable store\n * objects (record fields inlined beside envelope metadata, `_debug: 1`) so\n * native store tooling can read them without unwrapping `_data`. Requires\n * `encrypt: false` — combining with encryption throws `DebugPlaintextError`\n * at construction. NEVER enable for production or client data.\n */\n readonly debugPlaintext?: boolean\n /**\n * Object projection for direct-serve / external blob fields (`as-*`, e.g.\n * `@noy-db/as-aws-s3`). Blob fields declared `external` route their RAW bytes\n * to this projection as a single native object (servable from S3/CDN) instead\n * of the encrypted-chunk path; the encrypted record/slot stays the catalog.\n * Sees plaintext bytes — outside the zero-knowledge guarantee.\n */\n readonly objectStore?: ObjectProjection\n /** Conflict resolution strategy. Default: 'version'. */\n readonly conflict?: ConflictStrategy\n /**\n * Sync scheduling policy. Controls when push/pull fire.\n * Default inferred from store category: per-record → `on-change`,\n * bundle → `debounce 30s`.\n */\n readonly syncPolicy?: SyncPolicy\n /**\n * @deprecated Use `syncPolicy` instead. Kept for backward compatibility.\n * When both are supplied, `syncPolicy` takes precedence.\n */\n readonly autoSync?: boolean\n /**\n * @deprecated Use `syncPolicy` instead. Kept for backward compatibility.\n */\n readonly syncInterval?: number\n /**\n * Session timeout in ms. Clears keys after inactivity. Default: none.\n * @deprecated Use `sessionPolicy.idleTimeoutMs` instead. This field is\n * still honored for backwards compatibility but `sessionPolicy` takes\n * precedence when both are supplied.\n */\n readonly sessionTimeout?: number\n /**\n * Session policy controlling lifetime, re-auth requirements, and\n * background-lock behavior. When supplied, replaces the\n * legacy `sessionTimeout` field.\n */\n readonly sessionPolicy?: SessionPolicy\n /**\n * Validate passphrase strength against the phrase format\n * on first-time keyring creation. When\n * `true`, weak phrases throw {@link WeakPassphraseError} from\n * `createNoydb()` / `db.rotatePassphrase()`. Default: `false` for\n * back-compat; planned to flip to `true` in a future major release.\n */\n readonly validatePassphrase?: boolean\n /**\n * Vault-level policy gate document. When present, the hub\n * persists the merged policy at `_meta/policy` on first-time vault\n * creation and gates sensitive operations (`db.rotatePassphrase`,\n * `db.export*`, …) against it. Omitted ⇒ the engine uses\n * {@link PERSONAL_POLICY}. Use {@link STRICT_POLICY} for regulated\n * deployments.\n *\n * The on-disk document is the source of truth — the policy field\n * is only honored at vault creation; subsequent runs read from\n * `_meta/policy`. Use `db.updatePolicy()` to change it deliberately.\n *\n * Imported from `@noy-db/hub` as a type-only reference; the runtime\n * import lives in `policy/index.ts`.\n */\n readonly policy?: VaultPolicy\n /**\n * Mandatory recovery profile enrollment. Vaults with\n * `recover-passphrase` enabled MUST register at least one profile\n * before being production-ready, otherwise `createNoydb()` throws\n * {@link RecoveryNotEnrolledError}. Set\n * `policy.gates['recover-passphrase'].enabled = false` to\n * deliberately opt out of recovery (passphrase loss = data loss).\n *\n * The `'paper'` profile is supported end-to-end. Other\n * profiles ship the API shape and throw\n * {@link RecoveryProfileNotImplementedError} during use.\n */\n readonly recovery?: ReadonlyArray<RecoveryEnrollment>\n /**\n * When `true`, `createNoydb` rejects vaults with no recovery\n * entries persisted (per the spec's mandatory-enrollment\n * requirement). Default `false` for back-compat; planned to\n * flip to `true` in a future major release. Apps in regulated\n * environments should turn this on now.\n */\n readonly requireRecovery?: boolean\n /**\n * What to do when `openVault` finds an existing keyring in the store that\n * cannot be decrypted with the supplied credentials (`InvalidKeyError`).\n *\n * - `'error'` (default) — propagate the error. The app must prompt the user\n * to supply the correct credentials or clear both the data and auth stores.\n * - `'reset'` — delete the stale keyring and re-initialise the vault from\n * scratch using the current credentials. Use this when the data store can\n * become detached from the auth store (e.g. the user cleared the IndexedDB\n * data records but not the keyring row, or a WebAuthn credential was rotated).\n * **All previously encrypted data is unrecoverable after a reset.**\n *\n * Only applies to the passphrase (`secret`) path. When `getKeyring` is used,\n * the callback is responsible for handling stale-keyring detection itself.\n */\n readonly onInvalidKey?: 'error' | 'reset'\n /**\n * Enable the public envelope service (`https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/public-envelope.md`).\n * Pass `true` for the default schema (every standard field, 256 KB\n * icon cap, 200-char text cap), or a `PublicEnvelopeSchema` to\n * narrow what the owner can set. Off by default — vaults written\n * by hubs without this option carry no envelope, full stop.\n */\n readonly publicEnvelope?: true | PublicEnvelopeSchema\n /** Audit history configuration. */\n readonly history?: HistoryConfig\n /**\n * Consumer-supplied translation function for `i18nText` fields with\n * `autoTranslate: true`.\n *\n * ⚠ **`plaintextTranslator` receives unencrypted text.** Configuring\n * this hook causes plaintext to leave noy-db's zero-knowledge boundary\n * over whatever channel the consumer's implementation uses. noy-db ships\n * no built-in translator and adds no translator SDKs as dependencies.\n * The consumer chooses and owns the data policy of the external service.\n *\n * Per-field opt-in via `autoTranslate: true` on `i18nText()`. Calling\n * `put()` on a collection with `autoTranslate: true` fields while this\n * option is absent throws `TranslatorNotConfiguredError`.\n *\n * See `NOYDB_SPEC.md § Zero-Knowledge Storage` for the invariant text.\n */\n readonly plaintextTranslator?: PlaintextTranslatorFn\n /**\n * Human-readable name for the translator, recorded in the in-process\n * audit log (e.g. `'deepl-pro-with-dpa'`, `'self-hosted-llama-7b'`).\n * Defaults to `'anonymous'` when not supplied.\n */\n readonly plaintextTranslatorName?: string\n /**\n * Drain-barrier coordination transport for the schema fence.\n * When omitted, the kernel uses a {@link CoordinationProvider} backed by the\n * primary store (`StoreCoordinationProvider`), reproducing today's\n * store-polling fence behavior byte-for-byte. `@noy-db/by-tabs` /\n * `@noy-db/by-peer` inject a real-time push transport here; an external\n * orchestrator (`@klum-db/lobby`) drives it through the `Noydb` handle.\n *\n * @internal\n */\n readonly coordinationStrategy?: CoordinationProvider\n /**\n * Pre-resolved factory for the `vault.user` per-principal user-envelope\n * API. `createNoydb()` always resolves this itself (dynamically\n * importing `with-party/directory/user-envelope/api.js`) before\n * constructing `Noydb` — mirrors the {@link coordinationStrategy}\n * pre-resolve above. There is no supported way to override it; it exists\n * as an options-bag field only so `createNoydb()` can thread the\n * pre-resolved value into the constructor without a second parameter.\n *\n * @internal\n */\n readonly userApiFactory?: UserApiFactory\n /**\n * Pre-resolved factory for the `NoydbPolicy` service (vault-policy\n * read/update/bootstrap + session-policy enforcer wiring).\n * `createNoydb()` always resolves this itself (dynamically importing\n * `with-party/policy/index.js`) before constructing `Noydb` — mirrors the\n * {@link coordinationStrategy} / {@link userApiFactory} pre-resolves\n * above. There is no supported way to override it.\n *\n * @internal\n */\n readonly policyFactory?: NoydbPolicyFactory\n /**\n * Pre-resolved policy-gate engine function (`checkGate`).\n * `createNoydb()` always resolves this itself (dynamically importing\n * `with-party/policy/index.js`) before constructing `Noydb` — same\n * pre-resolve pattern as {@link policyFactory}.\n *\n * @internal\n */\n readonly policyCheckGateFn?: PolicyCheckGateFn\n /**\n * Stable id for the session that owns this instance's writers (one user's\n * writers across vaults). Tags every {@link WriterPresence} the fence\n * watcher reports. Defaults to a fresh ULID per `Noydb` instance.\n *\n * @internal\n */\n readonly sessionId?: string\n}\n\n// ─── History / Audit Trail ─────────────────────────────────────────────\n\n/** History configuration. */\nexport interface HistoryConfig {\n /** Enable history tracking. Default: true. */\n readonly enabled?: boolean\n /** Maximum history entries per record. Oldest pruned on overflow. Default: unlimited. */\n readonly maxVersions?: number\n /**\n * Participate in the vault-wide hash-chained tamper ledger. Default:\n * `true` (every write of this collection appends a ledger entry when\n * `withHistory()` is active). Set `false` to exclude this collection's\n * writes from the chain — its puts/deletes leave no ledger entry,\n * confining tamper-evidence to the collections where it carries weight.\n * Independent of `enabled`, which gates per-record snapshots. Has no\n * effect when `withHistory()` is not active (there is no ledger).\n */\n readonly ledger?: boolean\n}\n\n/** Options for querying history. */\nexport interface HistoryOptions {\n /** Start date (inclusive), ISO 8601. */\n readonly from?: string\n /** End date (inclusive), ISO 8601. */\n readonly to?: string\n /** Maximum entries to return. */\n readonly limit?: number\n}\n\n/** Options for pruning history. */\nexport interface PruneOptions {\n /** Keep only the N most recent versions. */\n readonly keepVersions?: number\n /** Delete versions older than this date, ISO 8601. */\n readonly beforeDate?: string\n}\n\n/** A decrypted history entry. */\nexport interface HistoryEntry<T> {\n readonly version: number\n readonly timestamp: string\n readonly userId: string\n readonly record: T\n}\n\n// ─── Bulk operations ──────────────────────────────────────\n\n/** Per-item options for `Collection.putMany()`. */\nexport interface PutManyItemOptions {\n /**\n * Optimistic-concurrency check: fail this item if the stored version\n * is not `expectedVersion`. Honored only in `atomic: true` mode;\n * ignored in the default best-effort loop.\n */\n readonly expectedVersion?: number\n}\n\n/**\n * Batch-level options for `Collection.putMany()` and `deleteMany()`.\n *\n * `atomic: true` switches the call from best-effort loop\n * to all-or-nothing: a pre-flight CAS check runs first, then every op\n * is executed; any mid-batch failure triggers a best-effort revert.\n * On failure in atomic mode the whole call throws — you won't get a\n * partial `PutManyResult`. On success the result mirrors the default\n * loop's shape.\n */\nexport interface PutManyOptions {\n readonly atomic?: boolean\n}\n\n/** Result of `Collection.putMany()`. */\nexport interface PutManyResult {\n /** `true` iff every entry succeeded. */\n readonly ok: boolean\n /** IDs that were successfully written. */\n readonly success: readonly string[]\n /** Entries that failed, with the error that prevented each write. */\n readonly failures: ReadonlyArray<{ readonly id: string; readonly error: Error }>\n}\n\n/** Result of `Collection.deleteMany()`. Same shape as `PutManyResult`. */\nexport interface DeleteManyResult {\n readonly ok: boolean\n readonly success: readonly string[]\n readonly failures: ReadonlyArray<{ readonly id: string; readonly error: Error }>\n}\n\n// ─── User Envelope (vault.user contract) ───────────────────────────────\n//\n// The per-principal user-envelope service's PUBLIC CONTRACT lives here in\n// the spine; the implementation (`UserApi` / `createUserApi`, storage\n// primitives) lives at `with-party/directory/user-envelope/` and is wired\n// in by `createNoydb()` via the pre-resolved `userApiFactory` option above\n// — the same dynamic-import-then-stash pattern used for the default\n// `CoordinationProvider`.\n//\n// @see docs/superpowers/specs/2026-05-05-user-envelope-design.md\n\n/**\n * Thin reader view of a user envelope. The on-disk shape is the standard\n * {@link EncryptedEnvelope}; this is what callers see after the storage\n * layer has decrypted the payload.\n *\n * Hub commits to the `keyringId` ⇔ `userId` identity and the `_v` / `_ts`\n * envelope metadata. The `data` payload is fully app-defined — hub does\n * not introspect, validate, or reserve any keys inside it.\n */\nexport interface UserEnvelope<T> {\n /** The principal id this envelope belongs to. Equals the keyring `user_id`. */\n readonly keyringId: string\n /** App-owned payload. Opaque to hub. */\n readonly data: T\n /** Optimistic-concurrency version. Increments on every write. */\n readonly _v: number\n /** ISO timestamp of the last write. */\n readonly _ts: string\n}\n\n/**\n * Recursive partial. Used for `updateMe(patch)` so callers can hand in\n * deeply-nested partial shapes and have them deep-merged onto the\n * current envelope.\n */\nexport type DeepPartial<T> = T extends object\n ? { [P in keyof T]?: DeepPartial<T[P]> }\n : T\n\n/**\n * Recursive partial with `null` allowed at every level — used by\n * `updateMe` to express deletion intent in addition to merge.\n *\n * Semantics inside `updateMe`:\n * - `undefined` (or absent key) — skip; source value preserved\n * - `null` — delete the key from the resulting envelope\n * - any other value — overwrite (deep-merge for plain objects,\n * replace for primitives / arrays)\n *\n * Matches lodash `_.merge` behavior on `null` and Firestore's\n * `FieldValue.delete()` semantics. Loosened from `DeepPartial<T>`.\n * Consumers wanting the original \"merge-only\" surface can keep\n * importing `DeepPartial` and avoid passing `null`.\n */\nexport type DeepPartialOrNull<T> = T extends object\n ? { [P in keyof T]?: DeepPartialOrNull<T[P]> | null }\n : T\n\n/** Cancel a previously-registered subscription. */\nexport type Unsubscribe = () => void\n\n/**\n * Optional factor-proof bundle threaded into gated user-envelope\n * operations. Same shape as `Noydb.checkGate(vault, gate, presented)`\n * accepts elsewhere — apps that have already presented a TOTP/email-OTP\n * for this session pass it here to satisfy tightened policies.\n */\nexport interface UserEnvelopePresented {\n readonly factors?: readonly FactorProof[]\n readonly sharedDevice?: boolean\n}\n\n/**\n * Callback used by `UserApi` to validate the active session against a\n * policy gate. Provided by the `Vault` constructor; in production this\n * delegates to `Noydb.checkGate(vault, gate, presented)`. In tests, a\n * no-op stub is fine.\n */\nexport type UserEnvelopeCheckGate = (\n gate:\n | 'edit-own-profile'\n | 'view-team-profiles'\n | 'client-unilateral-withdraw'\n | 'user-request-withdrawal'\n | 'approve-user-withdrawal',\n presented?: UserEnvelopePresented,\n) => Promise<void>\n\n/**\n * Reactive handle returned by `live()`. `current` is the most recently\n * observed value; `subscribe(cb)` fires on subsequent local writes.\n * `stop()` releases the underlying subscription.\n */\nexport interface LiveUserEnvelope<T> {\n current(): UserEnvelope<T> | null\n subscribe(cb: (env: UserEnvelope<T> | null) => void): Unsubscribe\n stop(): void\n}\n\n/**\n * The 2nd positional parameter of a {@link PortabilityStrategy} method\n * (index 1, right after the leading `vault` argument).\n */\ntype PortabilityParam1<K extends keyof PortabilityStrategy> = Parameters<PortabilityStrategy[K]>[1]\n/**\n * The 3rd positional parameter (index 2) — only present on\n * `approveWithdrawal` / `rejectWithdrawal` (requestId is index 1 there).\n */\ntype PortabilityParam2<K extends keyof PortabilityStrategy> = Parameters<PortabilityStrategy[K]>[2]\ntype PortabilityReturn<K extends keyof PortabilityStrategy> = ReturnType<PortabilityStrategy[K]>\n\n/**\n * Public `vault.user.*` API surface — the CONTRACT. The implementation\n * (`UserApi`) lives at `with-party/directory/user-envelope/api.ts` and\n * `implements` this interface; `createNoydb()` wires it in via the\n * pre-resolved {@link UserApiFactory}.\n *\n * Three families:\n * - Write-self: `me` / `updateMe` / `setMe` — always target the writer's\n * own keyringId. **Own-only write rule** is structural — no method\n * exists to write someone else's envelope.\n * - Read-anyone: `get` / `list` — read other principals' envelopes\n * (subject to `view-team-profiles` policy gate).\n * - Reactive: `subscribe` / `live` — in-process event emission on local\n * writes. Cross-instance updates land via the team/sync engine and\n * surface to subscribers when the sync diff replays through this API.\n *\n * @see docs/superpowers/specs/2026-05-05-user-envelope-design.md\n */\nexport interface VaultUserApi {\n requestWithdrawal(opts?: PortabilityParam1<'requestWithdrawal'>): PortabilityReturn<'requestWithdrawal'>\n listWithdrawalRequests(opts?: PortabilityParam1<'listWithdrawalRequests'>): PortabilityReturn<'listWithdrawalRequests'>\n approveWithdrawal(\n requestId: PortabilityParam1<'approveWithdrawal'>,\n opts?: PortabilityParam2<'approveWithdrawal'>,\n ): PortabilityReturn<'approveWithdrawal'>\n rejectWithdrawal(\n requestId: PortabilityParam1<'rejectWithdrawal'>,\n opts?: PortabilityParam2<'rejectWithdrawal'>,\n ): PortabilityReturn<'rejectWithdrawal'>\n unilateralWithdrawal(opts: PortabilityParam1<'withdrawAccessibleData'>): PortabilityReturn<'withdrawAccessibleData'>\n exportMyAccessibleData(opts?: PortabilityParam1<'exportAccessibleData'>): PortabilityReturn<'exportAccessibleData'>\n me<T = unknown>(): Promise<UserEnvelope<T> | null>\n updateMe<T extends object = Record<string, unknown>>(\n patch: DeepPartialOrNull<T>,\n presented?: UserEnvelopePresented,\n ): Promise<UserEnvelope<T>>\n setMe<T = unknown>(payload: T, presented?: UserEnvelopePresented): Promise<UserEnvelope<T>>\n getMyVisibility(): Promise<{ readonly hidden: boolean }>\n setMyVisibility(visibility: { readonly hidden: boolean }): Promise<void>\n get<T = unknown>(keyringId: string, presented?: UserEnvelopePresented): Promise<UserEnvelope<T> | null>\n list<T = unknown>(presented?: UserEnvelopePresented): Promise<UserEnvelope<T>[]>\n subscribe<T = unknown>(keyringId: string, cb: (env: UserEnvelope<T> | null) => void): Unsubscribe\n live<T = unknown>(keyringId: string): LiveUserEnvelope<T>\n}\n\n/**\n * Constructor dependencies for `UserApi` (the {@link VaultUserApi}\n * implementation). Built by `Vault`'s constructor and passed to the\n * pre-resolved {@link UserApiFactory}.\n */\nexport interface UserApiDeps {\n readonly adapter: NoydbStore\n readonly vaultName: string\n /** The writer's own keyringId. Frozen at construction time. */\n readonly writerKeyringId: string\n readonly getDek: () => Promise<EnclaveKey>\n /**\n * Policy-gate validator. When omitted, gates are skipped — useful\n * for low-level tests that exercise the storage layer directly.\n * Production paths always wire the Noydb-backed implementation.\n */\n readonly checkGate?: UserEnvelopeCheckGate\n /**\n * Noydb-backed `exportMyAccessibleData`, injected by the Vault\n * (which holds the keyring + bundle machinery). Omitted in low-level tests.\n */\n readonly exportAccessible?: (opts: PortabilityParam1<'exportAccessibleData'>) => PortabilityReturn<'exportAccessibleData'>\n /**\n * Noydb-backed `unilateralWithdrawal`, injected by the Vault.\n * Destructive — extract + dispose (delete | freeze). Omitted in low-level tests.\n */\n readonly unilateralWithdraw?: (opts: PortabilityParam1<'withdrawAccessibleData'>) => PortabilityReturn<'withdrawAccessibleData'>\n /**\n * Noydb-backed two-party withdrawal ceremony, injected by the\n * Vault. requestWithdraw = requester side; the rest = owner side.\n */\n readonly requestWithdraw?: (opts: PortabilityParam1<'requestWithdrawal'>) => PortabilityReturn<'requestWithdrawal'>\n readonly listWithdrawals?: (opts: PortabilityParam1<'listWithdrawalRequests'>) => PortabilityReturn<'listWithdrawalRequests'>\n readonly approveWithdraw?: (\n requestId: PortabilityParam1<'approveWithdrawal'>,\n opts: PortabilityParam2<'approveWithdrawal'>,\n ) => PortabilityReturn<'approveWithdrawal'>\n readonly rejectWithdraw?: (\n requestId: PortabilityParam1<'rejectWithdrawal'>,\n opts: PortabilityParam2<'rejectWithdrawal'>,\n ) => PortabilityReturn<'rejectWithdrawal'>\n}\n\n/**\n * Factory that builds the `vault.user` API implementation from its\n * dependencies. `createNoydb()` pre-resolves the real implementation\n * (`with-party/directory/user-envelope/api.js#createUserApi`) via a\n * dynamic import before constructing `Noydb`, so `Vault`'s constructor\n * can call it synchronously — the two sync `subscribe`/`live` methods on\n * `VaultUserApi` are why `vault.user` must be built synchronously.\n */\nexport type UserApiFactory = (deps: UserApiDeps) => VaultUserApi\n\n// ─── Policy gates (VaultPolicy contract) ───────────────────────────────\n//\n// Sensitive operations (rotate the passphrase, enroll an authenticator,\n// export plaintext, grant a user, …) are gated by a typed policy\n// object. The developer supplies a {@link VaultPolicy} at vault\n// creation; the hub merges it onto a built-in preset and persists the\n// merged document at `_meta/policy`.\n//\n// The CONTRACT (this section) lives here in the spine; the engine\n// (`checkGate`/`describeGate`), the presets (`PERSONAL_POLICY` /\n// `STRICT_POLICY`), storage (`loadVaultPolicy`/`saveVaultPolicy`), and the\n// `NoydbPolicy` facade implementation live at `with-party/policy/` and are\n// wired in by `createNoydb()` via the pre-resolved {@link NoydbPolicyFactory}\n// / {@link PolicyCheckGateFn} options above — the same\n// dynamic-import-then-stash pattern used for the default\n// `CoordinationProvider` / `UserApiFactory`.\n//\n// @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Policy gates DSL\n\n/**\n * A single factor surface — the proof an actor presents at gate time.\n *\n * | Kind | Source | Off-device? |\n * |---|---|---|\n * | `totp` | RFC 6238 authenticator app (Google Auth, 1Password) | yes |\n * | `email-otp` | one-time code mailed to the user | yes |\n * | `recovery` | printable Base32 code (`@noy-db/on-recovery`) | yes (paper) |\n * | `shamir` | k-of-n threshold share (`@noy-db/on-shamir`) | yes |\n * | `webauthn-roaming` | hardware key (YubiKey, SoloKey, Titan) | yes (key portable) |\n * | `webauthn-platform` | platform passkey (Touch ID, Face ID, Hello) | no (device-bound) |\n * | `password` | tier-2 password (`@noy-db/on-password`) | no |\n * | `pin` | tier-3 quick-resume PIN (`@noy-db/on-pin`) | no |\n *\n * Off-device kinds (TOTP, email-OTP, recovery, shamir, roaming WebAuthn)\n * are the strongest factor proofs because they require something\n * separate from the device the user just unlocked. Platform / password /\n * PIN are useful for \"fresh proof of *this* user\" but don't bind across\n * devices — policies can require ANY of them or insist on a count of 2\n * to force a mix.\n *\n * `webauthn-platform`, `password`, `pin` — for consumers with no\n * off-device infrastructure (no TOTP, no email-OTP, paper recovery not\n * enrolled) who want to require \"any second factor I have wired\"\n * without losing the freshness guarantee.\n */\nexport type FactorKind =\n | 'totp'\n | 'email-otp'\n | 'recovery'\n | 'shamir'\n | 'webauthn-roaming'\n | 'webauthn-platform'\n | 'password'\n | 'pin'\n\n/**\n * One factor requirement entry. The default is \"any one of the listed\n * factors, fresh within the last 5 minutes\". Bumping `count` requires N\n * distinct fresh proofs; bumping `freshnessMs` widens the acceptance\n * window.\n */\nexport interface FactorRequirement {\n readonly anyOf: ReadonlyArray<FactorKind>\n /** Number of distinct factors required. Default 1. */\n readonly count?: number\n /** How recent each proof must be. Default 5 minutes. */\n readonly freshnessMs?: number\n}\n\n/** Soft signals layered on top of the gate verdict — never block on their own. */\nexport interface WarningRules {\n /** Behavior on shared-device tier-1 ops. `'block'` raises a `PolicyDeniedError`. */\n readonly sharedDevice?: 'warn' | 'block'\n /** Behavior on weak tier-2 (e.g. password-only) for sensitive ops. */\n readonly weakAuthenticator?: 'warn' | 'block'\n}\n\n/**\n * Policy applied to one named gate. `enabled: false` disables the\n * action entirely (useful in managed-passphrase mode where rotation is\n * impossible by construction).\n */\nexport interface GatePolicy {\n /** Minimum tier the active session must hold. */\n readonly minTier: 1 | 2 | 3\n /** Extra freshness-bound proofs required at gate time. */\n readonly factors?: ReadonlyArray<FactorRequirement>\n readonly warn?: WarningRules\n readonly enabled?: boolean\n}\n\n/**\n * Built-in gate names. App-defined gates live in the `app:*` namespace\n * and use the same engine; the engine treats unknown names with no\n * configured policy as \"no gate\" (no-op).\n */\nexport type BuiltInGateName =\n | 'rotate-passphrase'\n | 'recover-passphrase'\n | 'enroll-authenticator'\n | 'remove-authenticator'\n /**\n * Authorize a deliberate paper-recovery-code regeneration —\n * `db.rotateRecovery`. Symmetric to `rotate-passphrase` for\n * the case where the user remembers their passphrase but wants a\n * fresh sheet (lost the printout, suspect compromise of the off-site\n * copy). PERSONAL allows tier-1; STRICT requires an off-device\n * factor so a stolen unlocked laptop cannot silently mint a new\n * sheet for an attacker.\n */\n | 'rotate-recovery'\n /**\n * Authorize a meta-only mutation on an existing authenticator slot —\n * `db.updateAuthenticator`. The slot's wrap material, id, and\n * method are immutable through this gate; only the `meta` blob\n * (nicknames, method-specific labels) can change. Anti-slot-swap\n * guard is preserved structurally regardless of this gate's\n * settings.\n */\n | 'update-authenticator'\n | 'rotate-unlock'\n | 'enroll-user'\n | 'revoke-user'\n | 'export-bundle'\n | 'export-plaintext'\n | 'view-user-auth'\n /** Authorize a write to one's own user envelope. */\n | 'edit-own-profile'\n /** Authorize reading other principals' user envelopes. */\n | 'view-team-profiles'\n /**\n * Authorize an atomic peer-recovery — `db.recoverUser`.\n * Distinct from `revoke-user` because peer-recovery is intentional\n * re-issuance of someone's keyring under a temp passphrase, NOT\n * removal. Allows owner→owner natively (matches the threat model:\n * a co-owner explicitly recovering another co-owner). Ships with a\n * factor-proof default in `STRICT_POLICY` so the issuer must\n * affirmatively prove identity at the moment of recovery.\n */\n | 'peer-recover-user'\n /**\n * Authorize a post-grant identity mutation — `db.updateUser`.\n * Covers `role`, `displayName`, `permissions` changes on an existing\n * keyring. Pure plaintext-header rewrite — no DEKs touched, no KEK\n * required. The role-elevation guard inside the implementation\n * mirrors `db.grant`'s hierarchy (admin cannot promote to owner)\n * regardless of this gate's settings.\n */\n | 'update-user'\n /**\n * Authorize a non-owner's self-service **destructive** withdrawal —\n * `vault.user.unilateralWithdrawal`. The actor exports their\n * own re-keyed copy and then removes (delete-closure) or freezes the\n * source records. Because it both egresses data AND destroys the\n * firm's live copy, it MUST fail closed: undefined in a policy = denied.\n * Hosts opt in explicitly (and typically pin `minTier`/factor proofs).\n */\n | 'client-unilateral-withdraw'\n /**\n * Authorize FILING a two-party withdrawal request —\n * `vault.user.requestWithdrawal`. Non-destructive (writes a\n * pending request only); enabled by default so a read-only client can ask.\n */\n | 'user-request-withdrawal'\n /**\n * Authorize DECIDING a two-party withdrawal request (approve/reject) —\n * `vault.user.approveWithdrawal` / `rejectWithdrawal`. The approve\n * path is destructive (extract-and-dispose under firm authority), so it\n * defaults to a tier-2 floor; owner/admin role is enforced structurally.\n */\n | 'approve-user-withdrawal'\n /**\n * Authorize minting a **custodian** — `db.grantCustodian` (FR-6). The\n * custodian is the de-facto operational authority on a sealed-owner (Deed)\n * vault, so granting one is an ownership-level act: this gate MUST fail\n * closed (undefined in a policy = denied) and owner-only role is enforced\n * structurally. Hosts opt in explicitly, typically pinning factor proofs.\n */\n | 'grant-custodian'\n /**\n * Authorize the audited **Liberate** ceremony — `vault.custody.liberate`\n * (FR-6). The custodian (holding the live DEKs) claims ownership of a\n * sealed-owner vault under a recorded legal basis, minting a NEW owner\n * keyring. Destructive-of-the-old-ownership and irreversible, so it MUST\n * fail closed (undefined = denied); the caller-is-custodian check is\n * enforced structurally in the ceremony.\n */\n | 'liberate-vault'\n\n/** Either a built-in gate name or an `app:*` custom gate. */\nexport type GateName = BuiltInGateName | `app:${string}`\n\n/**\n * Top-level policy object. Persisted at `_meta/policy` once at vault\n * creation. The `passphrase` block configures the strength rules\n * applied at every passphrase ingress; `gates` configures\n * the action-level requirements.\n */\nexport interface VaultPolicy {\n readonly passphrase?: PassphrasePolicy\n readonly gates: Partial<Record<GateName, GatePolicy>>\n}\n\n/** Concrete proof an actor presents to {@link checkGate}. */\nexport interface FactorProof {\n readonly kind: FactorKind\n /** ISO-8601 timestamp the proof was minted at. Compared against `freshnessMs`. */\n readonly mintedAt?: string\n /** Method-specific payload. The engine treats it as opaque — verification is delegated. */\n readonly payload?: unknown\n}\n\n/**\n * Bundle of factor proofs + session-context flags passed to a gated\n * Noydb method. Used as the optional last parameter of every method\n * that runs through `checkGate`: `db.grant`, `db.revoke`, `db.updateUser`,\n * `db.enrollAuthenticator`, `db.removeAuthenticator`, `db.updateAuthenticator`,\n * `db.enrollWebAuthn`, `db.rotatePassphrase`, `db.recoverPassphrase`,\n * `db.recoverUser`, `db.enrollUnlock`, `db.describeUserAuth`,\n * `db.describeAllUsersAuth`.\n *\n * Previously this type was inlined at every call site as\n * `{ factors?: ReadonlyArray<FactorProof>; sharedDevice?: boolean }`\n * and parameter names alternated between `factors` and `presented`.\n * Now exported so consumers can name their helpers and so the param\n * name converges to `factors` everywhere.\n */\nexport interface FactorProofBundle {\n readonly factors?: ReadonlyArray<FactorProof>\n readonly sharedDevice?: boolean\n}\n\n/** Active session tier — what the engine compares against `gate.minTier`. */\nexport type ActiveTier = 1 | 2 | 3\n\n/**\n * Caller-supplied context for the policy engine's `checkGate`/`describeGate`.\n * Structural mirror of `with-party/policy/engine.ts`'s `CheckGateContext` —\n * duplicated here (rather than imported) because the kernel spine may not\n * statically import a with-* service; see {@link PolicyCheckGateFn}.\n */\nexport interface PolicyCheckGateContext {\n /** Tier the active session currently holds. */\n readonly activeTier: ActiveTier\n /** Proofs the actor is presenting for this gate. */\n readonly factors?: ReadonlyArray<FactorProof>\n /**\n * If the host knows the actor is on a shared device, set this to\n * `true` so the engine can apply `warn.sharedDevice` rules. Defaults\n * to `false`.\n */\n readonly sharedDevice?: boolean\n /**\n * Override `now()` for tests. Defaults to `Date.now()`.\n * @internal\n */\n readonly now?: number\n}\n\n/**\n * Structural type of the policy engine's `checkGate` function. The real\n * implementation lives at `with-party/policy/engine.ts#checkGate`;\n * `createNoydb()` pre-resolves it via a dynamic import (mirrors\n * {@link UserApiFactory}) so `Noydb.checkGate` can call it without the\n * spine statically importing the service.\n */\nexport type PolicyCheckGateFn = (\n policy: VaultPolicy,\n gate: GateName,\n context: PolicyCheckGateContext,\n) => Promise<void>\n\n/**\n * Public `NoydbPolicy` surface — the CONTRACT. The implementation\n * (`NoydbPolicy` class) lives at `with-party/policy/noydb-facade.ts`;\n * `createNoydb()` wires it in via the pre-resolved {@link NoydbPolicyFactory}.\n */\nexport interface NoydbPolicyApi {\n /**\n * Touch the policy enforcer for a vault (records activity, resets\n * idle timer). Also touches the legacy session timer. No-op if no enforcer.\n */\n touchPolicy(vault?: string): void\n /**\n * Check that a policy-guarded operation is permitted.\n * Throws `SessionPolicyError` if re-auth is required.\n */\n checkPolicyOperation(vault: string, op: ReAuthOperation): void\n /**\n * Read the active policy for a vault. Loads from `_meta/policy` on\n * first call; subsequent calls hit the in-memory cache. Throws\n * `ValidationError` if the vault has not been opened.\n */\n getPolicy(vault: string): Promise<VaultPolicy>\n /**\n * Replace the policy document at `_meta/policy` and update the\n * in-memory cache. Gated by the `enroll-user` policy (a policy\n * change is fundamentally a privilege-management action).\n */\n updatePolicy(vault: string, override: Partial<VaultPolicy>): Promise<VaultPolicy>\n /** Read or persist the vault policy at `_meta/policy` on first open. */\n bootstrapPolicy(vault: string, opts?: { skipManagedCheck?: boolean }): Promise<void>\n}\n\n/**\n * Constructor dependencies for `NoydbPolicy` (the {@link NoydbPolicyApi}\n * implementation). Everything the policy/session-policy methods touch on\n * the owning `Noydb` instance's `this.*`.\n *\n * The `policyEnforcers` map is typed structurally (rather than importing\n * `PolicyEnforcer` from `with-party/session/session-policy.ts`) so this\n * spine-resident interface never needs a with-* import; the real\n * `PolicyEnforcer` class satisfies this shape.\n */\nexport interface NoydbPolicyDeps {\n /** In-memory vault-policy cache (Noydb-resident; read/written by reference). */\n readonly policyCache: Map<string, VaultPolicy>\n /** Per-vault session-policy enforcers (Noydb-resident; read/written by reference). */\n readonly policyEnforcers: Map<string, { touch(): void; destroy(): void; checkOperation(op: ReAuthOperation): void }>\n /** The ciphertext store. */\n readonly store: NoydbStore\n /** Whether records are encrypted (`options.encrypt !== false`). */\n readonly encrypted: boolean\n /** The configured session policy, or undefined. */\n readonly sessionPolicy: SessionPolicy | undefined\n /** The developer-supplied default policy, or undefined. */\n readonly policyOption: VaultPolicy | undefined\n /** Whether the owning instance has been closed. */\n isClosed(): boolean\n /** Reset the kernel-resident idle/session timer. */\n resetSessionTimer(): void\n /** Managed-recovery enrolment check (kernel-resident; called on bootstrap). */\n assertRecoveryEnrolled(\n vault: string,\n policy: VaultPolicy,\n opts?: { skipManagedCheck?: boolean },\n ): Promise<void>\n /** Evict the keyring + vault caches when a session is revoked. */\n onSessionRevoke(vault: string): void\n}\n\n/**\n * Factory that builds the `NoydbPolicy` service implementation from its\n * dependencies. `createNoydb()` pre-resolves the real implementation\n * (`with-party/policy/noydb-facade.js#createNoydbPolicy`) via a dynamic\n * import before constructing `Noydb`, so the constructor can call it\n * synchronously — mirrors {@link UserApiFactory}.\n */\nexport type NoydbPolicyFactory = (deps: NoydbPolicyDeps) => NoydbPolicyApi\n"],"mappings":";AAuEO,IAAM,uBAAuB;AAG7B,IAAM,wBAAwB;AAG9B,IAAM,uBAAuB;AAG7B,IAAM,qBAAqB;AA8T3B,IAAM,eAAN,MAA2C;AAAA,EACvC,SAAS;AAAA,EACT;AAAA,EAET,YAAY,QAA0B;AACpC,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,SAAqB;AACnB,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA;AAAA,EAGA,SAAiB;AACf,WAAO;AAAA,EACT;AACF;AAsVO,SAAS,YACd,SACmC;AACnC,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/via/lookup/registry.ts","../src/via/lookup/snapshot.ts","../src/port/with/lookup-strategy.ts","../src/kernel/via/dispatch.ts"],"sourcesContent":["/**\n * Pure dict-registry helpers — extracted from `kernel/vault.ts`'s dict\n * bodies (#650 Task 1 — via-lookup extraction, phase D).\n *\n * These take the vault-resident registry Maps (and a couple of vault-bound\n * callbacks) as ARGUMENTS instead of closing over `this` — no `Vault`\n * import here, so this module stays a plain, testable function library.\n * `kernel/vault.ts` keeps the registry Maps themselves (they're populated\n * by `vault.collection()` and read by the backup path) and calls these\n * helpers through the `port/with/lookup-strategy.ts` seam.\n */\n\nimport { getAtPath } from '../../kernel/paths.js'\nimport { UnknownDictCodeError, ValidationError } from '../../kernel/errors.js'\nimport type { JoinableSource } from '../../kernel/query/index.js'\nimport type { FieldRef, ViaGraph } from '../../kernel/via/graph.js'\nimport type { StaticDictDescriptor } from '../../port/with/i18n-strategy.js'\nimport { dictCollectionName, type LookupHandle } from './handle.js'\nimport type { LookupDescriptor, OnDelete } from './descriptor.js'\n\n/**\n * Validate staticDict codes on a `put()`. For each `staticDict()` field,\n * every stored code must be a declared key of the descriptor's table, else\n * `UnknownDictCodeError`. Opt out per descriptor with `{ validateCodes:\n * false }`. Supports scalar, dotted, and `[].`-wildcard field paths via\n * `getAtPath` (same path support as i18n validation).\n *\n * `staticFields` is the collection's `field → StaticDictDescriptor` map\n * (`Vault#staticDescriptorByField.get(collectionName)`) — `undefined`/empty\n * is a no-op.\n */\nexport function enforceStaticDictOnPut(\n staticFields: Record<string, StaticDictDescriptor> | undefined,\n record: unknown,\n): void {\n if (!staticFields || Object.keys(staticFields).length === 0) return\n if (!record || typeof record !== 'object') return\n\n const obj = record as Record<string, unknown>\n for (const [field, desc] of Object.entries(staticFields)) {\n if (desc.validateCodes === false) continue\n const known = new Set<string>(desc.keys)\n const values = getAtPath(obj, field)\n for (const value of values) {\n if (value === undefined || value === null) continue\n const codes = Array.isArray(value) ? value : [value]\n for (const code of codes) {\n if (typeof code !== 'string') continue\n if (!known.has(code)) {\n throw new UnknownDictCodeError(desc.name, field, code)\n }\n }\n }\n }\n}\n\n/**\n * Build a `JoinableSource` for a dictKey field, for use in dict joins.\n * Returns a source whose snapshot contains `{ key, labels, ...labels }`\n * records — one per dictionary entry — keyed by the stable key.\n *\n * staticDict: a code-table-backed source — snapshot() materialises the\n * in-memory table into rows, mirroring `LookupHandle.snapshotEntries()`.\n * Carries `displayLocale` so a locale-less `{ by: 'label' }` query has a\n * default locale to resolve at.\n *\n * Plain dictKey: the snapshot is built synchronously from the\n * `LookupHandle`'s write-through cache, which is populated on every\n * `put()`, `rename()`, `delete()`, and `list()` call. For pre-existing\n * data not yet touched this session, call `await vault.dictionary(name).list()`\n * first to warm the cache.\n *\n * Returns `null` when `field` is not a dictKey in `leftCollection`.\n */\nexport function resolveDictSource(\n leftCollection: string,\n field: string,\n staticDescriptorByField: ReadonlyMap<string, Record<string, StaticDictDescriptor>>,\n dictKeyFieldRegistry: ReadonlyMap<string, Record<string, string>>,\n getDictionaryHandle: (name: string) => LookupHandle,\n): JoinableSource | null {\n const staticFields = staticDescriptorByField.get(leftCollection)\n if (staticFields && field in staticFields) {\n const desc = staticFields[field]!\n const rows: readonly Record<string, unknown>[] = Object.entries(desc.table).map(\n ([key, labels]) => ({ key, labels, ...(labels as Record<string, string>) }),\n )\n const source: JoinableSource = {\n snapshot(): readonly unknown[] {\n return rows\n },\n lookupById(id: string): unknown {\n return rows.find((e) => e['key'] === id)\n },\n }\n if (desc.displayLocale !== undefined) {\n ;(source as { displayLocale?: string }).displayLocale = desc.displayLocale\n }\n return source\n }\n\n const dictFields = dictKeyFieldRegistry.get(leftCollection)\n if (!dictFields || !(field in dictFields)) return null\n const dictName = dictFields[field]\n if (!dictName) return null\n const handle = getDictionaryHandle(dictName)\n return {\n snapshot(): readonly unknown[] {\n return handle.snapshotEntries()\n },\n lookupById(id: string): unknown {\n const entries = handle.snapshotEntries()\n return entries.find((e) => e['key'] === id)\n },\n }\n}\n\n/** The minimal collection surface `updateReferencingRecords` needs. */\nexport interface DictReferencingCollection {\n list(): Promise<Record<string, unknown>[]>\n put(id: string, record: Record<string, unknown>): Promise<unknown>\n}\n\n/**\n * Find and rewrite records in every registered collection whose\n * dictKeyField points at `name`, replacing `oldKey` with `newKey`. Used by\n * `LookupHandle.rename()` (the only sanctioned mass-mutation path for\n * dictKey fields) via the vault's `findAndUpdateReferences` callback.\n *\n * `registry` is `Vault#dictKeyFieldRegistry` (collection name → field name\n * → dictionary name); `getCollection` is the vault's collection accessor —\n * rewrites go through the public `coll.put()` choke point, same as before.\n */\nexport async function updateReferencingRecords(\n registry: ReadonlyMap<string, Record<string, string>>,\n getCollection: (collectionName: string) => DictReferencingCollection,\n name: string,\n oldKey: string,\n newKey: string,\n): Promise<void> {\n for (const [collectionName, dictFields] of registry) {\n // Find fields that point at this dictionary\n const fields = Object.entries(dictFields)\n .filter(([, dn]) => dn === name)\n .map(([field]) => field)\n if (fields.length === 0) continue\n\n const coll = getCollection(collectionName)\n const records = await coll.list()\n for (const record of records) {\n let changed = false\n const updated = { ...record }\n for (const field of fields) {\n if (updated[field] === oldKey) {\n updated[field] = newKey\n changed = true\n }\n }\n if (changed) {\n const id = record['id'] as string | undefined\n if (id !== undefined) {\n await coll.put(id, updated)\n }\n }\n }\n }\n}\n\n/**\n * Resolve a label from an in-memory `{ locale -> label }` map, walking the\n * same fallback chain semantics as `LookupHandle.resolveLabel` (#650 Task 2\n * — moved here from `kernel/vault.ts` so the SAME chain serves both the\n * i18n binding's `dictLabelResolver` and the lookup binding's\n * `lookupLabelResolver`, which #650 Task 2 wires to the identical closure).\n */\nexport function resolveLabelFromMap(\n labels: Readonly<Record<string, string>>,\n locale: string,\n fallback?: string | readonly string[],\n): string | undefined {\n if (labels[locale] !== undefined) return labels[locale]\n const chain = Array.isArray(fallback)\n ? (fallback as readonly string[])\n : fallback\n ? [fallback as string]\n : []\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(labels)[0]\n if (any !== undefined) return any\n } else if (labels[fb] !== undefined) {\n return labels[fb]\n }\n }\n return undefined\n}\n\n/**\n * Project a native `lookup(dimension, { backing:'static', table, … })`\n * descriptor into the legacy `StaticDictDescriptor` shape — the\n * alias-equivalence compat seam (#650 Task 2) that lets a native\n * static-tier lookup field reuse the SAME vault registries\n * (`staticByName`/`staticDescriptorByField`) — and therefore the same\n * `dictLabelResolver`/`resolveDictSource` machinery — as its `staticDict()`\n * alias. `vocabulary:'closed'` maps to `validateCodes:true` (closed = only\n * declared codes are legal); `'open'` maps to `validateCodes:false`.\n * Returns `undefined` for non-static or table-less (bare `enumOf`)\n * descriptors — those have nothing to register.\n */\nexport function lookupToStaticDictCompat(desc: LookupDescriptor): StaticDictDescriptor | undefined {\n if (desc.backing !== 'static' || desc.table === undefined) return undefined\n return {\n _noydbStaticDict: true,\n _viaBrand: 'i18n',\n name: desc.dimension,\n table: desc.table,\n keys: desc.keys ?? Object.keys(desc.table),\n ...(desc.displayLocale !== undefined ? { displayLocale: desc.displayLocale } : {}),\n ...(desc.onMissing !== undefined ? { onMissing: desc.onMissing } : {}),\n ...(desc.substitute !== undefined ? { substitute: desc.substitute } : {}),\n validateCodes: desc.vocabulary === 'closed',\n }\n}\n\n/** The vault-registry entries a collection's `lookupFields` contribute — the alias-equivalence bridge (#650 Task 2). */\nexport interface LookupDictCompat {\n /** Reserved-tier fields: field name -> dimension (dictionary) name — merges into `dictKeyFieldRegistry`. */\n readonly dictFieldMap: Record<string, string>\n /** Static-tier (table-bearing) fields, projected — merges into `staticDescriptorByField`/`staticByName`. */\n readonly staticEntries: ReadonlyArray<readonly [string, StaticDictDescriptor]>\n}\n\n/**\n * Bridge a collection's `lookupFields` into the SAME shape the legacy dict\n * registries expect, so `resolveDictSource`/`dictLabelResolver` (and\n * therefore `.join()`/`orderBy({by:'label'})`) serve a native `dict()`/\n * `lookup(static)` field identically to its `dictKey()`/`staticDict()`\n * alias — the reserved-vs-first-class-backing \"matrix\" tier is NOT bridged\n * here (no vault registry backs it; Task 5/6 build its own graph edge /\n * snapshot seam).\n */\nexport function collectLookupDictCompat(\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): LookupDictCompat {\n const dictFieldMap: Record<string, string> = {}\n const staticEntries: Array<readonly [string, StaticDictDescriptor]> = []\n for (const [field, desc] of Object.entries(lookupFields ?? {})) {\n if (desc.backing === 'reserved') {\n dictFieldMap[field] = desc.dimension\n } else {\n const compat = lookupToStaticDictCompat(desc)\n if (compat) staticEntries.push([field, compat])\n }\n }\n return { dictFieldMap, staticEntries }\n}\n\n/**\n * A lookup dimension's sync membership/altKey table, materialized from its\n * backing rows (#650 Task 3). `keys` is every canonical key present;\n * `altIndex` maps an altKey candidate VALUE to its owning canonical key.\n */\nexport interface MaterializedBacking {\n /** Canonical key values present in the materialized rows. */\n readonly keys: ReadonlySet<string>\n /** altKey candidate value -> canonical key. */\n readonly altIndex: ReadonlyMap<string, string>\n}\n\n/**\n * Build a lookup dimension's altKey index from its backing rows, enforcing\n * declare/warm-time uniqueness across `key ∪ altKeys` values (#650 Task 3 —\n * the CHE/SWZ drift class: two different rows must never claim the same\n * candidate key). `rows` is keyed by canonical key (`row[descriptor.key]`\n * for the matrix tier; the dimension's own key for static/reserved).\n * An altKey candidate VALUE may be a string or number — both normalize via\n * `coerceLookupKey` (#651 Task 3); non-scalar/absent values are skipped.\n * Pure — no I/O. Throws `ValidationError` on collision.\n */\nexport function materializeBackingTable(\n descriptor: LookupDescriptor,\n rows: ReadonlyMap<string, Record<string, unknown>>,\n): MaterializedBacking {\n const keys = new Set<string>(rows.keys())\n // Every value that has claimed ownership so far (canonical keys seed it) —\n // the union `key ∪ altKeys` uniqueness set the spec requires.\n const owner = new Map<string, string>()\n for (const key of keys) owner.set(key, key)\n\n const altIndex = new Map<string, string>()\n const altFields = descriptor.altKeys ?? []\n for (const [canonicalKey, row] of rows) {\n for (const altField of altFields) {\n const value = coerceLookupKey(row[altField])\n if (value === undefined || value === '') continue\n const existingOwner = owner.get(value)\n if (existingOwner !== undefined && existingOwner !== canonicalKey) {\n throw new ValidationError(\n `lookup \"${descriptor.dimension}\": altKey field \"${altField}\" value \"${value}\" is claimed by ` +\n `both \"${existingOwner}\" and \"${canonicalKey}\" — key/altKey values must be unique across the dimension.`,\n )\n }\n owner.set(value, canonicalKey)\n altIndex.set(value, canonicalKey)\n }\n }\n return { keys, altIndex }\n}\n\n/**\n * Closed-vocabulary membership test for one candidate key (#650 Task 3).\n * Static tier: sync, against the in-config key set (declared `keys`, or the\n * table's own keys when table-bearing). Reserved tier: sync — the declared\n * `keys` union the reserved handle's live write-through snapshot (closes\n * #649 for the native `dict()` spelling: the declared-keys promise the old\n * `dictKey()` doc comment made falsely). Matrix (collection) tier: sync —\n * delegates to `buildLookupAltIndex` so membership is checked against the\n * SAME `row[descriptor.key]` keying the altKey index uses (review fix,\n * Important 1: an earlier PUT-id `.get(key)` scan disagreed with the\n * altIndex whenever `descriptor.key !== 'id'`, wrongly rejecting valid\n * non-id candidates and wrongly accepting an unrelated row's PUT-id).\n */\nexport function checkLookupMembership(\n descriptor: LookupDescriptor,\n key: string,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): boolean {\n if (descriptor.backing === 'static') {\n const known = descriptor.keys ?? (descriptor.table ? Object.keys(descriptor.table) : [])\n return known.includes(key)\n }\n if (descriptor.backing === 'reserved') {\n if ((descriptor.keys ?? []).includes(key)) return true\n return getDictionary(descriptor.dimension).snapshotEntries().some((e) => e['key'] === key)\n }\n return buildLookupAltIndex(descriptor, getDictionary, getCollection).keys.has(key)\n}\n\n/**\n * The ONE guarded key coercion (#651 Task 3, dm12) — string/number values\n * coerce to their canonical `String()` form; everything else (`null`,\n * `undefined`, objects, …) coerces to `undefined`. Every consumer that turns\n * a raw record field into a lookup key routes through this, closing the\n * bare-`String()` `\"undefined\"`/`\"null\"`-key poisoning class (seam map\n * finding 6): a row whose key field is genuinely absent must never mint the\n * literal candidate string `\"undefined\"`.\n */\nexport function coerceLookupKey(raw: unknown): string | undefined {\n return typeof raw === 'string' || typeof raw === 'number' ? String(raw) : undefined\n}\n\n/**\n * Resolve a backing row's canonical key VALUE — `coerceLookupKey(row[descriptor.key])`\n * (#651 Task 3). The matrix tier's `row[descriptor.key]`, never the row's own PUT-id\n * when the two differ (`descriptor.key !== 'id'`).\n */\nexport function resolveBackingRowKey(\n descriptor: LookupDescriptor,\n row: Record<string, unknown>,\n): string | undefined {\n return coerceLookupKey(row[descriptor.key])\n}\n\n/**\n * The referencing-side match predicate — does `rec[field]` (coerced) equal an\n * already-coerced `compareKey` (#651 Task 3)? Shared by every site that scans a\n * referencing collection for rows pointing at a given backing key\n * (`with-shape/links/vault-facade.ts`'s ref-delete propagation, `kernel/via/dispatch.ts`'s\n * forget-fanout twin).\n */\nexport function matchesReferencingValue(\n rec: Record<string, unknown>,\n field: string,\n compareKey: string,\n): boolean {\n return coerceLookupKey(rec[field]) === compareKey\n}\n\n/**\n * Materialize a lookup dimension's altKey index from whatever backing data\n * is synchronously available (#650 Task 3 — the `ingest` source). Static:\n * the in-config table. Reserved: the reserved handle's live write-through\n * cache (the same warm-via-put()/list() cache `resolveDictSource` already\n * relies on). Matrix (collection): the backing collection's own in-memory\n * eager cache via `querySourceForJoin()` — already public, already the\n * mechanism `.join()` uses (`with-shape/links/vault-facade.ts`'s\n * `resolveSource`); no new I/O, no fire-and-forget warm step. Like that\n * existing join precedent, a dimension collection this vault session has\n * not yet opened/populated sees an empty snapshot (no altKey normalization\n * until it has rows) — open/populate it first for normalization to apply.\n * A matrix row whose `descriptor.key` field coerces to `undefined` (missing/\n * non-scalar) is SKIPPED — never enters the index under a poisoned\n * `\"undefined\"` key (#651 Task 3, dm12).\n */\nexport function buildLookupAltIndex(\n descriptor: LookupDescriptor,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): MaterializedBacking {\n if (descriptor.backing === 'static') {\n return materializeBackingTable(descriptor, new Map(Object.entries(descriptor.table ?? {})))\n }\n if (descriptor.backing === 'reserved') {\n const entries = getDictionary(descriptor.dimension).snapshotEntries()\n return materializeBackingTable(descriptor, new Map(entries.map((e) => [String(e['key']), e])))\n }\n const rows = getCollection(descriptor.dimension).querySourceForJoin().snapshot()\n const keyed = new Map<string, Record<string, unknown>>()\n for (const r of rows) {\n const row = r as Record<string, unknown>\n const key = resolveBackingRowKey(descriptor, row)\n if (key !== undefined) keyed.set(key, row)\n }\n return materializeBackingTable(descriptor, keyed)\n}\n\n/** One cross-collection `'ref'` graph edge a lookup field declares (#650 Task 5). Module-private —\n * only `registerLookupRefEdges` below (the exported entry point) consumes it. */\ninterface LookupRefEdge {\n readonly referencing: FieldRef\n readonly sources: readonly FieldRef[]\n readonly onDelete: OnDelete\n /** The backing dimension's canonical-key FIELD NAME on its own row (`desc.key` — matrix tier\n * only varies this; reserved/static tiers are always `'id'`). A referencing field always\n * stores THIS field's value, never the backing row's PUT-id when the two differ. */\n readonly keyField: string\n}\n\n/**\n * Compute the cross-collection `'ref'` edges a collection's `lookupFields` declare (#650 Task 5,\n * spec §4) — one edge per non-static-backing field: target = the referencing field; sources =\n * the backing dimension's whole-collection node (`field:'*'`, the wildcard key\n * `ViaGraph.referencingEdgesOf` does its O(1) reverse lookup against) PLUS, when the descriptor\n * names a presentation field (`present.label`), that SPECIFIC field too. `foldPosture`'s\n * `DEFAULT_POSTURE` is the fold's identity element, so adding the wildcard alongside a real field\n * source changes nothing when that field is plain — but folds in a classified/money posture when\n * it isn't (taint composition, spec §4: \"a lookup edge whose source names a classified field\n * contributes that field's posture\"). Static tier (`backing:'static'`) has no backing collection/\n * dimension rows to reference-check — excluded. Pure; consumed only by `registerLookupRefEdges` below.\n */\nfunction collectLookupRefEdges(\n collectionName: string,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): readonly LookupRefEdge[] {\n const edges: LookupRefEdge[] = []\n for (const [field, desc] of Object.entries(lookupFields ?? {})) {\n if (desc.backing === 'static') continue\n const backing = desc.backing === 'reserved' ? dictCollectionName(desc.dimension) : desc.dimension\n edges.push({\n referencing: { collection: collectionName, field },\n sources: [\n { collection: backing, field: '*' },\n ...(desc.present?.label !== undefined ? [{ collection: backing, field: desc.present.label }] : []),\n ],\n onDelete: desc.onDelete,\n keyField: desc.key,\n })\n }\n return edges\n}\n\n/** Thin wrapper — `collectLookupRefEdges` + one `graph.registerDerived` call per edge. Lets\n * `vault.collection()` (kernel-surface-budgeted, #650 Task 5) register a collection's lookup-ref\n * edges with a single line, keeping the ceiling-guarded call site a thin call (route logic here). */\nexport function registerLookupRefEdges(\n graph: ViaGraph,\n collectionName: string,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): void {\n for (const e of collectLookupRefEdges(collectionName, lookupFields)) {\n graph.registerDerived(e.referencing, e.sources, 'ref', 'record', e.onDelete, e.keyField)\n }\n}\n\n/**\n * `LookupViaConfig.snapshotFor`'s vault-built row source (#650 Task 6, spec\n * §5; matrix-tier coverage added #650 Task 7, spec §6 — Task 6 deferred it,\n * see `task-6-report.md`'s Concerns #1; the reviewer's Task-7 dispatch\n * refuted the \"needs a new vault-resident registry\" premise: the descriptor\n * is already in hand at both call sites, so `snapshotFor` just needs to\n * ACCEPT it). Takes the full `descriptor` (not a bare dimension name) so it\n * can route the matrix tier's `key` field, which — unlike reserved tier's\n * hardcoded `'id'` — varies per collection. Routes on `descriptor.backing`:\n *\n * - **reserved**: rows come straight from the SAME `LookupHandle.\n * snapshotEntries()` write-through cache `dictLabelResolver`/\n * `resolveDictSource` already read (no second copy), keyed by each\n * entry's own canonical `key` (always `'id'` by construction for this\n * tier — `dict()`'s factory hardcodes it).\n * - **collection** (matrix): rows come from `getCollection(dimension).\n * querySourceForJoin().snapshot()` — the SAME sync, already-live cache\n * `buildLookupAltIndex`'s matrix branch (above, this file) and `.join()`\n * itself already read — re-keyed via `resolveBackingRowKey(descriptor, row)`,\n * NOT the row's own PUT-id (which may differ when `key !== 'id'`; the exact\n * distinction the #650 Task 3 review fix already applies to\n * `checkLookupMembership`'s matrix branch). A row whose `descriptor.key`\n * field coerces to `undefined` is skipped (#651 Task 3, dm12).\n * - **static**: never routed here — `descriptor.table` is read directly by\n * the caller (`binding.ts`'s `compareLookupOrder`/`resolveLookupOrderLabel`,\n * `snapshot.ts`'s `presentLookupForJoin`); no vault call needed.\n *\n * `isReservedDimension` is the vault's `reservedLookupCollections`\n * membership test.\n */\nexport function buildLookupSnapshotRows(\n descriptor: LookupDescriptor,\n isReservedDimension: (dimension: string) => boolean,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): ReadonlyMap<string, Record<string, unknown>> | undefined {\n const dimension = descriptor.dimension\n if (isReservedDimension(dimension)) {\n const rows = new Map<string, Record<string, unknown>>()\n for (const entry of getDictionary(dimension).snapshotEntries()) {\n const key = entry['key']\n if (typeof key === 'string') rows.set(key, entry)\n }\n return rows\n }\n if (descriptor.backing === 'collection') {\n const rawRows = getCollection(dimension).querySourceForJoin().snapshot()\n const rows = new Map<string, Record<string, unknown>>()\n for (const r of rawRows) {\n const row = r as Record<string, unknown>\n const key = resolveBackingRowKey(descriptor, row)\n if (key !== undefined) rows.set(key, row)\n }\n return rows\n }\n return undefined\n}\n","/**\n * The sync lookup snapshot + join/locale seam (#650 Task 6, spec §5 — \"the\n * snapshot+locale seam\"). Retires the #626 kernel→via grandfather:\n * `kernel/query/join.ts` no longer imports `via/i18n/core.js` directly\n * — it calls the `presentForJoin` hook this file's `buildPresentForJoin`\n * builds instead (seam map Part 2 item 4, the #626 reviewer-spec'd shape:\n * a sync `presentI18nForJoin`-class hook on `JoinableSource`).\n *\n * `LookupSnapshot` is the sync materialized `key -> row` view over ONE\n * lookup dimension's ALREADY-LIVE backing data (the `active.ts`\n * `_syncCache`/`snapshotEntries` write-through-cache pattern — never a\n * second copy of the data: `LookupViaConfig.snapshotFor`'s vault-built\n * closure reads the SAME `LookupHandle._syncCache` /\n * first-class-collection cache every other lookup consumer\n * (`dictLabelResolver`, `resolveDictSource`, `getAltIndex`) already reads).\n * Serves (reserved AND matrix tier since #650 Task 7 — `registry.ts`'s\n * `buildLookupSnapshotRows` routes both; static tier is read straight off\n * `descriptor.table` by every consumer below, never through this cache):\n * - join dressing (`presentForJoin`, consumed by `kernel/query/join.ts`\n * via `JoinableSource.presentForJoin`)\n * - dimension sort (`compareForOrder`, consumed by\n * `via/lookup/binding.ts`'s `ViaBinding.compareForOrder` closure)\n * - per-call-locale order-label resolution (`resolveOrderLabel`, #650\n * Task 7 — the `orderBy(..., {by:'label'})` channel `compareForOrder`\n * structurally can't serve, no locale param; consumed by\n * `kernel/query/builder.ts`'s `buildOrderLabelMaps`)\n * - membership: reserved/static-tier membership (#650 Task 3,\n * `checkLookupMembership`) already reads the identical sync caches\n * directly — not re-plumbed through this file; see\n * `.superpowers/sdd/task-6-report.md`'s \"bridge disposition\" section.\n *\n * Sync end-to-end (#553) — every function here is a pure, synchronous\n * transform over already-materialized rows; no store read, no Promise.\n */\nimport type { LookupDescriptor } from './descriptor.js'\nimport { presentI18nForJoin, type I18nTextDescriptor } from '../i18n/core.js'\n\n/** A lookup dimension's sync materialized view — see file header. */\nexport interface LookupSnapshot {\n /** The full backing row for `key`, or `undefined` when `key` isn't (yet) present in the snapshot. */\n row(key: string): Record<string, unknown> | undefined\n /** The dimension's declared presentation label for `key` at `locale` — mirrors `binding.ts`'s `fetchLookupLabel` (matrix-row branch), generalized to any tier's already-materialized rows. */\n label(key: string, locale: string, fallback?: unknown): string | undefined\n /**\n * Exact ordering for two canonical keys against `descriptor.sortBy`\n * (falls back to `present.label`, then to the raw keys) at `locale`.\n * Never throws — degrades to comparing the raw keys when no sortable\n * value resolves for either side.\n */\n compareKeys(a: string, b: string, locale: string): number\n}\n\n/** Read one row field, resolving a `by`-keyed (locale-map) value when `by` is declared. */\nfunction readRowField(\n row: Record<string, unknown> | undefined,\n field: string | undefined,\n by: string | undefined,\n locale: string,\n fallback?: unknown,\n): string | undefined {\n if (!row || field === undefined) return undefined\n const raw = row[field]\n if (by === undefined) return typeof raw === 'string' ? raw : undefined\n if (!raw || typeof raw !== 'object') return undefined\n const map = raw as Record<string, unknown>\n const val = map[locale]\n if (typeof val === 'string') return val\n if (typeof fallback === 'string' && typeof map[fallback] === 'string') return map[fallback]\n return undefined\n}\n\n/**\n * Build a sync `LookupSnapshot` over one dimension's already-materialized\n * rows (canonical-key -> row, the SAME keying `materializeBackingTable`\n * (`registry.ts`, #650 Task 3) uses). Pure — never reads a store.\n */\nexport function buildLookupSnapshot(\n dimension: string,\n rows: ReadonlyMap<string, Record<string, unknown>>,\n descriptor: LookupDescriptor,\n): LookupSnapshot {\n void dimension // identity only — kept for parity with materializeBackingTable/buildLookupAltIndex's signature and future diagnostics\n return {\n row: (key) => rows.get(key),\n label: (key, locale, fallback) =>\n readRowField(rows.get(key), descriptor.present?.label, descriptor.present?.by, locale, fallback),\n compareKeys: (a, b, locale) => {\n const sortField = descriptor.sortBy ?? descriptor.present?.label\n const av = readRowField(rows.get(a), sortField, descriptor.present?.by, locale) ?? a\n const bv = readRowField(rows.get(b), sortField, descriptor.present?.by, locale) ?? b\n return av < bv ? -1 : av > bv ? 1 : 0\n },\n }\n}\n\n/**\n * The lookup-label HALF of `presentForJoin` (#626 retirement, spec §5;\n * matrix-tier coverage added #650 Task 7) — resolves `<field>Label` for\n * every declared lookup field with a `present` dressing dimension, sync,\n * from `getSnapshotRows` (the vault-built `LookupViaConfig.snapshotFor`\n * closure — now descriptor-routed, see `registry.ts`'s\n * `buildLookupSnapshotRows`; static tier reads its own in-config `table`\n * directly, no vault call — never `undefined` for a declared static table).\n * Mirrors `binding.ts`'s `runLookupPresent` (the async `present()` hook)\n * minus the array/`[].`-wildcard handling that hook needs for full-record\n * reads — join dressing only ever sees the joined RIGHT-side record's\n * scalar fields, so that complexity doesn't apply here.\n */\nfunction presentLookupForJoin(\n record: Record<string, unknown>,\n locale: string,\n lookupFields: Record<string, LookupDescriptor>,\n getSnapshotRows: (descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n let result = record\n for (const [field, desc] of Object.entries(lookupFields)) {\n if (desc.present === undefined) continue\n const raw = record[field]\n if (typeof raw !== 'string') continue\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : getSnapshotRows(desc)\n if (!rows) continue\n const label = buildLookupSnapshot(desc.dimension, rows, desc).label(raw, locale)\n if (label === undefined) continue\n if (result === record) result = { ...record }\n result[`${field}Label`] = label\n }\n return result\n}\n\n/**\n * Build the combined sync `presentForJoin(record, locale)` hook a\n * `Collection` attaches to the `JoinableSource` it exposes\n * (`querySourceForJoin()`) — the i18n-text half (`presentI18nForJoin`, the\n * exact `applyI18nLocale(..., 'join')` partial application\n * `kernel/query/join.ts` used to call directly, #626) composed with the\n * lookup-label half above. `undefined` when the collection declares\n * neither — `JoinableSource.presentForJoin` then stays unset, matching\n * today's `i18nFields`-absent behavior exactly (#626 parity lock).\n */\nexport function buildPresentForJoin(\n i18nFields: Record<string, I18nTextDescriptor> | undefined,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n getSnapshotRows: ((descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined) | undefined,\n): ((record: unknown, locale: string) => unknown) | undefined {\n const hasI18n = i18nFields !== undefined && Object.keys(i18nFields).length > 0\n const hasLookup = lookupFields !== undefined && Object.keys(lookupFields).length > 0\n if (!hasI18n && !hasLookup) return undefined\n const resolveRows = getSnapshotRows ?? (() => undefined)\n return (record, locale) => {\n if (record === null || typeof record !== 'object') return record\n let result = record as Record<string, unknown>\n if (hasI18n) result = presentI18nForJoin(result, i18nFields, locale)\n if (hasLookup) result = presentLookupForJoin(result, locale, lookupFields, resolveRows)\n return result\n }\n}\n","/**\n * Lookup strategy seam (#650 Task 1 — via-lookup extraction, phase D of the\n * Via port; precedent: `port/with/i18n-strategy.ts`). Lives on the `/with`\n * port (the one seam the kernel spine may import statically) so `Vault` can\n * reach the dict-registry pure helpers and the `LookupHandle`/`NO_LOOKUP`\n * types without a spine→`via/` static import (Check 14 via-layering bans\n * that; `port/with/` is always allowed, Check 9's sanctioned exception).\n *\n * `kernel/vault.ts` imports ONLY this module for lookup — never\n * `via/lookup/*` directly.\n *\n * This task (#650 Task 1) is a pure move: `Vault.dictionary()` still\n * constructs its handle through `i18nStrategy.buildDictionaryHandle`\n * (`port/with/i18n-strategy.ts`), which now internally delegates to\n * `withLookup().buildLookupHandle` (same handle, new home). `LookupStrategy`\n * / `NO_LOOKUP` / `isLookupCollectionName` here are the seam later phase-D\n * tasks bind `vault.collection()`'s lookup fields onto — unused by Task 1's\n * wiring, but their exact shapes are frozen now so later tasks don't\n * re-litigate them.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport type { NoydbEventEmitter } from '../../kernel/events.js'\nimport type { ViaCryptoCtx } from '../../kernel/via/index.js'\nimport type { LookupHandle, DictionaryOptions } from '../../via/lookup/handle.js'\nimport {\n enforceStaticDictOnPut,\n resolveDictSource,\n updateReferencingRecords,\n resolveLabelFromMap,\n collectLookupDictCompat,\n lookupToStaticDictCompat,\n materializeBackingTable,\n checkLookupMembership,\n buildLookupAltIndex,\n registerLookupRefEdges,\n buildLookupSnapshotRows,\n coerceLookupKey,\n resolveBackingRowKey,\n matchesReferencingValue,\n type DictReferencingCollection,\n type LookupDictCompat,\n type MaterializedBacking,\n} from '../../via/lookup/registry.js'\nimport { buildPresentForJoin } from '../../via/lookup/snapshot.js'\nimport type { LookupDescriptor } from '../../via/lookup/descriptor.js'\n\n/**\n * Backing options for `LookupStrategy.buildLookupHandle` — same shape as\n * `DictionaryOptions` (kept as a distinct alias since the \"lookup\" name is\n * the forward-looking one; `DictionaryOptions` stays the dict-tier name).\n */\nexport type LookupBackingOptions = DictionaryOptions\n\n/**\n * Options accepted by `LookupStrategy.buildLookupHandle`. Mirrors the\n * `LookupHandle` constructor verbatim, plus the two choke-point\n * participation hooks (`onDirty`/`onRecordMutated`) #647 (Task 4) wires —\n * both `undefined` in this task (pure move, no new call sites).\n */\nexport interface BuildLookupHandleOptions<Keys extends string = string> {\n readonly adapter: NoydbStore\n readonly compartmentName: string\n readonly dimensionName: string\n readonly keyring: UnlockedKeyring\n /**\n * The `reservedEnvelopes('_dict_')` capability (#629 Task 4) — the\n * handle's sanctioned crypto door onto its `_dict_<name>` collection.\n * Bound by the Vault to its own `getDEK`, the same per-collection-name\n * DEK resolver every other collection uses.\n */\n readonly reservedEnvelopes: ReturnType<ViaCryptoCtx['reservedEnvelopes']>\n readonly encrypted: boolean\n readonly ledger: LedgerStore | undefined\n readonly options: LookupBackingOptions\n readonly findAndUpdateReferences:\n | ((dimension: string, oldKey: string, newKey: string) => Promise<void>)\n | undefined\n readonly emitter: NoydbEventEmitter\n /**\n * #647 fix wave 1 — mints a version-ordered delete-marker envelope. Bound by the Vault to the\n * real `kernel/enclave` `buildDeleteMarker` function — `LookupHandle` (`via/lookup/**`)\n * may not import `kernel/enclave/` itself (Check 11/15), so this capability is injected the\n * same way `reservedEnvelopes` above is.\n */\n readonly buildDeleteMarker: (version: number, actor: string) => EncryptedEnvelope\n /** #650 Task 4 (#647) — choke-point participation hooks. */\n readonly onDirty?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n readonly onRecordMutated?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n /**\n * #650 Task 5 (#648) — the real reference check `LookupHandle.delete()`'s strict branch calls:\n * restrict throws `DictKeyInUseError` naming the referencing collection, cascade/nullify apply\n * their propagation. Bound by the Vault (never a `Collection`/keyring/DEK reach-around); a\n * no-op when the dimension has no declared lookup-referencing edges (today's dangling behavior\n * for undeclared refs is unaffected). Return value is discarded by the handle — callers who\n * need cascade/nullify counts (forget) go through `VaultLinks` directly.\n */\n readonly checkReferencesOnDelete?: ((key: string) => Promise<unknown>) | undefined\n /**\n * Used by the active strategy to satisfy the generic-key parameter on the\n * returned handle. The NO_LOOKUP stub never reads it. Mirrors\n * `BuildDictionaryHandleOptions._keyMarker` (`port/with/i18n-strategy.ts`).\n */\n // marker generic — runtime sees no value\n _keyMarker?: Keys\n}\n\nexport interface LookupStrategy {\n /**\n * Construct a typed `LookupHandle` for the named dimension. Throws under\n * `NO_LOOKUP`.\n */\n buildLookupHandle<Keys extends string = string>(\n opts: BuildLookupHandleOptions<Keys>,\n ): LookupHandle<Keys>\n}\n\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op}: the NO_LOOKUP stub was reached, which should be unreachable today — there is no ` +\n '`lookupStrategy` `createNoydb({ ... })` option yet to select this stub over the real one; ' +\n '`vault.dictionary()` always resolves through `withLookup()` (see `via/i18n/active.ts`\\'s ' +\n 'delegation). This is forward scaffolding for a later task (mirrors `NO_I18N`\\'s shape) — if you ' +\n 'hit this, it indicates a bug, not a missing opt-in.',\n )\n}\n\n/**\n * No-lookup stub. Mirrors `NO_I18N.buildDictionaryHandle`'s shape, but unlike `NO_I18N` (wired as\n * `vault.ts`'s `opts.i18nStrategy ?? NO_I18N` default), nothing selects this stub today — there is\n * no `lookupStrategy` option on `createNoydb()`; `vault.dictionary()`'s only construction path\n * (`Vault.i18nStrategy.buildDictionaryHandle` → `withLookup().buildLookupHandle`) never reaches\n * here. Kept as forward scaffolding for a later task that wires an independent lookup opt-in.\n */\nexport const NO_LOOKUP: LookupStrategy = {\n buildLookupHandle() {\n throw notEnabled('vault.dictionary()')\n },\n}\n\n/** `_dict_*` (legacy dict tier) and `_lookup_*` (the phase-D reserved backing). */\nexport const LOOKUP_COLLECTION_PREFIXES = ['_dict_', '_lookup_'] as const\n\n/** Return true when a collection name is a reserved lookup-backing collection. */\nexport function isLookupCollectionName(name: string): boolean {\n return LOOKUP_COLLECTION_PREFIXES.some((prefix) => name.startsWith(prefix))\n}\n\n// Re-exported pure registry helpers (#650 Task 1) — `kernel/vault.ts`'s\n// thin delegators call these directly; small always-on functions, not\n// behind the tree-shake seam (same bundling class as `isLookupCollectionName`\n// above, just too large to duplicate inline like that one is).\nexport { enforceStaticDictOnPut, resolveDictSource, updateReferencingRecords }\nexport type { DictReferencingCollection }\n\n// #650 Task 4 (#647) — the reserved-collection naming helper `vault.ts`'s sync-registry\n// bookkeeping needs (mapping a declared dimension name to its `_dict_<name>` collection name).\nexport { dictCollectionName } from '../../via/lookup/handle.js'\n\n// #650 Task 2 — the alias-equivalence bridge (`resolveLabelFromMap` +\n// `collectLookupDictCompat`/`lookupToStaticDictCompat`) + the runtime\n// brand/shape predicates `via/compose.ts` needs to route `'lookup'`-branded\n// descriptors, mirroring `isI18nTextDescriptor`/`isDictKeyDescriptor` below.\nexport { resolveLabelFromMap, collectLookupDictCompat, lookupToStaticDictCompat }\nexport type { LookupDictCompat }\n\n// #650 Task 3 — altKeys ingest normalization + open/closed vocabulary\n// governance: the declare/warm-time altIndex builder + the membership test\n// vault.ts's `membership`/`getAltIndex` closures delegate to.\nexport { materializeBackingTable, checkLookupMembership, buildLookupAltIndex }\nexport type { MaterializedBacking }\n\n// #650 Task 5 — registers a collection's lookup-fields' cross-collection 'ref' graph edges.\nexport { registerLookupRefEdges }\n\n// #650 Task 6 — the sync snapshot+locale seam (#626 retirement, spec §5):\n// `snapshotFor`'s vault-built row source + the combined presentForJoin\n// builder `kernel/collection-config.ts` calls to build the\n// `JoinableSource.presentForJoin` hook `kernel/query/join.ts` consumes.\nexport { buildLookupSnapshotRows, buildPresentForJoin }\nexport type { LookupSnapshot } from '../../via/lookup/snapshot.js'\n\n// #651 Task 3 — the ONE descriptor-keyed key-resolution core (guarded coercion +\n// backing-row-key resolve + referencing-value match) — every consumer (vault.ts,\n// with-shape/links/vault-facade.ts, kernel/via/dispatch.ts) routes through here,\n// never a bare `String()`, ending the dm12 dialect drift.\nexport { coerceLookupKey, resolveBackingRowKey, matchesReferencingValue }\n\n/** Runtime predicate for detecting a `LookupDescriptor` (any of the three tiers). */\nexport function isLookupDescriptor(x: unknown): x is LookupDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _viaBrand?: unknown })._viaBrand === 'lookup'\n )\n}\n\n/** Runtime predicate for the bare enum tier (`backing:'static'`, no in-code `table` — no label source). */\nexport function isEnumDescriptor(x: unknown): x is LookupDescriptor {\n return isLookupDescriptor(x) && x.backing === 'static' && x.table === undefined\n}\n\n/**\n * Type-only re-exports — the kernel spine imports these descriptor/handle\n * types through the port instead of reaching into `via/lookup/*` or\n * `via/i18n/*` directly. `isolatedModules: true` erases these at\n * build time — no runtime coupling.\n */\nexport type { LookupHandle, DictEntry, DictionaryOptions } from '../../via/lookup/handle.js'\nexport type { LookupDescriptor, Vocabulary, LookupBacking, OnDelete } from '../../via/lookup/descriptor.js'\nexport type { LookupViaConfig } from '../../via/lookup/binding.js'\nexport type { DictKeyDescriptor, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\n","// kernel/via/dispatch.ts — the batched, origin-aware sync/cutover/restore dispatch wave\n// (Via port phase C, #638 Task 4, fixes #621).\n//\n// `Collection._onRecordMutated`'s `sync-apply`/`cutover`/`restore` cases feed touched\n// (collection, id) pairs into a per-session `GraphBatch` (owned by `Vault._collectGraphTouch`)\n// instead of dispatching inline — the `local-write` path keeps its own byte-identical inline\n// dispatch (`wave` stays `undefined` there, per the spec's behavior lock). At batch-flush time\n// `runGraphDispatchWave` decrypts each touched record (id threaded into the decrypt, matching\n// the phase-B at-rest contract) and re-runs the SAME `dispatchDerivations`/\n// `dispatchMaterializedViews` the local-write path uses, sharing one `WaveContext` so N touched\n// records feeding the SAME rollup/MV target recompute exactly once (per-target dedup).\n// See docs/superpowers/specs/2026-07-11-via-phase-c-design.md §3.\n\nimport type { ViaGraph } from './graph.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport { PeriodClosedError } from '../errors.js'\nimport { matchesReferencingValue } from '../../port/with/lookup-strategy.js'\n\n/** One deleted child's resolved rollup PARENT intent (#640) — ids + a field name only. A\n * resolved `parentId` is an id, same class as any touched record id — never a stored value. */\nexport interface RollupDeleteIntent {\n readonly into: string\n readonly parentId: string\n readonly field: string\n}\n\n/** One collection's batched touches this session (#640 widens the #638 `Set<string>` shape):\n * `puts` — the original semantics, unchanged; `deletes` — a deleted record's id mapped to its\n * resolved rollup-parent intents, captured PRE-invalidation by `Collection._onRecordMutated`'s\n * sync-apply delete case (the FK is only readable there — see `kernel/collection.ts\n * #_rollupDeleteIntents`). */\nexport interface GraphTouch {\n readonly puts: Set<string>\n readonly deletes: Map<string, readonly RollupDeleteIntent[]>\n}\n\n/** Per-session touched set — collection → its `GraphTouch`. Metadata only — ids (collection\n * names, record ids INCLUDING resolved rollup parent ids) and field names; NEVER record payload\n * or key material. A resolved parentId is an id, same class as the touched ids — not a stored\n * value. */\nexport type GraphBatch = Map<string, GraphTouch>\n\n/** Get-or-create `batch`'s `GraphTouch` entry for `collection` (#640) — shared by\n * `Vault._collectGraphTouch`/`_collectGraphDelete` so each stays a one-line call. */\nexport function touchFor(batch: GraphBatch, collection: string): GraphTouch {\n let t = batch.get(collection)\n if (!t) {\n t = { puts: new Set(), deletes: new Map() }\n batch.set(collection, t)\n }\n return t\n}\n\n/** #640 — sync, I/O-free: `deleted`'s resolved rollup PARENT intents (the FK is only readable\n * NOW, before the record is gone) — a pure function so `Collection._rollupDeleteIntents` stays\n * a one-line delegator under the kernel-surface ceiling. `registry` is `this.derivationSource\n * ?.registry()`; `collectionName` is `this.name` (the CHILD/`rollup.from` side). Generic over\n * the registry's own spec shape so this file never imports a `with-formula` type (port-layering\n * — via/dispatch.ts must not gain a with-* import). */\nexport function resolveRollupDeleteIntents<S extends { source: string; rollup?: { from: string; key: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n deleted: Record<string, unknown>,\n): RollupDeleteIntent[] {\n if (!registry) return []\n const intents: RollupDeleteIntent[] = []\n for (const { spec } of registry.strategiesForSource(collectionName)) {\n if (!spec.rollup || spec.rollup.from !== collectionName) continue\n const kv = deleted[spec.rollup.key]\n if (typeof kv === 'string' || typeof kv === 'number') intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field })\n }\n return intents\n}\n\n/** #640 — resolve a `RollupDeleteIntent` back to its registry `spec`. The wave's per-intent\n * driver needs `spec.rollup.compute`, which `GraphBatch`'s metadata-only pin forbids batching —\n * so it's re-resolved here, post-boundary, instead of carried across it. `undefined` if the\n * intent's originating strategy was unregistered between collect time and wave time (residual\n * gap, freshness-only). */\nexport function findRollupSpecForIntent<S extends { source: string; rollup?: { from: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n intent: RollupDeleteIntent,\n): S | undefined {\n return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec\n}\n\n/** One dedup ledger for a single wave — a target is recomputed at most once (mark-on-check). */\nexport class WaveContext {\n private readonly _seen = new Set<string>()\n seen(targetKey: string): boolean {\n if (this._seen.has(targetKey)) return true\n this._seen.add(targetKey)\n return false\n }\n}\n\n/** The slice of `Vault` the wave needs: the shared graph (the #553 zero-cost skip) and cached-\n * collection lookup — never constructs, since a touched collection is, by construction,\n * already open (it just fired `_onRecordMutated`). */\nexport interface VaultLike {\n readonly graph: ViaGraph\n _getCollection(name: string): Collection<Record<string, unknown>> | undefined\n /** #640 (#644 item 3) — structured wave-error surfacing, additive to the existing console.warn. */\n _emit(event: string, payload: unknown): void\n}\n\n/**\n * Run ONE dispatch wave for a completed batch: for each touched (collection, id), decrypt the\n * applied envelope (id threaded), then run the SAME `dispatchDerivations` +\n * `dispatchMaterializedViews` the local-write path uses — with a shared `WaveContext` so N\n * touched records feeding the SAME target recompute once. #553: a collection with no graph\n * out-edges (e.g. money-only) is skipped before any decrypt/dispatch async work.\n */\nexport async function runGraphDispatchWave(vault: VaultLike, batch: GraphBatch): Promise<void> {\n const wave = new WaveContext()\n for (const [collectionName, touch] of batch) {\n if (vault.graph.dependentsOf(collectionName).length === 0) continue\n const coll = vault._getCollection(collectionName)\n if (!coll) continue\n for (const id of touch.puts) {\n try {\n // Decrypt is INSIDE the per-id isolation boundary (whole-branch review Important\n // finding, #638): an undecryptable synced envelope (`TamperedError`) must not\n // escape `_getStoredRecordForDispatch` and abort the wave — that would propagate\n // through `_flushGraphBatch` and reject the surrounding `SyncEngine.pull`/`push`\n // AFTER records were already applied + meta persisted, starving every other\n // touched target in the same batch.\n const stored = await coll._getStoredRecordForDispatch(id)\n if (!stored) continue\n await coll.dispatchDerivations(id, stored.record, stored.version, wave)\n await coll.dispatchMaterializedViews(id, stored.record, wave)\n } catch (err) {\n // #638 Task 5 review mandate: one touched record's recompute must not abort the\n // whole wave (starving co-batched healthy targets) or the pull/push it's nested\n // inside. `PeriodClosedError` never reaches here — `putDerivedOutput` already\n // intercepts it at every output-write call site and turns it into a skip+event.\n // Anything else (a genuine decrypt failure, a derive()/executor bug, a schema\n // violation on the output, ...) is surfaced — not silently swallowed — via the\n // SAME console.warn channel `dispatchDerivations`/the MV executor already use for\n // their own non-strict-mode output failures, then isolated to just this one id.\n // #644 item 3: ADDITIVELY (never in place of the warn) emit a structured event too,\n // so a listener doesn't have to scrape console output to react to a wave failure.\n console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n // #640 — delete-kind touches: the deleted child's rollup-parent intents, resolved (sync,\n // pre-invalidation) at collect time by `Collection._rollupDeleteIntents`. Same per-id\n // isolation as the puts loop above; never routed through `dispatchDerivations` (the\n // mutation-choke-point.test.ts:85-99 pin — sync-applied deletes are rollup-on-delete only).\n for (const [id, intents] of touch.deletes) {\n try {\n await coll._recomputeDeletedRollups(intents, wave)\n } catch (err) {\n console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n }\n}\n\n/** A record's post-freeze source mutation, for the `'derivation:skipped-frozen'` event\n * and the optional audit-trail entry. See {@link putDerivedOutput}. */\nexport interface DerivationSkippedFrozen {\n readonly source: { readonly collection: string; readonly id: string }\n readonly target: { readonly collection: string; readonly id: string }\n readonly period: string\n readonly endDate: string\n}\n\n/** The minimal put-capable shape `putDerivedOutput` needs. Any `Collection<T>` structurally\n * satisfies this — its real `options` type is a superset of what's declared here. */\nexport interface CollectionLike {\n put(id: string, value: unknown, options?: { readonly source?: string }): Promise<void>\n}\n\nexport interface PutDerivedOutputCtx {\n readonly emit: (ev: string, p: unknown) => void\n readonly source: { readonly collection: string; readonly id: string }\n readonly audit?: ((e: DerivationSkippedFrozen) => Promise<void>) | undefined\n}\n\n/**\n * Attempt a dispatch-driven output write. On `PeriodClosedError` (the closed-period\n * `beforePut` gate — `freezePeriod`/`archivePeriod` add no separate gate, per seam map\n * Part 7): SKIP (no `_ts` stamped — the gate throws before any write happens), emit\n * `'derivation:skipped-frozen'` on the event bus (ALWAYS), and append an audit-trail entry\n * when the with-history ledger is active. Returns `'written' | 'skipped-frozen'`. Any OTHER\n * error propagates unchanged — this helper narrows exactly one error class. The SOURCE\n * write is never wrapped through this helper — only derived-output writes are (§7).\n */\nexport async function putDerivedOutput(\n outColl: CollectionLike, id: string, value: unknown,\n ctx: PutDerivedOutputCtx,\n options?: { readonly source?: string },\n): Promise<'written' | 'skipped-frozen'> {\n try {\n await outColl.put(id, value, options)\n return 'written'\n } catch (err) {\n if (!(err instanceof PeriodClosedError)) throw err\n // Reach-around for the target collection's private `name` — the SAME pattern\n // `with-formula/materialized-views/executor.ts`'s `listOutputIds` already uses to\n // read a `Collection`'s private `adapter`/`vault`/`name` fields from outside the class.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetCollection = (outColl as any).name as string\n const event: DerivationSkippedFrozen = {\n source: ctx.source,\n target: { collection: targetCollection, id },\n period: err.periodName,\n endDate: err.endDate,\n }\n ctx.emit('derivation:skipped-frozen', event)\n if (ctx.audit) await ctx.audit(event)\n return 'skipped-frozen'\n }\n}\n\n/** Structural (no static import — kernel spine may not statically reach a with-* service,\n * the S4 gate recipe `check-architecture.mjs`'s port-layering check enforces) shape of the\n * with-history `LedgerStore.append` seam this helper needs. */\ninterface AuditLedgerLike {\n append(input: {\n readonly op: 'lifecycle'\n readonly collection: string\n readonly id: string\n readonly version: number\n readonly actor: string\n readonly payloadHash: string\n readonly reason?: string\n }): Promise<unknown>\n}\n\n/** @internal — the optional with-history ledger audit hook for `putDerivedOutput`, present\n * only when the ledger is active (mirrors every other kernel event's `if (this.ledger)`\n * gate). Encoded as a `'lifecycle'` entry — the existing \"non-data audit event\" op (the\n * same convention `forget`'s JSON-summary-in-`reason` entry uses; `ledger/entry.ts:88-104`). */\nexport function ledgerAuditHook(\n ledger: AuditLedgerLike | undefined, actor: string,\n): ((e: DerivationSkippedFrozen) => Promise<void>) | undefined {\n if (!ledger) return undefined\n return async (e) => {\n await ledger.append({\n op: 'lifecycle', collection: e.target.collection, id: e.target.id, version: 0, actor, payloadHash: '',\n reason: JSON.stringify({ event: 'derivation-skipped-frozen', ...e }),\n })\n }\n}\n\n/** `recomputeRollup`/`dispatchRollupsOnDelete`'s per-target write outcome (#638 Task 6):\n * `'written'`/`'skipped-frozen'` mirror {@link putDerivedOutput}'s result; `'noop'` covers\n * no-parent/no-change/deduped-by-wave — nothing to report either way. */\nexport type RollupOutcome = 'written' | 'skipped-frozen' | 'noop'\n\n/** Mutable accumulator `forgetDerivedFanout` writes into, one per `Vault.forget()` call — keeps\n * the per-ref loop's call site to a single line under vault.ts's tight kernel-surface ceiling.\n * Maps 1:1 onto `ForgetResult`'s additive fields (`with-audit/forget/strategy.ts`). */\nexport interface ForgetFanoutStats {\n recordsErased: number\n aggregatesRecomputed: number\n readonly residueFrozen: string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred row (the backing row itself is unreadable) — propagation was\n * skipped for these, reported here so the skip is never silent. `backing:key:collection.field`\n * entries, one per un-propagated edge. */\n readonly lookupReferencesResidue: string[]\n}\n\n/**\n * #622 — after `_writeTombstone(ref.id, actor)` erases the forgotten subject's own record, fan\n * out to its derived residue via the graph (spec §5): record-grain artifacts (MV rows,\n * array-shape derivation rows, same-id record-shape derivation copies) are ERASED through the\n * SAME `!internal` housekeeping-bypass machinery the ordinary delete path uses (no user\n * `onDelete` re-fires — the shred-is-not-a-domain-delete property `_writeTombstone` protects);\n * aggregate-grain rollups are RECOMPUTED without the forgotten contribution in open periods, or\n * skip+audit (via `putDerivedOutput`, already wired into the rollup/MV output paths) in frozen\n * ones. Mutates `stats` in place. `envelope` is `ref`'s PRE-tombstone envelope, decoded only if\n * a rollup edge is actually present — the #553 zero-cost-skip discipline: no decrypt for the\n * common case of a forgotten record with no aggregate-grain consumer, and no work at all when\n * `ref.collection` has no graph out-edges. `lookupCompareKeys` is the `'ref'` edges' compare-key\n * map, resolved from the LIVE row BEFORE any shred (`VaultLinks.checkLookupRefsRestrict`'s return\n * value — `Vault.forget()`'s pre-shred restrict check doubles as the live-resolve pass) — see\n * {@link applyLookupRefsFanout}.\n */\nexport async function forgetDerivedFanout(\n vault: VaultLike,\n ref: { readonly collection: string; readonly id: string },\n envelope: EncryptedEnvelope | null,\n stats: ForgetFanoutStats,\n lookupCompareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<void> {\n const edges = vault.graph.derivedArtifactsOf(ref.collection)\n if (edges.length === 0) return\n\n const coll = vault._getCollection(ref.collection)\n if (!coll) return\n\n // #650 Task 5 (#648) — 'ref' cascade/nullify propagate ADDITIVELY, here, AFTER the shred\n // (restrict already refused BEFORE any shred — the caller's pre-tombstone check, spec §4).\n // The I/O shell (loop shape, collection accessor) is duplicated, not imported, from\n // `VaultLinks.applyLookupRefsPropagation`/`checkLookupRefsRestrict` (with-shape/links/\n // vault-facade.ts) — the kernel spine may not statically import a with-* service\n // (port-layering, the #638 Task 5 via/dispatch.ts precedent); `vault._getCollection` is\n // cached-only while `VaultLinks`' accessor constructs. The pure match predicate itself is\n // shared through the port seam (#651 Task 3 — `matchesReferencingValue`, `port/with/\n // lookup-strategy.ts`), so only the shell, not the coercion logic, stays duplicated. A\n // referencing edge whose dimension uses a non-default `key` (matrix tier only) needs the\n // backing row's OWN value at that field, not its PUT-id — the row is ALREADY tombstoned by\n // now, so it's read from `lookupCompareKeys`, resolved by the caller from the LIVE row\n // BEFORE the shred (#650 Task 5 review, Important fix — eliminates the post-shred\n // envelope-decode dependency this used to have, which silently skipped propagation whenever\n // that decode failed).\n if (edges.some((e) => e.kind === 'ref')) {\n const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys)\n stats.lookupReferencesCascaded += cascaded\n stats.lookupReferencesNullified += nullified\n stats.lookupReferencesResidue.push(...residue)\n }\n\n if (edges.some((e) => e.kind === 'mv')) {\n stats.recordsErased += await coll.dispatchMaterializedViewsOnDelete(ref.id)\n }\n if (edges.some((e) => e.kind === 'derivation')) {\n // #622 review Finding 1: count REAL erasures (dispatchArrayDerivationsOnDelete's own\n // `_internalDelete`-backed tally), not the derivation EDGE count — an edge exists whenever\n // this collection is ANY trigger (source/sources[]/triggerBy), but the same-id record-shape\n // guard only erases for `spec.source === this.name`, and `derive()` may never have produced\n // an output row (optional-skip) in the first place. Both cases must contribute 0, not +1.\n stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true)\n }\n\n if (envelope && edges.some((e) => e.kind === 'rollup')) {\n const priorRecord = await coll._decodeEnvelope(envelope, ref.id)\n if (priorRecord) {\n for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {\n if (r.outcome === 'written') stats.aggregatesRecomputed += 1\n else if (r.outcome === 'skipped-frozen') stats.residueFrozen.push(`${r.into}:${r.parentId}`)\n }\n }\n }\n}\n\n/**\n * Apply `cascade`/`nullify` propagation for `backing`'s non-restrict `'ref'` edges — the\n * forget-path counterpart of `VaultLinks.applyLookupRefsPropagation` (I/O shell duplicated, not\n * imported, match predicate shared via the port — see {@link forgetDerivedFanout}'s call site\n * comment). `restrict` edges are skipped here: the\n * forget loop's `checkLookupRefsRestrict`-equivalent call already refused (or the reference no\n * longer existed) BEFORE `_writeTombstone` ran, so by the time this runs only cascade/nullify\n * remain to propagate. `compareKeys` is the non-`'id'`-`keyField` compare-value map, resolved by\n * the caller from the LIVE row BEFORE the shred (#650 Task 5 review, Important fix) — the live row\n * is already shredded by the time THIS function runs, so it can no longer resolve one itself. A\n * `keyField` absent from (or `undefined` in) the map means that live resolve failed too — the edge\n * is reported as residue instead of silently skipped (never a bare `continue` with no trace).\n */\nasync function applyLookupRefsFanout(\n vault: VaultLike,\n backing: string,\n key: string,\n compareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<{ cascaded: number; nullified: number; residue: string[] }> {\n let cascaded = 0\n let nullified = 0\n const residue: string[] = []\n for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {\n if (onDelete === 'restrict') continue\n const compareKey = keyField === 'id' ? key : compareKeys.get(keyField)\n if (compareKey === undefined) {\n residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`)\n continue\n }\n const coll = vault._getCollection(referencing.collection)\n if (!coll) continue\n const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey))\n for (const rec of matches) {\n const id = rec['id'] as string | undefined\n if (id === undefined) continue\n if (onDelete === 'cascade') {\n await coll.delete(id)\n cascaded++\n } else if (onDelete === 'nullify') {\n await coll.put(id, { ...rec, [referencing.field]: null })\n nullified++\n }\n }\n }\n return { cascaded, nullified, residue }\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BO,SAAS,uBACd,cACA,QACM;AACN,MAAI,CAAC,gBAAgB,OAAO,KAAK,YAAY,EAAE,WAAW,EAAG;AAC7D,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAE3C,QAAM,MAAM;AACZ,aAAW,CAAC,OAAO,IAAI,KAAK,OAAO,QAAQ,YAAY,GAAG;AACxD,QAAI,KAAK,kBAAkB,MAAO;AAClC,UAAM,QAAQ,IAAI,IAAY,KAAK,IAAI;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