@hawkeyexl/manni 4.20.0 → 4.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{batch-TBQBH6XQ.js → batch-C534YIAU.js} +14 -14
- package/dist/{build-S3JQMDFX.js → build-SVKT7QFU.js} +16 -15
- package/dist/{calibrate-KLN22IGS.js → calibrate-AL3MH7TY.js} +15 -15
- package/dist/{capture-JS3ICXE7.js → capture-2F7B4DAD.js} +14 -14
- package/dist/check-BI7OGIVE.js +48 -0
- package/dist/{check-WS2USSUD.js → check-JZINDP3F.js} +13 -13
- package/dist/{check-2EAR4ZW3.js → check-LKPQPQWJ.js} +15 -15
- package/dist/check-OPUMZEVK.js +35 -0
- package/dist/{check-PDXYA6XH.js → check-OW7UD73D.js} +12 -12
- package/dist/{chunk-JKH2LV5D.js → chunk-22WGKOQ7.js} +5 -5
- package/dist/{chunk-IGAZWY2W.js → chunk-2HOWRAWK.js} +2 -2
- package/dist/{chunk-KZ7534CD.js → chunk-2NGFDLIM.js} +3 -3
- package/dist/{chunk-SOW6SVAM.js → chunk-2YKUSTHS.js} +4 -4
- package/dist/{chunk-DQO44Y5G.js → chunk-3SFAB75L.js} +5 -5
- package/dist/{chunk-BEQZI3V5.js → chunk-5LE4NH3Z.js} +24 -7
- package/dist/chunk-5LE4NH3Z.js.map +1 -0
- package/dist/{chunk-U2CE55YV.js → chunk-5UJKXOAD.js} +5 -5
- package/dist/chunk-6XK3NTL5.js +706 -0
- package/dist/chunk-6XK3NTL5.js.map +1 -0
- package/dist/{chunk-6D7FCU4E.js → chunk-762MM6NA.js} +3 -3
- package/dist/{chunk-ZEKQRBXO.js → chunk-A4QNKEX4.js} +2 -2
- package/dist/{chunk-2G4XYGTN.js → chunk-AE6KBAAU.js} +7 -7
- package/dist/chunk-AE6KBAAU.js.map +1 -0
- package/dist/{chunk-SX626JUF.js → chunk-APAF4VWW.js} +3 -3
- package/dist/{chunk-BV7FJ4V2.js → chunk-ARNI3SJT.js} +8 -8
- package/dist/chunk-ARNI3SJT.js.map +1 -0
- package/dist/{chunk-DTSWP5FC.js → chunk-BHGFLRXM.js} +5 -5
- package/dist/{chunk-PGDUVYTF.js → chunk-BJUEOC4G.js} +2 -2
- package/dist/{chunk-5MJE5KMY.js → chunk-BKY6GAFA.js} +8 -8
- package/dist/{chunk-ITA7V5Y2.js → chunk-BLXRIAV2.js} +4 -4
- package/dist/{chunk-SFSALDIR.js → chunk-BXCVOHEX.js} +7 -7
- package/dist/{chunk-PHOWMWFJ.js → chunk-BXE4L52Q.js} +2 -11
- package/dist/chunk-BXE4L52Q.js.map +1 -0
- package/dist/{chunk-VCU7OMXV.js → chunk-CLPC3LKX.js} +13 -9
- package/dist/chunk-CLPC3LKX.js.map +1 -0
- package/dist/{chunk-PTXHJLAS.js → chunk-CREFJCWZ.js} +7 -7
- package/dist/chunk-CREFJCWZ.js.map +1 -0
- package/dist/{chunk-FRM62BEN.js → chunk-CZIO37J5.js} +3 -3
- package/dist/{chunk-SFTWEGUD.js → chunk-D4QHRVDJ.js} +2 -2
- package/dist/{chunk-6VGWLCYT.js → chunk-D5GBYKDU.js} +2 -2
- package/dist/{chunk-RXCDT55X.js → chunk-DENZLZ3Z.js} +34 -32
- package/dist/chunk-DENZLZ3Z.js.map +1 -0
- package/dist/{chunk-GVOI7SCF.js → chunk-DMVBIIP3.js} +3 -3
- package/dist/{chunk-5HB4YKZW.js → chunk-DPDG3FHL.js} +17 -3
- package/dist/chunk-DPDG3FHL.js.map +1 -0
- package/dist/{chunk-O26NQ7KT.js → chunk-E23KWEPL.js} +2 -2
- package/dist/{chunk-NDQA4VYK.js → chunk-E7OG5F6S.js} +3 -3
- package/dist/{chunk-HIZNNOVW.js → chunk-FHJIH6XP.js} +16 -106
- package/dist/chunk-FHJIH6XP.js.map +1 -0
- package/dist/{chunk-JNMY7KZG.js → chunk-G5I2JTDK.js} +2 -2
- package/dist/{chunk-O4O6JOGD.js → chunk-GMLOAKOA.js} +16 -4
- package/dist/chunk-GMLOAKOA.js.map +1 -0
- package/dist/{chunk-4KM23E53.js → chunk-H5YWCCBO.js} +16 -11
- package/dist/chunk-H5YWCCBO.js.map +1 -0
- package/dist/{chunk-HSC5G3FW.js → chunk-HHJ2HFPP.js} +8 -8
- package/dist/{chunk-HZWLHSZG.js → chunk-IN5T22FP.js} +2 -2
- package/dist/{chunk-FERFWKZM.js → chunk-IOJD2RFG.js} +2 -2
- package/dist/{chunk-ZODSGFAP.js → chunk-JQA6RF4R.js} +22 -22
- package/dist/{chunk-ZODSGFAP.js.map → chunk-JQA6RF4R.js.map} +1 -1
- package/dist/{chunk-GCF7STEA.js → chunk-JUUCCML3.js} +4 -4
- package/dist/{chunk-3OXBZSDN.js → chunk-KBSTXL6L.js} +3 -3
- package/dist/{chunk-SRTBHEUM.js → chunk-KCWNJMSS.js} +3 -3
- package/dist/{chunk-2XRSQXGZ.js → chunk-KQDRO6N6.js} +2 -2
- package/dist/{chunk-ZVEDBFTM.js → chunk-LWBNHK72.js} +45 -41
- package/dist/chunk-LWBNHK72.js.map +1 -0
- package/dist/{chunk-QSY5YPM4.js → chunk-MTCOBRCX.js} +4 -4
- package/dist/{chunk-Q5EKERQS.js → chunk-NLJ3XIKT.js} +7 -5
- package/dist/{chunk-Q5EKERQS.js.map → chunk-NLJ3XIKT.js.map} +1 -1
- package/dist/{chunk-RGZBROMW.js → chunk-OWJLB2AF.js} +2 -2
- package/dist/{chunk-QA7AXRGH.js → chunk-P7HAXMFN.js} +2 -2
- package/dist/{chunk-GXDVERLV.js → chunk-PACZEDOH.js} +5 -5
- package/dist/{chunk-QSPH4F56.js → chunk-PTGXEZQD.js} +2 -2
- package/dist/chunk-PTGXEZQD.js.map +1 -0
- package/dist/{chunk-UKSXQHSE.js → chunk-Q76T6Y6X.js} +6 -6
- package/dist/{chunk-SGI3WPYK.js → chunk-R2CR62JV.js} +4 -4
- package/dist/{chunk-MLY65CQE.js → chunk-RKACUTY5.js} +7 -7
- package/dist/{chunk-MNK732BZ.js → chunk-RQPEKHZH.js} +14 -11
- package/dist/chunk-RQPEKHZH.js.map +1 -0
- package/dist/{chunk-EBYLQE7P.js → chunk-RWXR3GJI.js} +2 -2
- package/dist/{chunk-JOZVVIVD.js → chunk-S5G6T4VC.js} +3 -3
- package/dist/chunk-SHXPE4D4.js +100 -0
- package/dist/chunk-SHXPE4D4.js.map +1 -0
- package/dist/{chunk-GL2HXZVX.js → chunk-TFVNEPMF.js} +3 -3
- package/dist/{chunk-TKINOTVS.js → chunk-TI4DA6DF.js} +1 -1
- package/dist/{chunk-TKINOTVS.js.map → chunk-TI4DA6DF.js.map} +1 -1
- package/dist/{chunk-I62V2ZAJ.js → chunk-U4OJ7U45.js} +8 -8
- package/dist/{chunk-QWCP7UMG.js → chunk-V2XJJEEF.js} +6 -6
- package/dist/{chunk-5UJQLZXY.js → chunk-VLRIP4BQ.js} +60 -63
- package/dist/chunk-VLRIP4BQ.js.map +1 -0
- package/dist/{chunk-ZRMA5U53.js → chunk-WHVFHBL3.js} +3 -3
- package/dist/{chunk-IYRGV2BC.js → chunk-XBJKYXOR.js} +6 -6
- package/dist/{chunk-ZBE735BH.js → chunk-XI3BNZG4.js} +5 -5
- package/dist/{chunk-Z6FATXBE.js → chunk-YSZNJ2ID.js} +2 -2
- package/dist/{cli-4HH6IY2L.js → cli-3PBRPPMQ.js} +14 -14
- package/dist/{cli-GVHXRQAD.js → cli-6NKE6RMT.js} +18 -18
- package/dist/{cli-T4NY2EGM.js → cli-77A46SB2.js} +17 -17
- package/dist/{cli-EQG4KETY.js → cli-AVHLY2AI.js} +61 -45
- package/dist/cli-AVHLY2AI.js.map +1 -0
- package/dist/{cli-UIY57JPM.js → cli-FDXU7CGZ.js} +16 -15
- package/dist/{cli-UIY57JPM.js.map → cli-FDXU7CGZ.js.map} +1 -1
- package/dist/{cli-5BFVL3DH.js → cli-FSDJY5OC.js} +2 -2
- package/dist/{cli-L7H4C442.js → cli-JNYL6LB7.js} +16 -16
- package/dist/{cli-HTAR3PWY.js → cli-K47XWDLJ.js} +21 -21
- package/dist/{cli-ZPW5VIRA.js → cli-LP5OE3BL.js} +9 -9
- package/dist/{cli-AR43H5BW.js → cli-MOKRUHZT.js} +9 -9
- package/dist/{cli-4IE6CRAT.js → cli-MQXOK64K.js} +27 -26
- package/dist/{cli-4IE6CRAT.js.map → cli-MQXOK64K.js.map} +1 -1
- package/dist/cli.js +15 -15
- package/dist/{config-7I5CHHRZ.js → config-BMWDC66C.js} +2 -2
- package/dist/docmeta.d.ts +1 -1
- package/dist/docmeta.js +8 -8
- package/dist/github-6GYTPSGV.js +35 -0
- package/dist/{github-RIU47U73.js → github-DJOLVNDD.js} +12 -12
- package/dist/{github-CMWG4QMI.js → github-ZF2TQ3RP.js} +14 -14
- package/dist/graph/embed.d.ts +2 -1
- package/dist/graph/runtime.d.ts +2 -1
- package/dist/index.d.ts +29 -15
- package/dist/index.js +51 -49
- package/dist/index.js.map +1 -1
- package/dist/json-Y7625EFE.js +42 -0
- package/dist/{json-KSBVGZUX.js → json-YIK72XAL.js} +12 -12
- package/dist/{labels-VNKACCAG.js → labels-X633ZPK7.js} +11 -11
- package/dist/{lint-75BD6L5T.js → lint-RF3B55W7.js} +14 -14
- package/dist/{list-MH54XU7E.js → list-5DW4QZ7P.js} +12 -12
- package/dist/list-7CHWJ633.js +39 -0
- package/dist/{list-PHNZAYIM.js → list-UNWG6NPD.js} +12 -12
- package/dist/{page-5AJS7AEM.js → page-OMPEACUN.js} +11 -11
- package/dist/{prepare-R63RJI6O.js → prepare-B4JVDVOV.js} +13 -13
- package/dist/{pretty-DE4WXJFA.js → pretty-PPNHHOEN.js} +13 -13
- package/dist/{pretty-E3DS32NZ.js → pretty-U7ATCFBN.js} +12 -12
- package/dist/pretty-XGYQ25PH.js +43 -0
- package/dist/{reporters-V2PSDBVW.js → reporters-FAIEOTC4.js} +13 -13
- package/dist/{reporters-DLMLFLKS.js → reporters-KE7AZR6C.js} +4 -4
- package/dist/{run-QT2LVHRU.js → run-MHJ3AYKG.js} +12 -12
- package/dist/{sarif-GKMUHCZB.js → sarif-DOGRSGTB.js} +10 -10
- package/dist/{sarif-HUIRTPSL.js → sarif-MIEMQOIK.js} +11 -11
- package/dist/{sarif-2ZKPRT42.js → sarif-RGRG7VFX.js} +15 -15
- package/dist/{strategy-TBFM7NZU.js → strategy-EK5VY5DG.js} +24 -23
- package/dist/{strategy-TBFM7NZU.js.map → strategy-EK5VY5DG.js.map} +1 -1
- package/dist/{term-ZZWAVUW5.js → term-MDN3NJDW.js} +17 -17
- package/dist/{validate-ZEUFF3BG.js → validate-QDYQ642J.js} +5 -5
- package/package.json +21 -21
- package/plugin/manni/.claude-plugin/plugin.json +11 -3
- package/plugin/manni/hooks/hooks.json +4 -4
- package/plugin/manni/hooks/manni.mjs +47 -7
- package/plugin/manni/hooks/tracevals.mjs +7 -0
- package/plugin/manni/skills/fix/SKILL.md +5 -1
- package/dist/check-6D2JCIMD.js +0 -47
- package/dist/check-RNAB7X74.js +0 -33
- package/dist/chunk-2G4XYGTN.js.map +0 -1
- package/dist/chunk-4KM23E53.js.map +0 -1
- package/dist/chunk-5HB4YKZW.js.map +0 -1
- package/dist/chunk-5UJQLZXY.js.map +0 -1
- package/dist/chunk-BEQZI3V5.js.map +0 -1
- package/dist/chunk-BV7FJ4V2.js.map +0 -1
- package/dist/chunk-HIZNNOVW.js.map +0 -1
- package/dist/chunk-MNK732BZ.js.map +0 -1
- package/dist/chunk-NEO2HN2N.js +0 -326
- package/dist/chunk-NEO2HN2N.js.map +0 -1
- package/dist/chunk-O4O6JOGD.js.map +0 -1
- package/dist/chunk-PHOWMWFJ.js.map +0 -1
- package/dist/chunk-PTXHJLAS.js.map +0 -1
- package/dist/chunk-QSPH4F56.js.map +0 -1
- package/dist/chunk-RXCDT55X.js.map +0 -1
- package/dist/chunk-SIREOHLW.js +0 -233
- package/dist/chunk-SIREOHLW.js.map +0 -1
- package/dist/chunk-VCU7OMXV.js.map +0 -1
- package/dist/chunk-ZVEDBFTM.js.map +0 -1
- package/dist/cli-EQG4KETY.js.map +0 -1
- package/dist/github-NIRLMJ65.js +0 -27
- package/dist/json-EJTB7XYG.js +0 -34
- package/dist/list-6XVIW3RW.js +0 -33
- package/dist/pretty-SUKMF6AB.js +0 -35
- /package/dist/{batch-TBQBH6XQ.js.map → batch-C534YIAU.js.map} +0 -0
- /package/dist/{build-S3JQMDFX.js.map → build-SVKT7QFU.js.map} +0 -0
- /package/dist/{calibrate-KLN22IGS.js.map → calibrate-AL3MH7TY.js.map} +0 -0
- /package/dist/{capture-JS3ICXE7.js.map → capture-2F7B4DAD.js.map} +0 -0
- /package/dist/{check-6D2JCIMD.js.map → check-BI7OGIVE.js.map} +0 -0
- /package/dist/{check-PDXYA6XH.js.map → check-JZINDP3F.js.map} +0 -0
- /package/dist/{check-2EAR4ZW3.js.map → check-LKPQPQWJ.js.map} +0 -0
- /package/dist/{check-RNAB7X74.js.map → check-OPUMZEVK.js.map} +0 -0
- /package/dist/{check-WS2USSUD.js.map → check-OW7UD73D.js.map} +0 -0
- /package/dist/{chunk-JKH2LV5D.js.map → chunk-22WGKOQ7.js.map} +0 -0
- /package/dist/{chunk-IGAZWY2W.js.map → chunk-2HOWRAWK.js.map} +0 -0
- /package/dist/{chunk-KZ7534CD.js.map → chunk-2NGFDLIM.js.map} +0 -0
- /package/dist/{chunk-SOW6SVAM.js.map → chunk-2YKUSTHS.js.map} +0 -0
- /package/dist/{chunk-DQO44Y5G.js.map → chunk-3SFAB75L.js.map} +0 -0
- /package/dist/{chunk-U2CE55YV.js.map → chunk-5UJKXOAD.js.map} +0 -0
- /package/dist/{chunk-6D7FCU4E.js.map → chunk-762MM6NA.js.map} +0 -0
- /package/dist/{chunk-ZEKQRBXO.js.map → chunk-A4QNKEX4.js.map} +0 -0
- /package/dist/{chunk-SX626JUF.js.map → chunk-APAF4VWW.js.map} +0 -0
- /package/dist/{chunk-DTSWP5FC.js.map → chunk-BHGFLRXM.js.map} +0 -0
- /package/dist/{chunk-PGDUVYTF.js.map → chunk-BJUEOC4G.js.map} +0 -0
- /package/dist/{chunk-5MJE5KMY.js.map → chunk-BKY6GAFA.js.map} +0 -0
- /package/dist/{chunk-ITA7V5Y2.js.map → chunk-BLXRIAV2.js.map} +0 -0
- /package/dist/{chunk-SFSALDIR.js.map → chunk-BXCVOHEX.js.map} +0 -0
- /package/dist/{chunk-FRM62BEN.js.map → chunk-CZIO37J5.js.map} +0 -0
- /package/dist/{chunk-SFTWEGUD.js.map → chunk-D4QHRVDJ.js.map} +0 -0
- /package/dist/{chunk-6VGWLCYT.js.map → chunk-D5GBYKDU.js.map} +0 -0
- /package/dist/{chunk-GVOI7SCF.js.map → chunk-DMVBIIP3.js.map} +0 -0
- /package/dist/{chunk-O26NQ7KT.js.map → chunk-E23KWEPL.js.map} +0 -0
- /package/dist/{chunk-NDQA4VYK.js.map → chunk-E7OG5F6S.js.map} +0 -0
- /package/dist/{chunk-JNMY7KZG.js.map → chunk-G5I2JTDK.js.map} +0 -0
- /package/dist/{chunk-HSC5G3FW.js.map → chunk-HHJ2HFPP.js.map} +0 -0
- /package/dist/{chunk-HZWLHSZG.js.map → chunk-IN5T22FP.js.map} +0 -0
- /package/dist/{chunk-FERFWKZM.js.map → chunk-IOJD2RFG.js.map} +0 -0
- /package/dist/{chunk-GCF7STEA.js.map → chunk-JUUCCML3.js.map} +0 -0
- /package/dist/{chunk-3OXBZSDN.js.map → chunk-KBSTXL6L.js.map} +0 -0
- /package/dist/{chunk-SRTBHEUM.js.map → chunk-KCWNJMSS.js.map} +0 -0
- /package/dist/{chunk-2XRSQXGZ.js.map → chunk-KQDRO6N6.js.map} +0 -0
- /package/dist/{chunk-QSY5YPM4.js.map → chunk-MTCOBRCX.js.map} +0 -0
- /package/dist/{chunk-RGZBROMW.js.map → chunk-OWJLB2AF.js.map} +0 -0
- /package/dist/{chunk-QA7AXRGH.js.map → chunk-P7HAXMFN.js.map} +0 -0
- /package/dist/{chunk-GXDVERLV.js.map → chunk-PACZEDOH.js.map} +0 -0
- /package/dist/{chunk-UKSXQHSE.js.map → chunk-Q76T6Y6X.js.map} +0 -0
- /package/dist/{chunk-SGI3WPYK.js.map → chunk-R2CR62JV.js.map} +0 -0
- /package/dist/{chunk-MLY65CQE.js.map → chunk-RKACUTY5.js.map} +0 -0
- /package/dist/{chunk-EBYLQE7P.js.map → chunk-RWXR3GJI.js.map} +0 -0
- /package/dist/{chunk-JOZVVIVD.js.map → chunk-S5G6T4VC.js.map} +0 -0
- /package/dist/{chunk-GL2HXZVX.js.map → chunk-TFVNEPMF.js.map} +0 -0
- /package/dist/{chunk-I62V2ZAJ.js.map → chunk-U4OJ7U45.js.map} +0 -0
- /package/dist/{chunk-QWCP7UMG.js.map → chunk-V2XJJEEF.js.map} +0 -0
- /package/dist/{chunk-ZRMA5U53.js.map → chunk-WHVFHBL3.js.map} +0 -0
- /package/dist/{chunk-IYRGV2BC.js.map → chunk-XBJKYXOR.js.map} +0 -0
- /package/dist/{chunk-ZBE735BH.js.map → chunk-XI3BNZG4.js.map} +0 -0
- /package/dist/{chunk-Z6FATXBE.js.map → chunk-YSZNJ2ID.js.map} +0 -0
- /package/dist/{cli-4HH6IY2L.js.map → cli-3PBRPPMQ.js.map} +0 -0
- /package/dist/{cli-GVHXRQAD.js.map → cli-6NKE6RMT.js.map} +0 -0
- /package/dist/{cli-T4NY2EGM.js.map → cli-77A46SB2.js.map} +0 -0
- /package/dist/{cli-5BFVL3DH.js.map → cli-FSDJY5OC.js.map} +0 -0
- /package/dist/{cli-L7H4C442.js.map → cli-JNYL6LB7.js.map} +0 -0
- /package/dist/{cli-HTAR3PWY.js.map → cli-K47XWDLJ.js.map} +0 -0
- /package/dist/{cli-ZPW5VIRA.js.map → cli-LP5OE3BL.js.map} +0 -0
- /package/dist/{cli-AR43H5BW.js.map → cli-MOKRUHZT.js.map} +0 -0
- /package/dist/{config-7I5CHHRZ.js.map → config-BMWDC66C.js.map} +0 -0
- /package/dist/{github-CMWG4QMI.js.map → github-6GYTPSGV.js.map} +0 -0
- /package/dist/{github-NIRLMJ65.js.map → github-DJOLVNDD.js.map} +0 -0
- /package/dist/{github-RIU47U73.js.map → github-ZF2TQ3RP.js.map} +0 -0
- /package/dist/{json-EJTB7XYG.js.map → json-Y7625EFE.js.map} +0 -0
- /package/dist/{json-KSBVGZUX.js.map → json-YIK72XAL.js.map} +0 -0
- /package/dist/{labels-VNKACCAG.js.map → labels-X633ZPK7.js.map} +0 -0
- /package/dist/{lint-75BD6L5T.js.map → lint-RF3B55W7.js.map} +0 -0
- /package/dist/{list-6XVIW3RW.js.map → list-5DW4QZ7P.js.map} +0 -0
- /package/dist/{list-MH54XU7E.js.map → list-7CHWJ633.js.map} +0 -0
- /package/dist/{list-PHNZAYIM.js.map → list-UNWG6NPD.js.map} +0 -0
- /package/dist/{page-5AJS7AEM.js.map → page-OMPEACUN.js.map} +0 -0
- /package/dist/{prepare-R63RJI6O.js.map → prepare-B4JVDVOV.js.map} +0 -0
- /package/dist/{pretty-DE4WXJFA.js.map → pretty-PPNHHOEN.js.map} +0 -0
- /package/dist/{pretty-E3DS32NZ.js.map → pretty-U7ATCFBN.js.map} +0 -0
- /package/dist/{pretty-SUKMF6AB.js.map → pretty-XGYQ25PH.js.map} +0 -0
- /package/dist/{reporters-DLMLFLKS.js.map → reporters-FAIEOTC4.js.map} +0 -0
- /package/dist/{reporters-V2PSDBVW.js.map → reporters-KE7AZR6C.js.map} +0 -0
- /package/dist/{run-QT2LVHRU.js.map → run-MHJ3AYKG.js.map} +0 -0
- /package/dist/{sarif-2ZKPRT42.js.map → sarif-DOGRSGTB.js.map} +0 -0
- /package/dist/{sarif-GKMUHCZB.js.map → sarif-MIEMQOIK.js.map} +0 -0
- /package/dist/{sarif-HUIRTPSL.js.map → sarif-RGRG7VFX.js.map} +0 -0
- /package/dist/{term-ZZWAVUW5.js.map → term-MDN3NJDW.js.map} +0 -0
- /package/dist/{validate-ZEUFF3BG.js.map → validate-QDYQ642J.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph/core/vector-index.ts","../src/graph/runtime/chunks.ts","../src/graph/runtime/graph.ts","../src/graph/runtime/vector.ts","../src/graph/runtime/trace.ts","../src/graph/runtime/entry.ts","../src/graph/runtime/lexical.ts","../src/graph/runtime/traverse.ts","../src/graph/runtime/retrieve.ts"],"sourcesContent":["/**\n * The vector sidecar (ADR 01020) — `graph/vectors.<lang>.bin`, embeddings for the\n * same text that language's lexical index covers (ADR 01038).\n *\n * Layout, fixed. The magic is four ASCII bytes in file order; every number\n * after it is little-endian:\n *\n * ```\n * 0 magic \"MGRV\" 4 bytes\n * 4 format version (u32) 4 bytes\n * 8 header length (u32) 4 bytes\n * 12 header JSON (UTF-8) headerLength bytes\n * . float32 payload count * dims * 4 bytes\n * ```\n *\n * The header names the model, dtype, dimensions, the node IRIs in payload order\n * (sorted), and a digest of the `search.json` the vectors were built from — so\n * the runtime can refuse to rank against vectors from a different model or a\n * stale corpus rather than returning quietly wrong results.\n *\n * Vectors are **L2-normalized at build time and stored as float32**. Normalizing\n * makes cosine collapse to a dot product at query time; float32 rather than int8\n * because int8 retains only ~91% of retrieval quality at 384 dimensions — see\n * ADR 01020, where that correction is recorded.\n *\n * No `node:` imports: the encoder runs in the CLI, the decoder in the browser.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/**\n * \"MGRV\", manni graph vectors, as the bytes a hex dump shows first. It read\n * \"DKGV\" while the tool was dockg and \"MKGV\" while it was manni kg. Nothing was\n * published under either name, so no sidecar in the wild carries the old bytes.\n * Raw bytes rather than a little-endian u32: a u32 lands on disk reversed.\n */\nconst MAGIC = new Uint8Array([0x4d, 0x47, 0x52, 0x56]);\n// 2 since ADR 01038: the header names the language its vectors cover, so a\n// consumer cannot pair a sidecar with the wrong locale's index. A version-1\n// file is refused by `decodeVectorIndex` rather than read as if it had one.\nconst FORMAT_VERSION = 2;\nconst HEADER_OFFSET = 12;\n\nexport interface VectorIndexHeader {\n /** Embedding model id, e.g. an HF repo path. */\n model: string;\n /** Model-weight quantization the vectors were produced under. */\n dtype: string;\n /** Vector dimensions. Never assumed — always read from here. */\n dims: number;\n /** Number of vectors; equals `ids.length`. */\n count: number;\n /** Node IRIs, sorted, in payload order. */\n ids: string[];\n /** Digest of the `search.<lang>.json` these were built from (staleness detection). */\n source: string;\n /**\n * BCP-47 tag of the index these cover, or `und` (ADR 01038). Recorded so a\n * host that fetched the wrong pair is refused rather than ranked against a\n * model that never saw the language.\n */\n language: string;\n}\n\nexport interface VectorIndexDoc {\n header: VectorIndexHeader;\n /** `count * dims` floats, L2-normalized, row-major in `ids` order. */\n vectors: Float32Array;\n}\n\n/** Thrown for malformed input so callers can map it to an exit code / refusal. */\nexport class VectorIndexError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexError\";\n }\n}\n\n/**\n * L2-normalize a vector in place and return it. A zero vector is left alone —\n * dividing by its norm would produce NaNs that silently poison every later dot\n * product.\n */\nexport function normalize(vector: Float32Array): Float32Array {\n let sum = 0;\n // Iterating rather than indexing: every element is an element, which is what\n // the assertions here used to say.\n for (const value of vector) sum += value * value;\n if (sum === 0) return vector;\n const inv = 1 / Math.sqrt(sum);\n // `set(map(…))` scales every element in place with the same per-element\n // float32 rounding the indexed loop had, and without an index to assert.\n vector.set(vector.map((value) => value * inv));\n return vector;\n}\n\n/**\n * Encode entries into the sidecar. Entries are sorted by IRI first, so the bytes\n * depend on the set of entries and not on the order they were produced in.\n */\nexport function encodeVectorIndex(\n entries: Array<{ id: string; vector: Float32Array }>,\n meta: { model: string; dtype: string; source: string; language: string },\n): Uint8Array {\n const sorted = [...entries].sort((a, b) => byCodeUnit(a.id, b.id));\n const dims = sorted[0]?.vector.length ?? 0;\n for (const entry of sorted) {\n if (entry.vector.length !== dims) {\n throw new VectorIndexError(\n `Inconsistent vector dimensions: ${entry.id} has ${entry.vector.length}, expected ${dims}.`,\n );\n }\n }\n\n const header: VectorIndexHeader = {\n model: meta.model,\n dtype: meta.dtype,\n dims,\n count: sorted.length,\n ids: sorted.map((e) => e.id),\n source: meta.source,\n language: meta.language,\n };\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n\n const payloadBytes = sorted.length * dims * 4;\n const out = new Uint8Array(HEADER_OFFSET + headerBytes.length + payloadBytes);\n const view = new DataView(out.buffer);\n out.set(MAGIC, 0);\n view.setUint32(4, FORMAT_VERSION, true);\n view.setUint32(8, headerBytes.length, true);\n out.set(headerBytes, HEADER_OFFSET);\n\n let offset = HEADER_OFFSET + headerBytes.length;\n for (const entry of sorted) {\n // Normalize a copy: the caller's array is not ours to mutate.\n const vector = normalize(Float32Array.from(entry.vector));\n // Exactly `dims` elements: the loop above rejected any entry of another\n // length, so iterating the vector is the same walk without the index.\n for (const value of vector) {\n view.setFloat32(offset, value, true);\n offset += 4;\n }\n }\n return out;\n}\n\n/** Decode a sidecar, rejecting anything malformed rather than mis-reading it. */\nexport function decodeVectorIndex(bytes: Uint8Array): VectorIndexDoc {\n if (bytes.length < HEADER_OFFSET) {\n throw new VectorIndexError(\"Not a manni graph vector index: file is too short.\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (!MAGIC.every((byte, i) => bytes[i] === byte)) {\n throw new VectorIndexError(\n \"Not a manni graph vector index: bad magic — is this the right file?\",\n );\n }\n const version = view.getUint32(4, true);\n if (version !== FORMAT_VERSION) {\n throw new VectorIndexError(\n `Unsupported vector index version ${version} (this build reads ${FORMAT_VERSION}) — re-run \\`manni graph embed\\`.`,\n );\n }\n\n const headerLength = view.getUint32(8, true);\n if (HEADER_OFFSET + headerLength > bytes.length) {\n throw new VectorIndexError(\"Vector index is truncated: header overruns.\");\n }\n\n let header: VectorIndexHeader;\n try {\n header = JSON.parse(\n new TextDecoder().decode(\n bytes.subarray(HEADER_OFFSET, HEADER_OFFSET + headerLength),\n ),\n ) as VectorIndexHeader;\n } catch {\n throw new VectorIndexError(\"Vector index header is not valid JSON.\");\n }\n if (\n !Array.isArray(header.ids) ||\n typeof header.dims !== \"number\" ||\n header.ids.length !== header.count\n ) {\n throw new VectorIndexError(\"Vector index header is malformed.\");\n }\n\n const start = HEADER_OFFSET + headerLength;\n const expected = header.count * header.dims * 4;\n if (bytes.length - start !== expected) {\n throw new VectorIndexError(\n `Vector index is truncated: expected ${expected} payload bytes, found ${bytes.length - start}.`,\n );\n }\n\n // Copy rather than aliasing: `bytes` may be a view into a larger buffer whose\n // byteOffset is not 4-aligned, which Float32Array construction rejects.\n const vectors = new Float32Array(header.count * header.dims);\n for (let i = 0; i < vectors.length; i++) {\n vectors[i] = view.getFloat32(start + i * 4, true);\n }\n return { header, vectors };\n}\n","/**\n * The chunk artifact's shapes (proposal 0090): `chunks.json`, the manifest,\n * and one `chunks.<tag>.jsonl` row per servable passage, each carrying its\n * provenance record. `manni graph export chunks` writes them on the Node side;\n * every host reads them. Types only, so the runtime bundle stays\n * platform-neutral.\n */\n\n/** What a pin's finding says: cite's rule, at the severity `cite.severity` resolves. */\nexport interface PinFinding {\n rule: string;\n severity: \"notice\" | \"warning\" | \"error\";\n}\n\n/** One citation pin whose claim overlaps the passage. */\nexport interface PinItem {\n /** The citation's `id`, when it has one. */\n id: string | null;\n /** The body lines the claim occupies now: `N` or `N-M`. */\n claim: string;\n /** `path:lines` as the entry spells it; an encrypted path stays its token. */\n source: string;\n /** The commit the source end was recorded at, as recorded, or `null`. */\n commit: string | null;\n /** Empty means current. */\n findings: PinFinding[];\n /** The entry's `last-verified` as written, or `null`. */\n lastVerified: string | null;\n /** The entry's `verified-by` entries, or `[]`. */\n verifiedBy: unknown[];\n}\n\nexport interface PinSummary {\n total: number;\n current: number;\n notice: number;\n warning: number;\n error: number;\n items: PinItem[];\n}\n\n/**\n * A merge-safe date (proposals 0069, 0072): the derived UTC day, and whether\n * the page names it. `stamp` is `null` exactly when `day` is: with no derived\n * day there is nothing to compare the page against.\n */\nexport interface DerivedDate {\n day: string | null;\n stamp: \"current\" | \"stale\" | \"absent\" | null;\n}\n\nexport interface ProvenanceDates {\n created: DerivedDate;\n lastUpdated: DerivedDate;\n /** The page's `last-verified` as written, or `null`. */\n lastVerified: string | null;\n /** The page's `verified-by` entries, or `[]`. */\n verifiedBy: unknown[];\n}\n\nexport interface EvalItem {\n name: string;\n suite: string;\n grader: string;\n outcome: \"pass\" | \"fail\" | \"needs-review\" | \"skipped\" | \"error\";\n confidence?: number;\n}\n\nexport interface ProvenanceEvals {\n /** `sha256-<64 hex>` of the report the verdicts came from. */\n report: string;\n /** Whether the page still has the bytes the verdicts judged. */\n current: boolean;\n pass: number;\n fail: number;\n needsReview: number;\n skipped: number;\n error: number;\n items: EvalItem[];\n}\n\n/** A statement (proposal 0099) anchored inside the passage: on a block, or on a section's heading. */\nexport interface PassageStatement {\n /** Body lines, `N-M`. */\n lines: string;\n status: \"current\" | \"changed\" | \"unpinned\";\n /** Its delivered fields. */\n data: Record<string, unknown>;\n}\n\n/** The proof one served passage carries. Self-contained: copied out alone, it still says what it describes. */\nexport interface ProvenanceRecord {\n node: string;\n page: string;\n lines: string;\n /** The docs commit, or `null` outside git. */\n commit: string | null;\n worktree: \"clean\" | \"modified\" | null;\n pins: PinSummary;\n dates: ProvenanceDates;\n /** `null` when no docevals report was given. */\n evals: ProvenanceEvals | null;\n statements: PassageStatement[];\n}\n\n/** One line of `chunks.<tag>.jsonl`. */\nexport interface ChunkRow {\n /** The graph node IRI. */\n id: string;\n /** The digest of the graph the row was built from. */\n graph: string;\n page: string;\n /** Body lines, `N-M`. */\n lines: string;\n language: string;\n title: string;\n text: string;\n /** Present when the manifest names a model for the row's language. */\n vector?: number[];\n /** The page's delivered fields, overlaid by its heading statements down to this section. */\n metadata: Record<string, unknown>;\n provenance: ProvenanceRecord;\n}\n\nexport type WithholdReason = \"drifted\" | \"failing\";\n\n/** `chunks.json`. Keys are sorted, and nothing in it reads the wall clock. */\nexport interface ChunksManifest {\n format: \"manni-graph-chunks\";\n version: 1;\n /** `sha256-<64 hex>` of `graphFile`. */\n graph: string;\n graphFile: string;\n searchIndex: string;\n commit: string | null;\n worktree: \"clean\" | \"modified\" | null;\n retrieve: { seeds: number; depth: number; maxChars: number; withhold: WithholdReason[] };\n evals: { report: string; digest: string } | null;\n /** Each language's rows, and the model its vector sidecar was embedded with, or `null` without one. */\n languages: Record<string, { file: string; rows: number; model: { id: string; dimensions: number } | null }>;\n pages: Record<string, { metadata: Record<string, unknown> }>;\n withheld: { id: string; page: string; because: WithholdReason[] }[];\n}\n\n/** A cite line spec, `N` or `N-M`, as a span; `undefined` when it is not one or runs backwards. */\nexport function range(spec: string): { start: number; end: number } | undefined {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(spec.trim());\n if (m?.[1] === undefined) return undefined;\n const start = Number(m[1]);\n const end = m[2] === undefined ? start : Number(m[2]);\n return end < start ? undefined : { start, end };\n}\n","/**\n * `GraphIndex` — the browser-native in-memory graph (ADR 01018).\n *\n * Built from `graph.jsonld` (the Phase 6 export) with **no RDF parser**: that\n * artifact is plain `JSON.parse`-able, deterministically sorted, and free of\n * blank nodes, so a `Map`-based adjacency index is all the runtime needs. Node\n * callers can also build from quads (`fromQuads`) so the CLI can read Turtle.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies, no I/O — the\n * caller supplies the bytes. Type-only imports are erased at build time.\n *\n * Every accessor returns deterministically sorted results, so traversal order\n * (and therefore the trace) is byte-stable for a given graph.\n */\nimport type { Quad } from \"../core/derive.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { RDF_TYPE } from \"../core/vocab.js\";\n\n/** An object value: an IRI reference or a literal. */\nexport type Value =\n | { kind: \"iri\"; value: string }\n | { kind: \"literal\"; value: string; datatype?: string; language?: string };\n\nexport interface GraphNode {\n id: string;\n /** Full class IRIs, sorted. */\n types: string[];\n /** Full predicate IRI → values, in insertion-normalized sorted order. */\n props: Map<string, Value[]>;\n}\n\n/** The parsed shape of a `graph.jsonld` document. */\ninterface JsonLdDoc {\n \"@context\"?: Record<string, string>;\n \"@graph\"?: unknown[];\n}\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\n\nfunction compareValues(a: Value, b: Value): number {\n if (a.kind !== b.kind) return a.kind === \"iri\" ? -1 : 1;\n const v = byCodeUnit(a.value, b.value);\n if (v !== 0) return v;\n const da = a.kind === \"literal\" ? (a.datatype ?? \"\") : \"\";\n const db = b.kind === \"literal\" ? (b.datatype ?? \"\") : \"\";\n const la = a.kind === \"literal\" ? (a.language ?? \"\") : \"\";\n const lb = b.kind === \"literal\" ? (b.language ?? \"\") : \"\";\n return byCodeUnit(da, db) || byCodeUnit(la, lb);\n}\n\nexport class GraphIndex {\n private readonly nodes = new Map<string, GraphNode>();\n /** subject → predicate → object IRIs (sorted). */\n private readonly outbound = new Map<string, Map<string, string[]>>();\n /** object → predicate → subject IRIs (sorted). */\n private readonly inbound = new Map<string, Map<string, string[]>>();\n /** class IRI → instance IRIs (sorted). */\n private readonly byType = new Map<string, string[]>();\n /** prefix → namespace, from the artifact's own `@context`. */\n readonly context: Record<string, string>;\n\n private constructor(context: Record<string, string>) {\n this.context = context;\n }\n\n /**\n * Build from a `graph.jsonld` document — a JSON string or the parsed object.\n * CURIE keys and `@type` values are expanded using the document's own\n * `@context`, so the index is self-describing.\n */\n static fromJsonLd(input: string | object): GraphIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as JsonLdDoc) : input\n ) as JsonLdDoc;\n const context = doc[\"@context\"] ?? {};\n const index = new GraphIndex({ ...context });\n for (const raw of doc[\"@graph\"] ?? []) {\n index.addJsonLdNode(raw as Record<string, unknown>);\n }\n index.finalize();\n return index;\n }\n\n /** Build from dockg's internal quad shape (the Node/CLI path). */\n static fromQuads(quads: Quad[], context: Record<string, string> = {}) {\n const index = new GraphIndex({ ...context });\n for (const q of quads) {\n const o = q.o;\n const value: Value =\n o.kind === \"iri\"\n ? { kind: \"iri\", value: o.value }\n : o.language\n ? { kind: \"literal\", value: o.value, language: o.language }\n : o.datatype && o.datatype !== XSD_STRING\n ? { kind: \"literal\", value: o.value, datatype: o.datatype }\n : { kind: \"literal\", value: o.value };\n index.addTriple(q.s, q.p, value);\n }\n index.finalize();\n return index;\n }\n\n /** Expand a CURIE (`dcterms:title`) to a full IRI using `@context`. */\n expand(term: string): string {\n const colon = term.indexOf(\":\");\n if (colon <= 0) return term;\n const ns = this.context[term.slice(0, colon)];\n return ns ? `${ns}${term.slice(colon + 1)}` : term;\n }\n\n /** Compact a full IRI to a CURIE when a context namespace matches. */\n compact(iri: string): string {\n let best = iri;\n let bestNs = \"\";\n for (const [prefix, ns] of Object.entries(this.context)) {\n if (\n iri.startsWith(ns) &&\n iri.length > ns.length &&\n ns.length > bestNs.length\n ) {\n best = `${prefix}:${iri.slice(ns.length)}`;\n bestNs = ns;\n }\n }\n return best;\n }\n\n private addJsonLdNode(raw: Record<string, unknown>): void {\n const id = typeof raw[\"@id\"] === \"string\" ? this.expand(raw[\"@id\"]) : \"\";\n if (!id) return;\n this.ensureNode(id);\n\n const rawTypes = raw[\"@type\"];\n for (const t of toArray(rawTypes)) {\n if (typeof t === \"string\") {\n this.addTriple(id, RDF_TYPE, { kind: \"iri\", value: this.expand(t) });\n }\n }\n\n for (const [key, rawValue] of Object.entries(raw)) {\n if (key === \"@id\" || key === \"@type\") continue;\n const predicate = this.expand(key);\n for (const v of toArray(rawValue)) {\n const value = this.toValue(v);\n if (value) this.addTriple(id, predicate, value);\n }\n }\n }\n\n private toValue(v: unknown): Value | undefined {\n if (typeof v === \"string\") return { kind: \"literal\", value: v };\n if (typeof v === \"number\" || typeof v === \"boolean\") {\n return { kind: \"literal\", value: String(v) };\n }\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (typeof o[\"@id\"] === \"string\") {\n return { kind: \"iri\", value: this.expand(o[\"@id\"]) };\n }\n if (o[\"@value\"] !== undefined) {\n const raw = o[\"@value\"];\n // JSON.stringify spells a number or boolean the way String() would,\n // and gives an object a lexical form instead of \"[object Object]\".\n const lexical = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n if (typeof o[\"@language\"] === \"string\") {\n return { kind: \"literal\", value: lexical, language: o[\"@language\"] };\n }\n const dt =\n typeof o[\"@type\"] === \"string\" ? this.expand(o[\"@type\"]) : undefined;\n return dt && dt !== XSD_STRING\n ? { kind: \"literal\", value: lexical, datatype: dt }\n : { kind: \"literal\", value: lexical };\n }\n }\n return undefined;\n }\n\n private ensureNode(id: string): GraphNode {\n let node = this.nodes.get(id);\n if (!node) {\n node = { id, types: [], props: new Map() };\n this.nodes.set(id, node);\n }\n return node;\n }\n\n private addTriple(s: string, p: string, o: Value): void {\n const node = this.ensureNode(s);\n let values = node.props.get(p);\n if (!values) {\n values = [];\n node.props.set(p, values);\n }\n values.push(o);\n\n if (p === RDF_TYPE && o.kind === \"iri\") {\n node.types.push(o.value);\n const instances = this.byType.get(o.value);\n if (instances) instances.push(s);\n else this.byType.set(o.value, [s]);\n }\n\n if (o.kind === \"iri\") {\n addEdge(this.outbound, s, p, o.value);\n addEdge(this.inbound, o.value, p, s);\n // Referenced-only IRIs still resolve as (empty) nodes.\n this.ensureNode(o.value);\n }\n }\n\n /** Sort every collection so traversal order is deterministic. */\n private finalize(): void {\n for (const node of this.nodes.values()) {\n node.types.sort(byCodeUnit);\n for (const values of node.props.values()) values.sort(compareValues);\n }\n for (const instances of this.byType.values()) instances.sort(byCodeUnit);\n for (const map of [this.outbound, this.inbound]) {\n for (const preds of map.values()) {\n for (const targets of preds.values()) targets.sort(byCodeUnit);\n }\n }\n }\n\n /** Every node IRI, sorted. */\n ids(): string[] {\n return [...this.nodes.keys()].sort(byCodeUnit);\n }\n\n size(): number {\n return this.nodes.size;\n }\n\n node(iri: string): GraphNode | undefined {\n return this.nodes.get(iri);\n }\n\n has(iri: string): boolean {\n return this.nodes.has(iri);\n }\n\n /** Class IRIs of a node, sorted. */\n types(iri: string): string[] {\n return this.nodes.get(iri)?.types ?? [];\n }\n\n /** Instances of a class, sorted. */\n instancesOf(classIri: string): string[] {\n return this.byType.get(classIri) ?? [];\n }\n\n /** All values for a predicate, sorted. */\n values(iri: string, predicate: string): Value[] {\n return this.nodes.get(iri)?.props.get(predicate) ?? [];\n }\n\n /** Literal lexical forms for a predicate, sorted. */\n literals(iri: string, predicate: string): string[] {\n return this.values(iri, predicate)\n .filter((v) => v.kind === \"literal\")\n .map((v) => v.value);\n }\n\n /** The first literal for a predicate, if any. */\n literal(iri: string, predicate: string): string | undefined {\n return this.literals(iri, predicate)[0];\n }\n\n /** Outbound IRI targets: all predicates, or one. Sorted. */\n out(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.outbound, iri, predicate);\n }\n\n /** Inbound IRI sources (who points at this node). Sorted. */\n in(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.inbound, iri, predicate);\n }\n}\n\nfunction addEdge(\n map: Map<string, Map<string, string[]>>,\n key: string,\n predicate: string,\n target: string,\n): void {\n let preds = map.get(key);\n if (!preds) {\n preds = new Map();\n map.set(key, preds);\n }\n const targets = preds.get(predicate);\n if (targets) targets.push(target);\n else preds.set(predicate, [target]);\n}\n\nfunction edges(\n map: Map<string, Map<string, string[]>>,\n iri: string,\n predicate?: string,\n): Array<{ predicate: string; target: string }> {\n const preds = map.get(iri);\n if (!preds) return [];\n const out: Array<{ predicate: string; target: string }> = [];\n const keys = predicate ? [predicate] : [...preds.keys()].sort(byCodeUnit);\n for (const p of keys) {\n for (const target of preds.get(p) ?? []) out.push({ predicate: p, target });\n }\n return out;\n}\n\nfunction toArray(v: unknown): unknown[] {\n if (v === undefined || v === null) return [];\n return Array.isArray(v) ? v : [v];\n}\n","/**\n * Vector search (ADR 01020) — semantic entry, and a standalone capability.\n *\n * `search()` is usable on its own: give it a query vector and it ranks nodes by\n * meaning, with no lexical index and no graph involved. `findEntry` composes it\n * with the lexical leg, but does not own it.\n *\n * Hand-written rather than taken from a library, on evidence: the dedicated\n * browser vector libraries are 3 years stale, no maintained micro-package does\n * cosine top-k over typed arrays (the popular one throws on `Float32Array`), and\n * the engines that do exist run this same brute-force loop internally. See ADR\n * 01020 for the full survey.\n *\n * Vectors are L2-normalized at build time, so cosine similarity **is** the dot\n * product — no norms, no division, at query time. The loop is indexed rather\n * than `.reduce()`, which measures ~13× slower on typed arrays.\n *\n * Platform-neutral: no `node:` imports, no dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport {\n decodeVectorIndex,\n normalize,\n type VectorIndexHeader,\n} from \"../core/vector-index.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface VectorSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n /**\n * Drop candidates scoring below this. Default 0 — every model has its own\n * useful range, so dockg does not impose a threshold the user did not choose.\n */\n minScore?: number;\n}\n\n/** Why a vector index cannot be used with the embedder or corpus at hand. */\nexport interface VectorMismatch {\n reason: \"model\" | \"dtype\" | \"dims\" | \"stale-source\";\n detail: string;\n}\n\n/**\n * Thrown when a query would be ranked against vectors it cannot be compared to.\n *\n * A distinct type so hosts can catch exactly this — and so it cannot be mistaken\n * for \"no results\". Ranking on regardless is the silent-wrong-answer failure\n * ADR 01020 exists to prevent, so this is loud by design.\n */\nexport class VectorMismatchError extends Error {\n readonly reason: VectorMismatch[\"reason\"];\n constructor(mismatch: VectorMismatch) {\n super(mismatch.detail);\n this.name = \"VectorMismatchError\";\n this.reason = mismatch.reason;\n }\n}\n\n/**\n * The digest `manni graph embed` records as a sidecar's `source`, computed the same\n * way in a browser — SHA-256 over the **raw bytes of `search.json` exactly as\n * fetched**, hex, prefixed `sha256:`.\n *\n * Exists so a host can pass `source` to `findEntry` and get the staleness half\n * of the refusal (ADR 01020) without reconstructing the recipe. Re-serializing\n * the parsed JSON would change the bytes and so the digest — pass the response\n * text, not `JSON.stringify(doc)`.\n *\n * Uses Web Crypto, which is platform-neutral: browsers and Node 18+ both have\n * it on `globalThis`.\n */\nexport async function searchIndexDigest(raw: string): Promise<string> {\n // `lib.dom` and @types/node both declare `globalThis.crypto.subtle` as\n // always present. A page served over plain HTTP gets `crypto` without\n // `subtle`, which is the case this throw exists for: the declaration is the\n // optimistic one, and reading through `Partial` is how the guard gets to say\n // so instead of reading as a test that cannot fail.\n const webCrypto = globalThis.crypto as\n | Partial<typeof globalThis.crypto>\n | undefined;\n const subtle = webCrypto?.subtle;\n if (!subtle) {\n throw new Error(\n \"searchIndexDigest needs Web Crypto (globalThis.crypto.subtle), which is unavailable here — a page served over plain HTTP does not get it.\",\n );\n }\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(raw));\n const hex = [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nexport interface VectorIndex {\n /**\n * Rank nodes against a query vector. The vector is normalized here, so\n * callers need not — an unnormalized query would otherwise scale every score.\n */\n search(query: Float32Array, options?: VectorSearchOptions): EntryCandidate[];\n /**\n * Check this index against the embedder and corpus in play. Returns the\n * mismatch, or undefined when they agree. Ranking against vectors from a\n * different model compares outputs of two different functions (ADR 01020), so\n * callers should refuse rather than proceed.\n */\n check(expected: {\n model?: string;\n dtype?: string;\n dims?: number;\n source?: string;\n }): VectorMismatch | undefined;\n readonly model: string;\n /**\n * Weight quantization the corpus vectors were produced under. The query side\n * must embed at the *same* dtype — q8 and fp32 weights are different\n * functions, so mixing them compares incomparable vectors (ADR 01020).\n */\n readonly dtype: string;\n readonly dims: number;\n readonly source: string;\n size(): number;\n /** The IRI at a payload row, for callers walking the index directly. */\n idAt(row: number): string | undefined;\n}\n\n/** Build a vector index from encoded sidecar bytes. */\nexport function createVectorIndex(bytes: Uint8Array): VectorIndex {\n const { header, vectors } = decodeVectorIndex(bytes);\n const { dims, ids } = header;\n\n return {\n model: header.model,\n dtype: header.dtype,\n dims,\n source: header.source,\n size: () => ids.length,\n idAt: (row) => ids[row],\n\n check(expected) {\n if (expected.model !== undefined && expected.model !== header.model) {\n return {\n reason: \"model\",\n detail: `Vector index was built with ${header.model}, but the embedder is ${expected.model}. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dtype !== undefined && expected.dtype !== header.dtype) {\n return {\n reason: \"dtype\",\n detail: `Vector index was built at dtype ${header.dtype}, but the embedder is at ${expected.dtype} — different weights are a different function. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dims !== undefined && expected.dims !== dims) {\n return {\n reason: \"dims\",\n detail: `Vector index has ${dims} dimensions, but the embedder produces ${expected.dims}.`,\n };\n }\n if (expected.source !== undefined && expected.source !== header.source) {\n return {\n reason: \"stale-source\",\n detail:\n \"Vector index was built from a different search index — the corpus changed. Re-run `manni graph embed`.\",\n };\n }\n return undefined;\n },\n\n search(query, options = {}) {\n if (dims === 0 || ids.length === 0) return [];\n if (query.length !== dims) {\n // A silent zero-fill or truncate here would return confident nonsense.\n // Typed like every other mismatch so a caller (and the CLI's exit-code\n // mapping) handles it the same way rather than seeing a raw stack.\n throw new VectorMismatchError({\n reason: \"dims\",\n detail: `Query vector has ${query.length} dimensions, but the index has ${dims}.`,\n });\n }\n const limit = normalizeLimit(options.limit);\n if (limit === 0) return [];\n const minScore = options.minScore ?? 0;\n\n // Copy before normalizing: the caller's vector is not ours to mutate.\n const q = normalize(Float32Array.from(query));\n\n const scored: EntryCandidate[] = [];\n // `entries()` pairs each row with its IRI, so the id is proven present\n // by the iteration rather than asserted after an index.\n for (const [row, iri] of ids.entries()) {\n // The payload is `count × dims` floats, so this row is exactly these\n // `dims` of them — and `q` was checked to be `dims` long above. Both\n // walks are therefore in range; `?? 0` spells that a term outside the\n // row contributes nothing, which is what out of range means for a dot\n // product.\n const stored = vectors.subarray(row * dims, (row + 1) * dims);\n let score = 0;\n for (const [i, value] of q.entries()) score += value * (stored[i] ?? 0);\n if (score >= minScore) {\n scored.push({ iri, score, via: \"vector\" });\n }\n }\n\n scored.sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n return scored.slice(0, limit);\n },\n };\n}\n\n/**\n * A limit that is not a non-negative integer falls back to the documented\n * default — `slice(0, NaN)` is empty, which would report a confident \"no\n * results\" for a query that does match.\n */\nfunction normalizeLimit(limit: number | undefined): number {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit >= 0\n ? limit\n : 10;\n}\n\nexport type { VectorIndexHeader };\n","/**\n * Query trace — the explainability contract (ADR 01018). Every runtime stage\n * appends to a trace, and no API returns results without one: retrieval\n * provenance is part of the contract exactly as PROV provenance is part of the\n * build. The trace answers \"how and why did this result come back\": which nodes\n * were seeded, every hop walked, every node scope excluded (and by which rule),\n * and every content resolution attempted.\n *\n * Events are appended in traversal order, which is itself deterministic, so the\n * trace is byte-stable for a given graph + query.\n */\n\n/** How a seed was found. `hybrid` means several legs agreed on it. */\nexport type EntryVia = \"explicit\" | \"lexical\" | \"vector\" | \"hybrid\";\n\n/** A starting node, with the score/reason that made it a seed. */\nexport interface EntryCandidate {\n iri: string;\n /**\n * Relevance score: 1 for an explicitly requested seed, otherwise the fused\n * `rrfMerge` score. Note that fusion is **rank**-based, so a searched seed's\n * score reflects its position (1/(60 + rank)), not the engine's relevance —\n * it orders candidates but is not a magnitude to threshold on.\n */\n score: number;\n via: EntryVia;\n}\n\n/** One edge walked, in either direction. */\nexport interface Hop {\n from: string;\n predicate: string;\n to: string;\n /** Hops from the nearest seed (seeds are depth 0; their neighbors are 1). */\n depth: number;\n direction: \"out\" | \"in\";\n}\n\n/** A node the scope filter removed, and why. */\nexport interface ScopeExclusion {\n node: string;\n /**\n * The predicate that disqualified the node: a `graph:not*` IRI when an\n * explicit negative named the target, or the positive predicate (e.g.\n * `iirds:relates-to-product-variant`) when the node declared a scope set that\n * omits the target.\n */\n rule: string;\n /**\n * The filter target being applied — the variant or subject IRI the query\n * asked for. Under a `graph:not*` rule the node named this explicitly; under\n * a positive rule this is what the node's declared set was missing.\n */\n value: string;\n}\n\n/** One content-resolution attempt. */\nexport interface Resolution {\n iri: string;\n sourceUrl: string;\n ok: boolean;\n /** Present when `ok` is false. */\n error?: string;\n}\n\nexport interface QueryTrace {\n entry: EntryCandidate[];\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n}\n\nexport function createTrace(): QueryTrace {\n return { entry: [], hops: [], exclusions: [], resolutions: [] };\n}\n\n/**\n * Every node named anywhere in the trace as reached — seeds plus hop targets.\n * The trace-completeness contract: a traversal's results must be a subset of\n * this, so every returned node is explainable by recorded events.\n */\nexport function reachedNodes(trace: QueryTrace): Set<string> {\n const reached = new Set<string>();\n for (const e of trace.entry) reached.add(e.iri);\n for (const h of trace.hops) reached.add(h.to);\n return reached;\n}\n","/**\n * Entry-point finding (ADR 01019, extended by ADR 01020) — the stage that turns\n * a question into seed nodes for the walker.\n *\n * Two rankings now: lexical (BM25 over the search artifact) and, when the host\n * supplies an embedder, vector (cosine over the sidecar). `rrfMerge` fuses them.\n *\n * **Each leg is returned separately as well as fused.** A caller rendering a\n * search UI wants to show \"text matches\" and \"semantic matches\" as distinct\n * things, and either leg is usable on its own — `lexical.search` and\n * `vectors.search` are public and independent of this function.\n *\n * Every candidate is appended to the trace, so \"why did retrieval start here?\"\n * is answerable alongside \"why did it walk there?\" (ADR 01018 invariant 2).\n *\n * Platform-neutral: no `node:` imports.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { LexicalIndex } from \"./lexical.js\";\nimport { VectorMismatchError, type VectorIndex } from \"./vector.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type QueryTrace,\n} from \"./trace.js\";\n\n/**\n * Enough of an embedder to verify it against a vector index. Structural rather\n * than the `Embedder` interface itself, so the runtime stays independent of\n * `@hawkeyexl/manni/graph/embed` — any object with these three fields works.\n */\nexport interface QueryEmbedder {\n readonly model: string;\n readonly dtype: string;\n embed(text: string): Promise<Float32Array> | Float32Array;\n}\n\nexport interface FindEntryOptions {\n /** The lexical index to query. */\n lexical: LexicalIndex;\n /** The vector index. Without it (and an embedder), entry is lexical-only. */\n vectors?: VectorIndex;\n /**\n * The embedder for the query side. **Prefer this over `embedQuery`**: it\n * carries the model and dtype, so `findEntry` can verify they match the\n * vector index and refuse rather than rank against incomparable vectors.\n */\n embedder?: QueryEmbedder;\n /**\n * Embed the query with a bare function. An escape hatch for hosts wiring\n * their own model — but it carries no identity, so **the model/dtype match\n * cannot be verified**; only the dimension check inside `search` applies.\n * Prefer `embedder`.\n */\n embedQuery?: (query: string) => Promise<Float32Array> | Float32Array;\n /**\n * Digest of the `search.json` this caller loaded, from `searchIndexDigest`.\n * Supplied, a sidecar built from a *different* corpus is refused rather than\n * ranked — its IRIs may no longer exist, and it misses everything added\n * since. Omitted, that half of the check simply does not run: the runtime\n * cannot derive the digest, since it never sees the raw bytes.\n */\n source?: string;\n /** Maximum seeds to return. Default 10. */\n limit?: number;\n /** Append candidates here instead of starting a new trace. */\n trace?: QueryTrace;\n}\n\nexport interface EntryResult {\n /** The fused ranking — what seeds traversal. */\n candidates: EntryCandidate[];\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was supplied. */\n vector: EntryCandidate[];\n trace: QueryTrace;\n}\n\n/**\n * Reciprocal rank fusion over N ranked lists: score = Σ 1/(k + rank).\n *\n * Rank-based rather than score-based on purpose — lexical BM25 scores and\n * cosine similarities are not on a comparable scale, so fusing raw scores would\n * let whichever leg happens to produce bigger numbers dominate. `k = 60` is the\n * standard damping constant.\n *\n * Deterministic: input list order does not affect the result, and ties break by\n * IRI.\n */\nexport function rrfMerge(\n rankings: EntryCandidate[][],\n k = 60,\n): EntryCandidate[] {\n const fused = new Map<string, { score: number; vias: Set<EntryVia> }>();\n for (const ranking of rankings) {\n ranking.forEach((candidate, i) => {\n const current = fused.get(candidate.iri) ?? {\n score: 0,\n vias: new Set<EntryVia>(),\n };\n current.score += 1 / (k + i + 1);\n current.vias.add(candidate.via);\n fused.set(candidate.iri, current);\n });\n }\n\n return [...fused.entries()]\n .map(([iri, { score, vias }]) => {\n // One leg keeps its own provenance; several means the seed was fused.\n // Destructuring rather than `[...vias][0]!` so the single-leg case needs\n // no non-null assertion — an empty set simply falls through to \"hybrid\",\n // which is unreachable anyway (a set only exists once a leg added to it).\n const [only] = vias;\n return {\n iri,\n score,\n via: vias.size === 1 && only !== undefined ? only : \"hybrid\",\n };\n })\n .sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n}\n\n/**\n * Find seed nodes for a question, returning each ranking leg and their fusion.\n *\n * Async because embedding a query is: local models are a WASM forward pass.\n * Uniformly async rather than sync-when-lexical-only, so callers have one\n * contract to hold rather than a return type that changes with the options.\n *\n * The vector leg runs only when both a `vectors` index and an `embedQuery` are\n * supplied. Absent either, this is lexical entry exactly as Phase 8 shipped it —\n * additive, never a new failure mode (ADR 01009's degrade-don't-fail rule).\n */\nexport async function findEntry(\n query: string,\n options: FindEntryOptions,\n): Promise<EntryResult> {\n const trace = options.trace ?? createTrace();\n // `--limit abc` parses to NaN, and `slice(0, NaN)` is empty — a typo'd flag\n // would report a confident \"0 results\" for a query that does match. Anything\n // that is not a non-negative integer falls back to the documented default.\n const limit =\n typeof options.limit === \"number\" &&\n Number.isInteger(options.limit) &&\n options.limit >= 0\n ? options.limit\n : 10;\n\n const lexical = options.lexical.search(query, { limit });\n\n // Bound first: the closure then captures the embedder the test found, rather\n // than re-reading a property the type cannot know is still the same one.\n const embedder = options.embedder;\n const embed = embedder ? (q: string) => embedder.embed(q) : options.embedQuery;\n\n let vector: EntryCandidate[] = [];\n if (options.vectors && embed && query.trim() !== \"\") {\n // Verify *before* embedding. The refusal is enforced here, not only in the\n // CLI, because this is the browser-facing surface — and the whole reason\n // ADR 01020 exists is that the browser must embed with a function that\n // agrees with the one that embedded the corpus. Ranking a stale or\n // wrong-model index would be the silent wrong answer this design prevents.\n const mismatch = options.vectors.check({\n ...(options.embedder\n ? { model: options.embedder.model, dtype: options.embedder.dtype }\n : {}),\n // Staleness is checked whichever way the query is embedded — it is a\n // property of the corpus, not of the embedder, so even the unverified\n // `embedQuery` path gets it when the caller supplies a digest.\n ...(options.source === undefined ? {} : { source: options.source }),\n });\n if (mismatch) throw new VectorMismatchError(mismatch);\n const queryVector = await embed(query);\n vector = options.vectors.search(queryVector, { limit });\n }\n\n const rankings = vector.length > 0 ? [lexical, vector] : [lexical];\n const candidates = rrfMerge(rankings).slice(0, limit);\n\n for (const candidate of candidates) trace.entry.push(candidate);\n return { candidates, lexical, vector, trace };\n}\n","/**\n * Lexical entry (ADR 01019) — text query → ranked seed nodes.\n *\n * Loads the `search.json` artifact (produced by `manni graph export search`)\n * and scores it with MiniSearch. The artifact carries body text, which the graph\n * deliberately does not (ADR 01008), so a query can match what a document *says*\n * and not merely what it is titled.\n *\n * MiniSearch is this runtime's one production dependency; the bundle-purity gate\n * allow-lists exactly it. Two guards keep ranking a dockg contract rather than a\n * library's: ties are broken by IRI here (MiniSearch does not define tie order),\n * and the on-disk artifact format is ours, so upgrading MiniSearch can never\n * change a committed artifact.\n *\n * Platform-neutral: no `node:` imports.\n */\nimport MiniSearch from \"minisearch\";\nimport type { SearchEntry, SearchIndexDoc } from \"../core/search-index.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface LexicalSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n}\n\nexport interface LexicalIndex {\n /** Ranked candidates, best first, ties broken by IRI. */\n search(query: string, options?: LexicalSearchOptions): EntryCandidate[];\n /** Indexed entry count. */\n size(): number;\n /** The entry behind an IRI, for callers that want its title/type. */\n entry(iri: string): SearchEntry | undefined;\n}\n\n/**\n * Build a lexical index from the search artifact — a JSON string or the parsed\n * document.\n */\nexport function createLexicalIndex(\n input: string | SearchIndexDoc,\n): LexicalIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as SearchIndexDoc) : input\n ) as SearchIndexDoc | null;\n // Shape-check rather than trust: handed something that is valid JSON but not\n // a search artifact, MiniSearch's `addAll` throws \"documents is not\n // iterable\" from inside the library. An empty index is the honest answer.\n const entries = Array.isArray(doc?.entries) ? doc.entries : [];\n\n const mini = new MiniSearch<SearchEntry>({\n fields: [\"title\", \"labels\", \"description\", \"text\"],\n storeFields: [\"id\"],\n idField: \"id\",\n // Titles and labels are the strongest signal that a node *is* the subject;\n // body text is evidence it merely mentions it.\n searchOptions: {\n boost: { title: 3, labels: 2, description: 1.5 },\n prefix: true,\n fuzzy: 0.2,\n },\n });\n mini.addAll(entries);\n\n const byIri = new Map(entries.map((e) => [e.id, e]));\n\n return {\n size: () => entries.length,\n entry: (iri) => byIri.get(iri),\n search(query, options = {}) {\n const trimmed = query.trim();\n if (trimmed === \"\") return [];\n const hits = mini.search(trimmed);\n // MiniSearch does not define an order for equal scores; sort explicitly so\n // the same query against the same artifact always ranks identically.\n hits.sort((a, b) =>\n a.score === b.score\n ? byCodeUnit(String(a.id), String(b.id))\n : b.score - a.score,\n );\n return hits\n .slice(0, options.limit ?? 10)\n .map((h) => ({ iri: String(h.id), score: h.score, via: \"lexical\" }));\n },\n };\n}\n","/**\n * The deterministic walker (ADR 01018) — breadth-first traversal over a\n * `GraphIndex` with scope filtering, recording every hop and every exclusion\n * into a `QueryTrace`. This is the engine: generic RDF engines return bindings\n * without the path that produced them, and dockg's scope rules (ADR 01014)\n * are domain semantics no general engine knows.\n *\n * Determinism: neighbors come back sorted from the index, the frontier is\n * processed in (depth, IRI) order, and results are emitted in discovery order —\n * so the same graph + query always yields the same nodes *and* the same trace.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { NS, RDF_TYPE } from \"../core/vocab.js\";\nimport { canonicalLanguageTag } from \"../core/localizations.js\";\nimport {\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n GRAPH_NOT_SOFTWARE_SUBJECT,\n IIRDS_HAS_SUBJECT,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n SOFTWARE_SUBJECT_IRIS,\n} from \"../core/iirds.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport { createTrace, type QueryTrace, type ScopeExclusion } from \"./trace.js\";\n\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_REFERENCES = `${NS.dcterms}references`;\nconst DCTERMS_LANGUAGE = `${NS.dcterms}language`;\n\n/**\n * Block and verification nodes (proposal 0099) are graph data, not passages:\n * a walk never steps into one. `graph query` still sees them all.\n */\nconst STATEMENT_DATA = new Set([`${NS.graph}Block`, `${NS.graph}Verification`]);\n\nfunction isStatementData(graph: GraphIndex, iri: string): boolean {\n return graph.types(iri).some((t) => STATEMENT_DATA.has(t));\n}\n\n/** A section IRI's document, or the IRI itself when it has no fragment. */\nfunction documentOf(iri: string): string {\n const hash = iri.indexOf(\"#\");\n return hash === -1 ? iri : iri.slice(0, hash);\n}\n\nexport type Direction = \"out\" | \"in\" | \"both\";\n\nexport interface ScopeFilter {\n /** Product variant: an IRI, a `dcterms:title` (e.g. \"SP-X100\"), or a slug. */\n variant?: string;\n /** Software subject: an IRI or a `graph.about-product-aspect` value (e.g. \"architecture\"). */\n subject?: string;\n /**\n * BCP-47 tag (ADR 01037). Matched against `dcterms:language` after both are\n * canonicalized, since tags are case-insensitive. There is no fallback:\n * `de-AT` is not `de`, because relatedness between locales is an inference\n * and this runtime does not infer.\n */\n language?: string;\n}\n\nexport interface TraverseOptions extends ScopeFilter {\n /** Starting nodes (IRIs). */\n seeds: string[];\n /** Maximum hops from a seed. Default 1. */\n depth?: number;\n /** Restrict to these predicates (full IRIs). Default: every predicate. */\n predicates?: string[];\n /** Which edge directions to follow. Default \"out\". */\n direction?: Direction;\n /** Stop after this many nodes (seeds included). */\n limit?: number;\n /**\n * Follow `rdf:type` edges into class nodes. Default false, deliberately:\n * class nodes are schema, not content, and every document shares them — so\n * traversing them makes every document reachable from every other in two\n * hops (`a → graph:Document → b`). That is exactly the edge contamination\n * graph-governed retrieval exists to avoid. A `predicates` list that names\n * `rdf:type` follows them too, because it asked for them by name.\n */\n includeTypeEdges?: boolean;\n /** Append to an existing trace instead of starting a new one. */\n trace?: QueryTrace;\n}\n\nexport interface TraversedNode {\n iri: string;\n /** Hops from the nearest seed; seeds are 0. */\n depth: number;\n}\n\nexport interface TraverseResult {\n nodes: TraversedNode[];\n trace: QueryTrace;\n}\n\n/**\n * Resolve a variant input to its IRI: an exact node IRI, a `dcterms:title`\n * match on an `iirds:ProductVariant`, or a trailing-segment slug match.\n */\nexport function resolveVariant(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n if (graph.has(input)) return input;\n const wanted = input.toLowerCase();\n const variants = graph.instancesOf(`${NS.iirds}ProductVariant`);\n for (const v of variants) {\n if (graph.literal(v, DCTERMS_TITLE)?.toLowerCase() === wanted) return v;\n }\n for (const v of variants) {\n if (v.slice(v.lastIndexOf(\"/\") + 1).toLowerCase() === wanted) return v;\n }\n return undefined;\n}\n\n/** Resolve a software-subject input to its iiRDS IRI. */\nexport function resolveSubject(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n const mapped = SOFTWARE_SUBJECT_IRIS[input.toLowerCase()];\n if (mapped) return mapped;\n const expanded = graph.expand(input);\n return expanded.startsWith(\"http\") ? expanded : undefined;\n}\n\n/**\n * Decide whether a node survives the scope filter, and if not, why.\n *\n * Rules, in the spirit of ADR 01014 (absence of a positive claim is not a\n * negative claim, so both polarities are explicit):\n * - An explicit negative (`graph:notApplicableToVariant` /\n * `graph:notSoftwareSubject`) naming the target **excludes** the node.\n * - A node that declares a positive set which omits the target is **excluded**\n * — it scoped itself elsewhere — recorded under the positive predicate so\n * the trace distinguishes this from an explicit negative.\n * - A node that makes no claim is **kept**: unscoped content applies broadly.\n */\nexport function scopeExclusion(\n graph: GraphIndex,\n iri: string,\n scope: { variantIri?: string; subjectIri?: string; language?: string },\n): ScopeExclusion | undefined {\n // [target, positive predicate, negative predicate, object kind]. Language\n // joins the same table with two differences, both deliberate: its objects are\n // literals, and it has **no negative predicate** — a document has one\n // language (`sh:maxCount 1`), so \"not in German\" is not a claim an author\n // makes and there is nothing for a `graph:not*` term to express (ADR 01037).\n const checks: Array<\n [string | undefined, string, string | undefined, \"iri\" | \"literal\"]\n > = [\n [\n scope.variantIri,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n \"iri\",\n ],\n [scope.subjectIri, IIRDS_HAS_SUBJECT, GRAPH_NOT_SOFTWARE_SUBJECT, \"iri\"],\n [scope.language, DCTERMS_LANGUAGE, undefined, \"literal\"],\n ];\n for (const [target, positive, negative, kind] of checks) {\n if (!target) continue;\n if (negative !== undefined) {\n const denied = graph\n .values(iri, negative)\n .some((v) => v.kind === kind && v.value === target);\n if (denied) return { node: iri, rule: negative, value: target };\n }\n\n // Language is the one dimension a section inherits. Applicability is\n // explicit-only by ADR 01013 — a section may legitimately scope itself\n // differently from its document — but a section's *text* is in its\n // document's language and cannot differ, and the per-locale indexes file it\n // that way (`partitionByLanguage`). Without this a link with an anchor\n // reaches a section directly (derive.ts mints section IRIs as\n // `dcterms:references` targets) and carries English prose past a `de`\n // filter that excluded the document it belongs to.\n const subject = positive === DCTERMS_LANGUAGE ? documentOf(iri) : iri;\n const claimed = graph.values(subject, positive);\n if (claimed.length > 0) {\n const matches = claimed.some(\n (v) => v.kind === kind && v.value === target,\n );\n if (!matches) return { node: iri, rule: positive, value: target };\n }\n }\n return undefined;\n}\n\n/** Breadth-first traversal with scope filtering and full trace recording. */\nexport function traverse(\n graph: GraphIndex,\n options: TraverseOptions,\n): TraverseResult {\n const trace = options.trace ?? createTrace();\n const maxDepth = options.depth ?? 1;\n const direction: Direction = options.direction ?? \"out\";\n const allowed =\n options.predicates && options.predicates.length > 0\n ? new Set(options.predicates.map((p) => graph.expand(p)))\n : undefined;\n\n const variantIri = options.variant\n ? resolveVariant(graph, options.variant)\n : undefined;\n const subjectIri = options.subject\n ? resolveSubject(graph, options.subject)\n : undefined;\n // Language needs no resolution step, only a spelling: the filter value and\n // the graph value are both BCP-47 tags, and `derive` writes the canonical one.\n const language =\n options.language === undefined\n ? undefined\n : canonicalLanguageTag(options.language);\n const scope = { variantIri, subjectIri, language };\n // A predicate list that names `rdf:type` asked for type edges. Dropping them\n // anyway answered a question nobody asked, with an empty result.\n const followTypes =\n options.includeTypeEdges === true || allowed?.has(RDF_TYPE) === true;\n\n const excluded = new Set<string>();\n const keep = (iri: string): boolean => {\n if (excluded.has(iri)) return false;\n const exclusion = scopeExclusion(graph, iri, scope);\n if (exclusion) {\n excluded.add(iri);\n trace.exclusions.push(exclusion);\n return false;\n }\n return true;\n };\n\n const nodes: TraversedNode[] = [];\n const seen = new Set<string>();\n let frontier: string[] = [];\n\n // A seed `findEntry` already recorded keeps its real provenance. Re-recording\n // it as `explicit`/1 would leave the trace answering \"why did retrieval start\n // here?\" twice, with the lexical/vector score contradicted by a flat 1.\n const alreadySeeded = new Set(trace.entry.map((e) => e.iri));\n\n for (const seed of [...options.seeds].sort(byCodeUnit)) {\n if (!graph.has(seed) || seen.has(seed)) continue;\n seen.add(seed);\n if (!alreadySeeded.has(seed)) {\n trace.entry.push({ iri: seed, score: 1, via: \"explicit\" });\n }\n // A seed always expands, even when the scope filter excludes it. The\n // filter governs what the walk *reaches*, not where the caller chose to\n // start — and the canonical query is exactly this shape: from an English\n // page, `--impact --lang de` asks what German content a change here\n // affects. Gating the seed made that return nothing at all, because the\n // seed excluded itself before the frontier was ever populated.\n //\n // It is still kept out of the results and recorded in the trace, so the\n // answer honors the filter even though the walk started outside it.\n if (keep(seed)) nodes.push({ iri: seed, depth: 0 });\n frontier.push(seed);\n }\n\n const limit = options.limit ?? Infinity;\n for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {\n const next: string[] = [];\n for (const from of frontier) {\n if (nodes.length >= limit) break;\n for (const { predicate, target, dir } of neighbors(\n graph,\n from,\n direction,\n )) {\n if (allowed && !allowed.has(predicate)) continue;\n if (!followTypes && predicate === RDF_TYPE) continue;\n if (isStatementData(graph, target)) continue;\n // The hop is recorded before filtering: the trace shows the edge was\n // walked even when the target is then scope-excluded.\n trace.hops.push({ from, predicate, to: target, depth, direction: dir });\n if (seen.has(target)) continue;\n seen.add(target);\n if (!keep(target)) continue;\n if (nodes.length >= limit) break;\n nodes.push({ iri: target, depth });\n next.push(target);\n }\n }\n frontier = next;\n }\n\n return { nodes, trace };\n}\n\nfunction neighbors(\n graph: GraphIndex,\n iri: string,\n direction: Direction,\n): Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> {\n const out: Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> =\n [];\n if (direction === \"out\" || direction === \"both\") {\n for (const e of graph.out(iri)) out.push({ ...e, dir: \"out\" });\n }\n if (direction === \"in\" || direction === \"both\") {\n for (const e of graph.in(iri)) out.push({ ...e, dir: \"in\" });\n }\n return out;\n}\n\n/** Who links to this node (one hop inbound over `dcterms:references`). */\nexport function reverseReferences(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\" | \"predicates\"> = {},\n): TraverseResult {\n return traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n predicates: [DCTERMS_REFERENCES],\n depth: options.depth ?? 1,\n });\n}\n\n/**\n * Transitive inbound reach — \"what is affected if this node changes\".\n * Excludes the node itself from the returned set. Defaults to depth 3 rather\n * than the walker's 1, because impact analysis is only useful transitively.\n */\nexport function impact(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\"> = {},\n): TraverseResult {\n const result = traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n depth: options.depth ?? 3,\n // The seed *may* occupy a slot in the walker's limit, so ask for one more:\n // `limit` means \"this many *affected* nodes\". Whether it actually takes\n // one depends on the scope filter — a seed the filter excludes still\n // expands but is not in `nodes` — so the slack is trimmed below rather\n // than assumed spent.\n limit: options.limit === undefined ? undefined : options.limit + 1,\n });\n const affected = result.nodes.filter((n) => n.iri !== iri);\n return {\n nodes:\n options.limit === undefined ? affected : affected.slice(0, options.limit),\n trace: result.trace,\n };\n}\n","/**\n * Served passages with their proof (proposal 0090): the cores every host\n * calls, the two seams a host supplies, and `createRetriever`, the script\n * surface.\n *\n * - `retrieve` ranks entry passages, walks outward from them, and assembles a\n * bundle within a character budget.\n * - `lookup` takes only a question. It picks the language, then returns three\n * full sections: the ranked matches, everything reached outward from them,\n * and everything that depends on them. Nothing is dropped; a passage past a\n * section's budget keeps its node and record and loses only its text.\n *\n * A host supplies a `VectorStore`, which ranks rows for a query, and a\n * `ChunkSource`, which reads rows by id. The CLI and `createRetriever` build\n * the same context over the same artifact, so both answer alike.\n *\n * Platform-neutral: no `node:` imports. Each language's rows name their own\n * model, and the query is embedded with the queried language's. The default\n * embedder loads each model from the sibling `graph/embed` file when a\n * language first needs it, and a host where that fails falls back to lexical\n * entry and says so in the trace.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { canonicalLanguageTag, parseLocalizations } from \"../core/localizations.js\";\nimport { normalize } from \"../core/vector-index.js\";\nimport type { Citation, ContextBlock, Refusal } from \"./assemble.js\";\nimport type { ChunkRow, ChunksManifest, ProvenanceRecord, WithholdReason } from \"./chunks.js\";\nimport { rrfMerge, type QueryEmbedder } from \"./entry.js\";\nimport { GraphIndex } from \"./graph.js\";\nimport { createLexicalIndex, type LexicalIndex } from \"./lexical.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type Hop,\n type QueryTrace,\n type Resolution,\n type ScopeExclusion,\n} from \"./trace.js\";\nimport { impact as impactWalk, resolveSubject, resolveVariant, traverse } from \"./traverse.js\";\nimport { searchIndexDigest } from \"./vector.js\";\n\n// ---- the seams ---------------------------------------------------------------\n\n/** One condition on a chunk row's `metadata`. A list field matches when it contains the value. */\nexport interface WhereCondition {\n field: string;\n value: string;\n}\n\n/** What a vector store is asked. `vector` is `null` when the host did not embed the query. */\nexport interface VectorStoreQuery {\n text: string;\n vector: number[] | null;\n k: number;\n language: string | null;\n /** Every condition must hold. Empty when the caller set none. */\n where: WhereCondition[];\n}\n\nexport interface VectorStoreMatch {\n id: string;\n score: number;\n /** The row, when the store holds it. Otherwise the id is read through the `ChunkSource`. */\n row?: ChunkRow;\n}\n\n/** Ranks chunk rows for a query. */\nexport interface VectorStore {\n query(q: VectorStoreQuery): Promise<VectorStoreMatch[]>;\n}\n\n/** Reads chunk rows by id, from one language or, with `null`, from every one. */\nexport interface ChunkSource {\n get(ids: string[], language: string | null): Promise<ChunkRow[]>;\n}\n\n/** A `fetch` as the runtime uses it: GET for files, POST for the HTTP store. */\nexport type RetrieverFetch = (\n url: string,\n init?: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n\n// ---- errors ------------------------------------------------------------------\n\n/** The rows or the graph were built from another graph than the manifest names. */\nexport class StaleArtifactError extends Error {\n constructor(manifestGraph: string, found: string, file = \"graph.jsonld\") {\n super(`chunks.json was built from graph ${manifestGraph}, and ${file} is ${found}; publish again.`);\n this.name = \"StaleArtifactError\";\n }\n}\n\n/** The query embedder is not the model the queried language's rows were embedded with. */\nexport class ModelMismatchError extends Error {\n readonly expected: string;\n readonly actual: string;\n constructor(expected: string, actual: string) {\n super(`chunks.json was embedded with ${expected}, and the embedder loads ${actual}.`);\n this.name = \"ModelMismatchError\";\n this.expected = expected;\n this.actual = actual;\n }\n}\n\n// ---- results -----------------------------------------------------------------\n\nexport type PassageRole = \"match\" | \"context\" | \"dependent\";\n\nexport interface WithheldNode {\n node: string;\n because: WithholdReason[];\n /** `export` when the rows left it out, `query` when this call did. */\n at: \"export\" | \"query\";\n}\n\nexport interface FilteredNode {\n node: string;\n /** The first `where` field the row did not satisfy. */\n field: string;\n}\n\n/** The trace a served result carries: the walk's, plus what the trust floor and the filter left out. */\nexport interface RetrievalTrace {\n entry: {\n /** The ranked entry candidates that became matches, or the node a walk started from. */\n candidates: EntryCandidate[];\n /** `\"lexical\"` when the vector path was wanted and unavailable. */\n fallback?: \"lexical\";\n /** On `lookup`: each language's best entry score. */\n languages?: Record<string, number>;\n /** On `lookup`: the language chosen. */\n chosen?: string;\n };\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n withheld: WithheldNode[];\n filtered: FilteredNode[];\n}\n\n/** One served passage in a bundle. */\nexport interface PassageBlock extends ContextBlock {\n title: string;\n page: string;\n provenance: ProvenanceRecord;\n role: PassageRole;\n}\n\n/** What `retrieve`, `traverse` and `impact` return. */\nexport interface PassageBundle {\n /** The question, on `retrieve`. */\n question?: string;\n /** The node the walk started from, on `traverse` and `impact`. */\n node?: string;\n language: string | null;\n context: PassageBlock[];\n citations: Citation[];\n /** The delivered fields of each cited page, once per page. */\n pages: Record<string, { metadata: Record<string, unknown> }>;\n trace: RetrievalTrace;\n /** Present when nothing could be served. `context` is then empty. */\n refusal?: Refusal;\n /** True when the budget dropped a passage. */\n truncated: boolean;\n}\n\nexport interface LookupPassage {\n iri: string;\n title: string;\n page: string;\n lines: string;\n /** `null` when the section's budget ran out before it. */\n text: string | null;\n truncated: boolean;\n provenance: ProvenanceRecord;\n}\n\nexport interface LookupMatch extends LookupPassage {\n rank: number;\n /** `null` where a path did not run, or did not rank the passage. */\n score: { lexical: number | null; vector: number | null; fused: number };\n}\n\nexport interface LookupReached extends LookupPassage {\n depth: number;\n}\n\n/** An edge in the graph's own direction. */\nexport interface LookupEdge {\n from: string;\n predicate: string;\n to: string;\n}\n\nexport interface LookupSection<P> {\n passages: P[];\n truncated: boolean;\n}\n\nexport interface LookupWalk extends LookupSection<LookupReached> {\n edges: LookupEdge[];\n}\n\n/** What `lookup` returns: three full sections, each with its proof. */\nexport interface LookupResult {\n question: string;\n language: string | null;\n matches: LookupSection<LookupMatch>;\n traversal: LookupWalk;\n impact: LookupWalk;\n pages: Record<string, { metadata: Record<string, unknown> }>;\n citations: Citation[];\n trace: RetrievalTrace;\n /** Present only when there are no matches, or every match was withheld. Every section is then empty. */\n refusal?: Refusal;\n}\n\n// ---- the context every core reads --------------------------------------------\n\n/** The model one language's rows were embedded with, as `chunks.json` records it. */\nexport interface EmbeddingModel {\n id: string;\n dimensions: number;\n}\n\nexport interface RetrieverContext {\n manifest: ChunksManifest;\n graph: GraphIndex;\n /** One language's lexical index, or `undefined` when it has none. */\n lexical(language: string): Promise<LexicalIndex | undefined>;\n store: VectorStore;\n chunks: ChunkSource;\n /** The query embedder for one model, or `null` to send no query vector. */\n embedder(model: EmbeddingModel): Promise<QueryEmbedder | null>;\n}\n\nexport type RetrieveMode = \"lexical\" | \"vector\" | \"hybrid\";\n\nexport interface RetrieveOptions {\n question: string;\n lang?: string;\n variant?: string;\n softwareSubject?: string;\n seeds?: number;\n depth?: number;\n maxChars?: number;\n mode?: RetrieveMode;\n /** Tightens the trust floor for this call. */\n withhold?: WithholdReason[];\n where?: WhereCondition[];\n}\n\nexport interface WalkOptions {\n node: string;\n /** Walk inward, to what depends on the node. */\n impact?: boolean;\n depth?: number;\n predicates?: string[];\n reverse?: boolean;\n lang?: string;\n variant?: string;\n softwareSubject?: string;\n limit?: number;\n maxChars?: number;\n withhold?: WithholdReason[];\n where?: WhereCondition[];\n}\n\nexport interface LookupOptions {\n question: string;\n /** The serve host's query-time floor. */\n withhold?: WithholdReason[];\n}\n\n/** The depth `graph traverse --impact` uses by default, and so `lookup`'s inward walk. */\nexport const IMPACT_DEPTH = 3;\n\n// ponytail: one fixed candidate pool per leg; raise it when filters routinely\n// exhaust the pool before `seeds` matches are found.\nconst ENTRY_POOL = 50;\n\n// ---- the trust floor and the filter --------------------------------------------\n\n/** Whether a record falls under one withhold reason. A stale verdict never counts. */\nexport function withholds(record: ProvenanceRecord, reason: WithholdReason): boolean {\n if (reason === \"drifted\") return record.pins.error > 0;\n return record.evals !== null && record.evals.current && record.evals.fail + record.evals.error > 0;\n}\n\n/** The first condition a row fails, or `undefined` when it meets them all. */\nfunction failedField(row: ChunkRow, where: readonly WhereCondition[]): string | undefined {\n for (const { field, value } of where) {\n const held = row.metadata[field];\n const values = Array.isArray(held) ? held : [held];\n if (!values.some((v) => v !== undefined && v !== null && scalarText(v) === value)) return field;\n }\n return undefined;\n}\n\nfunction scalarText(v: unknown): string {\n return typeof v === \"string\" ? v : JSON.stringify(v);\n}\n\n// ---- entry ---------------------------------------------------------------------\n\ninterface Ranked {\n iri: string;\n via: EntryVia;\n fused: number;\n lexical: number | null;\n vector: number | null;\n row?: ChunkRow;\n}\n\ninterface Entry {\n ranked: Ranked[];\n fallback: boolean;\n /** The lexical leg's best score, else the vector leg's: what `lookup` compares languages by. */\n best: number | undefined;\n}\n\nfunction modelOf(manifest: ChunksManifest, language: string): EmbeddingModel | null {\n return manifest.languages[language]?.model ?? null;\n}\n\nasync function rank(\n ctx: RetrieverContext,\n question: string,\n language: string,\n mode: RetrieveMode | undefined,\n where: WhereCondition[],\n): Promise<Entry> {\n const model = modelOf(ctx.manifest, language);\n const wantVector = mode === \"vector\" || mode === \"hybrid\" || (mode === undefined && model !== null);\n let vector: EntryCandidate[] = [];\n const storeRows = new Map<string, ChunkRow>();\n // A language with no model, in a corpus where another has one, enters\n // lexically as a host that cannot load the model does, and says so.\n let fallback =\n mode === undefined && model === null && Object.values(ctx.manifest.languages).some((l) => l.model !== null);\n if (wantVector && question.trim() !== \"\") {\n let queryVector: number[] | null = null;\n const embedder = model === null ? null : await ctx.embedder(model);\n if (model !== null && embedder !== null) {\n if (embedder.model !== model.id) throw new ModelMismatchError(model.id, embedder.model);\n queryVector = Array.from(await embedder.embed(question));\n }\n const found = await ctx.store.query({ text: question, vector: queryVector, k: ENTRY_POOL, language, where });\n for (const m of found) if (m.row !== undefined) storeRows.set(m.id, m.row);\n vector = found\n .map((m): EntryCandidate => ({ iri: m.id, score: m.score, via: \"vector\" }))\n .sort((a, b) => (a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score));\n fallback = queryVector === null && vector.length === 0;\n }\n let lexical: EntryCandidate[] = [];\n if (mode !== \"vector\" || fallback) {\n const index = await ctx.lexical(language);\n lexical = index?.search(question, { limit: ENTRY_POOL }) ?? [];\n }\n const lexicalScore = new Map(lexical.map((c) => [c.iri, c.score]));\n const vectorScore = new Map(vector.map((c) => [c.iri, c.score]));\n const ranked = rrfMerge([lexical, vector].filter((leg) => leg.length > 0)).map((c): Ranked => {\n const row = storeRows.get(c.iri);\n return {\n iri: c.iri,\n via: c.via,\n fused: c.score,\n lexical: lexicalScore.get(c.iri) ?? null,\n vector: vectorScore.get(c.iri) ?? null,\n ...(row === undefined ? {} : { row }),\n };\n });\n // Words shared with the question say which language it is in; a similarity\n // from a model trained on one language says less. So the lexical leg's best\n // score speaks for the language, and the vector leg's only without it.\n const best = lexical[0]?.score ?? vector[0]?.score;\n return { ranked, fallback, best };\n}\n\n// ---- rows ----------------------------------------------------------------------\n\n/** Reads rows and holds them to the manifest's graph. */\nasync function rowsFor(\n ctx: RetrieverContext,\n ids: readonly string[],\n language: string | null,\n): Promise<Map<string, ChunkRow>> {\n const out = new Map<string, ChunkRow>();\n if (ids.length === 0) return out;\n for (const row of await ctx.chunks.get([...ids], language)) {\n if (row.graph !== ctx.manifest.graph) {\n throw new StaleArtifactError(ctx.manifest.graph, row.graph, ctx.manifest.languages[row.language]?.file ?? \"a chunk row\");\n }\n out.set(row.id, row);\n }\n return out;\n}\n\nfunction chunkFile(ctx: RetrieverContext, language: string | null): string {\n return language === null ? \"\" : (ctx.manifest.languages[language]?.file ?? \"\");\n}\n\n/** What happened to one node on its way to being served. */\ntype Admission = { kind: \"row\"; row: ChunkRow } | { kind: \"withheld\" } | { kind: \"skipped\" };\n\n/**\n * One node through the trust floor, the filter and the chunk lookup, each\n * outcome traced. A node with no row and no export record is not a passage.\n */\nfunction admit(\n ctx: RetrieverContext,\n iri: string,\n row: ChunkRow | undefined,\n language: string | null,\n floor: { withhold: readonly WithholdReason[]; where: readonly WhereCondition[]; exported: ReadonlyMap<string, WithholdReason[]> },\n trace: RetrievalTrace,\n): Admission {\n const exported = floor.exported.get(iri);\n if (exported !== undefined) {\n trace.withheld.push({ node: iri, because: exported, at: \"export\" });\n return { kind: \"withheld\" };\n }\n const sourceUrl = row === undefined ? chunkFile(ctx, language) : chunkFile(ctx, row.language);\n if (row === undefined) {\n trace.resolutions.push({ iri, sourceUrl, ok: false, error: \"no chunk row\" });\n return { kind: \"skipped\" };\n }\n const field = failedField(row, floor.where);\n if (field !== undefined) {\n trace.filtered.push({ node: iri, field });\n return { kind: \"skipped\" };\n }\n const because = floor.withhold.filter((reason) => withholds(row.provenance, reason));\n if (because.length > 0) {\n trace.withheld.push({ node: iri, because, at: \"query\" });\n return { kind: \"withheld\" };\n }\n trace.resolutions.push({ iri, sourceUrl, ok: true });\n return { kind: \"row\", row };\n}\n\nfunction floorOf(\n ctx: RetrieverContext,\n withhold: readonly WithholdReason[] | undefined,\n where: readonly WhereCondition[] | undefined,\n): Parameters<typeof admit>[4] {\n return {\n withhold: withhold ?? [],\n where: where ?? [],\n exported: new Map(ctx.manifest.withheld.map((w) => [w.id, w.because])),\n };\n}\n\nfunction emptyTrace(): RetrievalTrace {\n return { entry: { candidates: [] }, hops: [], exclusions: [], resolutions: [], withheld: [], filtered: [] };\n}\n\ninterface Matched {\n ranked: Ranked;\n row: ChunkRow;\n rank: number;\n}\n\n/**\n * The top `seeds` passages among the ranked candidates. A candidate that is\n * not a passage, or that the filter rejects, gives its place to the next; a\n * withheld one keeps its place and is left out.\n */\nasync function selectMatches(\n ctx: RetrieverContext,\n entry: Entry,\n language: string,\n seeds: number,\n floor: Parameters<typeof admit>[4],\n trace: RetrievalTrace,\n): Promise<{ kept: Matched[]; withheld: number }> {\n const rows = await rowsFor(\n ctx,\n entry.ranked.filter((r) => r.row === undefined).map((r) => r.iri),\n language,\n );\n const kept: Matched[] = [];\n let withheld = 0;\n for (const ranked of entry.ranked) {\n if (kept.length + withheld >= seeds) break;\n const row = ranked.row ?? rows.get(ranked.iri);\n if (row !== undefined && row.graph !== ctx.manifest.graph) {\n throw new StaleArtifactError(ctx.manifest.graph, row.graph, chunkFile(ctx, language) || \"a chunk row\");\n }\n const admitted = admit(ctx, ranked.iri, row, language, floor, trace);\n if (admitted.kind === \"skipped\") continue;\n trace.entry.candidates.push({ iri: ranked.iri, score: ranked.fused, via: ranked.via });\n if (admitted.kind === \"withheld\") withheld += 1;\n else kept.push({ ranked, row: admitted.row, rank: kept.length + withheld + 1 });\n }\n // Ranks count the withheld places too, so a reader sees the gap.\n return { kept, withheld };\n}\n\n// ---- walks ---------------------------------------------------------------------\n\ninterface Reached {\n iri: string;\n depth: number;\n row: ChunkRow;\n}\n\n/** Copy a walk's events into the served trace. */\nfunction absorb(trace: RetrievalTrace, walked: QueryTrace): void {\n trace.hops.push(...walked.hops);\n trace.exclusions.push(...walked.exclusions);\n}\n\n/** Every reached node past the seeds that is a servable passage, in walk order. */\nasync function passagesOf(\n ctx: RetrieverContext,\n nodes: readonly { iri: string; depth: number }[],\n language: string | null,\n floor: Parameters<typeof admit>[4],\n trace: RetrievalTrace,\n): Promise<Reached[]> {\n const rows = await rowsFor(ctx, nodes.map((n) => n.iri), language);\n const out: Reached[] = [];\n for (const n of nodes) {\n const admitted = admit(ctx, n.iri, rows.get(n.iri), language, floor, trace);\n if (admitted.kind === \"row\") out.push({ iri: n.iri, depth: n.depth, row: admitted.row });\n }\n return out;\n}\n\n/** An edge as the graph holds it, from a hop in either direction. */\nfunction edgeOf(graph: GraphIndex, hop: Hop): LookupEdge {\n const predicate = graph.compact(hop.predicate);\n return hop.direction === \"out\"\n ? { from: hop.from, predicate, to: hop.to }\n : { from: hop.to, predicate, to: hop.from };\n}\n\n// ---- language and scope --------------------------------------------------------\n\nfunction languagesOf(manifest: ChunksManifest): string[] {\n return Object.keys(manifest.languages).sort(byCodeUnit);\n}\n\n/** The manifest's own spelling of a tag, matched in any case. */\nfunction languageNamed(manifest: ChunksManifest, tag: string): string | undefined {\n const wanted = canonicalLanguageTag(tag);\n return languagesOf(manifest).find((l) => canonicalLanguageTag(l) === wanted);\n}\n\nfunction refusal(reason: Refusal[\"reason\"], detail: string): Refusal {\n return { reason, detail };\n}\n\n/** The refusal an unresolvable scope earns, or `undefined` when every filter resolves. */\nfunction scopeRefusal(\n ctx: RetrieverContext,\n scope: { variant?: string; softwareSubject?: string; lang?: string },\n): Refusal | undefined {\n if (scope.variant !== undefined && resolveVariant(ctx.graph, scope.variant) === undefined) {\n return refusal(\"unknown-scope\", `No product variant matches ${scope.variant}.`);\n }\n if (scope.softwareSubject !== undefined && resolveSubject(ctx.graph, scope.softwareSubject) === undefined) {\n return refusal(\"unknown-scope\", `No software subject matches ${scope.softwareSubject}.`);\n }\n if (scope.lang !== undefined && languageNamed(ctx.manifest, scope.lang) === undefined) {\n const have = languagesOf(ctx.manifest).join(\", \") || \"none\";\n return refusal(\"unknown-scope\", `No localization ${scope.lang}; this corpus has ${have}.`);\n }\n return undefined;\n}\n\n// ---- assembly ------------------------------------------------------------------\n\nfunction pagesOf(\n manifest: ChunksManifest,\n pages: Iterable<string>,\n): Record<string, { metadata: Record<string, unknown> }> {\n const out: Record<string, { metadata: Record<string, unknown> }> = {};\n for (const page of [...new Set(pages)].sort(byCodeUnit)) {\n out[page] = { metadata: manifest.pages[page]?.metadata ?? {} };\n }\n return out;\n}\n\n/** Blocks in order within the budget; a block past it is dropped, as `assemble` drops it. */\nfunction bundleOf(\n ctx: RetrieverContext,\n head: { question: string } | { node: string },\n language: string | null,\n items: readonly { row: ChunkRow; depth: number; role: PassageRole }[],\n maxChars: number,\n trace: RetrievalTrace,\n empty: Refusal,\n): PassageBundle {\n const base = { ...head, language, trace };\n if (items.length === 0) {\n return { ...base, context: [], citations: [], pages: {}, truncated: false, refusal: empty };\n }\n const context: PassageBlock[] = [];\n let used = 0;\n let truncated = false;\n for (const { row, depth, role } of items) {\n if (used + row.text.length > maxChars) {\n truncated = true;\n continue;\n }\n used += row.text.length;\n context.push({\n iri: row.id,\n title: row.title,\n text: row.text,\n sourceUrl: row.page,\n depth,\n page: row.page,\n provenance: row.provenance,\n role,\n });\n }\n if (context.length === 0) {\n return {\n ...base,\n context: [],\n citations: [],\n pages: {},\n truncated,\n refusal: refusal(\"no-content\", \"Every matching passage exceeded the character budget.\"),\n };\n }\n return {\n ...base,\n context,\n citations: context.map((b) => ({ iri: b.iri, title: b.title, sourceUrl: b.sourceUrl })),\n pages: pagesOf(ctx.manifest, context.map((b) => b.page)),\n truncated,\n };\n}\n\n/** Lay a section's passages against its budget: past it, a passage keeps all but its text. */\nfunction budget(passages: { text: string | null; truncated: boolean }[], maxChars: number): boolean {\n let used = 0;\n let cut = false;\n for (const p of passages) {\n const n = p.text?.length ?? 0;\n if (used + n > maxChars) {\n p.text = null;\n p.truncated = true;\n cut = true;\n } else {\n used += n;\n }\n }\n return cut;\n}\n\nfunction passageOf(row: ChunkRow): LookupPassage {\n return {\n iri: row.id,\n title: row.title,\n page: row.page,\n lines: row.lines,\n text: row.text,\n truncated: false,\n provenance: row.provenance,\n };\n}\n\n// ---- the cores -----------------------------------------------------------------\n\n/** Rank, choose, walk outward, assemble: the bundle a steering caller asked for. */\nexport async function retrieve(input: RetrieverContext & RetrieveOptions): Promise<PassageBundle> {\n const ctx = input;\n const trace = emptyTrace();\n const settings = ctx.manifest.retrieve;\n const seeds = input.seeds ?? settings.seeds;\n const depth = input.depth ?? settings.depth;\n const maxChars = input.maxChars ?? settings.maxChars;\n const head = { question: input.question };\n const refuse = (r: Refusal, language: string | null): PassageBundle =>\n bundleOf(ctx, head, language, [], maxChars, trace, r);\n\n const scope = scopeRefusal(ctx, input);\n if (scope !== undefined) return refuse(scope, null);\n const languages = languagesOf(ctx.manifest);\n const language = input.lang === undefined ? languages[0] : languageNamed(ctx.manifest, input.lang);\n if (input.lang === undefined && languages.length > 1) {\n return refuse(\n refusal(\"lang-required\", `This corpus has more than one localization (${languages.join(\", \")}); pass lang to choose one.`),\n null,\n );\n }\n if (language === undefined) return refuse(refusal(\"no-route\", \"This artifact holds no passages.\"), null);\n\n const where = input.where ?? [];\n const entry = await rank(ctx, input.question, language, input.mode, where);\n if (entry.fallback) trace.entry.fallback = \"lexical\";\n const floor = floorOf(ctx, input.withhold, where);\n const { kept, withheld } = await selectMatches(ctx, entry, language, seeds, floor, trace);\n if (kept.length === 0) {\n return refuse(\n withheld > 0\n ? refusal(\"withheld\", \"Every match was withheld by the trust floor; trace.withheld names them.\")\n : refusal(\"no-route\", \"No passage in the docs matches this question.\"),\n language,\n );\n }\n\n const walked = createTrace();\n const { nodes } = traverse(ctx.graph, {\n seeds: kept.map((m) => m.row.id),\n depth,\n direction: \"out\",\n ...(input.variant === undefined ? {} : { variant: input.variant }),\n ...(input.softwareSubject === undefined ? {} : { subject: input.softwareSubject }),\n language,\n trace: walked,\n });\n absorb(trace, walked);\n const inScope = new Set(nodes.filter((n) => n.depth === 0).map((n) => n.iri));\n const reached = await passagesOf(ctx, nodes.filter((n) => n.depth > 0), language, floor, trace);\n const items = [\n ...kept.filter((m) => inScope.has(m.row.id)).map((m) => ({ row: m.row, depth: 0, role: \"match\" as const })),\n ...reached.map((r) => ({ row: r.row, depth: r.depth, role: \"context\" as const })),\n ];\n return bundleOf(ctx, head, language, items, maxChars, trace, refusal(\"no-route\", \"Every match is outside the requested scope.\"));\n}\n\n/** A walk from one node, as a bundle: `traverse`, or `impact` with `impact: true`. */\nexport async function walkPassages(input: RetrieverContext & WalkOptions): Promise<PassageBundle> {\n const ctx = input;\n const trace = emptyTrace();\n const maxChars = input.maxChars ?? ctx.manifest.retrieve.maxChars;\n const node = ctx.graph.expand(input.node);\n const head = { node };\n const refuse = (r: Refusal): PassageBundle => bundleOf(ctx, head, null, [], maxChars, trace, r);\n if (!ctx.graph.has(node)) return refuse(refusal(\"unknown-node\", `No node ${input.node} in the graph.`));\n const scope = scopeRefusal(ctx, input);\n if (scope !== undefined) return refuse(scope);\n const language = input.lang === undefined ? null : (languageNamed(ctx.manifest, input.lang) ?? null);\n\n const walked = createTrace();\n const options = {\n ...(input.depth === undefined ? {} : { depth: input.depth }),\n ...(input.predicates === undefined ? {} : { predicates: input.predicates }),\n ...(input.variant === undefined ? {} : { variant: input.variant }),\n ...(input.softwareSubject === undefined ? {} : { subject: input.softwareSubject }),\n ...(input.lang === undefined ? {} : { language: input.lang }),\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n trace: walked,\n };\n const { nodes } =\n input.impact === true\n ? impactWalk(ctx.graph, node, options)\n : traverse(ctx.graph, { ...options, seeds: [node], direction: input.reverse === true ? \"in\" : \"out\" });\n absorb(trace, walked);\n trace.entry.candidates.push({ iri: node, score: 1, via: \"explicit\" });\n\n const floor = floorOf(ctx, input.withhold, input.where);\n const start = await passagesOf(ctx, [{ iri: node, depth: 0 }], language, floor, trace);\n const reached = await passagesOf(ctx, nodes.filter((n) => n.iri !== node), language, floor, trace);\n const inward = input.impact === true || input.reverse === true;\n const items = [\n ...start.map((r) => ({ row: r.row, depth: 0, role: \"match\" as const })),\n ...reached.map((r) => ({ row: r.row, depth: r.depth, role: inward ? (\"dependent\" as const) : (\"context\" as const) })),\n ];\n const languageOut = language ?? start[0]?.row.language ?? null;\n return bundleOf(\n ctx,\n head,\n languageOut,\n items,\n maxChars,\n trace,\n refusal(\"no-route\", \"No passage was reachable from this node under the active scope filter.\"),\n );\n}\n\n/**\n * The one call: a question in, three full sections out. It enters every\n * localization, keeps the one whose best match scores highest, and never asks\n * for a language.\n */\nexport async function lookup(input: RetrieverContext & LookupOptions): Promise<LookupResult> {\n const ctx = input;\n const trace = emptyTrace();\n const { seeds, depth, maxChars } = ctx.manifest.retrieve;\n const empty = (language: string | null, r: Refusal): LookupResult => ({\n question: input.question,\n language,\n matches: { passages: [], truncated: false },\n traversal: { passages: [], edges: [], truncated: false },\n impact: { passages: [], edges: [], truncated: false },\n pages: {},\n citations: [],\n trace,\n refusal: r,\n });\n\n // The language first, by its lexical scores, so only its model loads. With\n // no lexical match anywhere, each language's vector leg speaks for it.\n const choose = async (mode: RetrieveMode | undefined) => {\n const scores: Record<string, number> = {};\n let chosen: { language: string; entry: Entry; best: number } | undefined;\n for (const language of languagesOf(ctx.manifest)) {\n const entry = await rank(ctx, input.question, language, mode, []);\n if (entry.best === undefined) continue;\n scores[language] = entry.best;\n if (chosen === undefined || entry.best > chosen.best) chosen = { language, entry, best: entry.best };\n }\n return { scores, chosen };\n };\n let picked = await choose(\"lexical\");\n if (picked.chosen === undefined) picked = await choose(undefined);\n else picked.chosen.entry = await rank(ctx, input.question, picked.chosen.language, undefined, []);\n trace.entry.languages = picked.scores;\n if (picked.chosen === undefined) return empty(null, refusal(\"no-route\", \"No passage in the docs matches this question.\"));\n const { language, entry } = picked.chosen;\n trace.entry.chosen = language;\n if (entry.fallback) trace.entry.fallback = \"lexical\";\n\n const floor = floorOf(ctx, input.withhold, []);\n const { kept, withheld } = await selectMatches(ctx, entry, language, seeds, floor, trace);\n if (kept.length === 0) {\n return empty(\n language,\n withheld > 0\n ? refusal(\"withheld\", \"Every match was withheld by the trust floor; trace.withheld names them.\")\n : refusal(\"no-route\", \"No passage in the docs matches this question.\"),\n );\n }\n\n const seedIris = kept.map((m) => m.row.id);\n const walk = async (direction: \"out\" | \"in\", reach: number): Promise<LookupWalk> => {\n const walked = createTrace();\n const { nodes } = traverse(ctx.graph, { seeds: seedIris, depth: reach, direction, language, trace: walked });\n absorb(trace, walked);\n const reached = await passagesOf(ctx, nodes.filter((n) => n.depth > 0), language, floor, trace);\n const passages = reached.map((r): LookupReached => ({ ...passageOf(r.row), depth: r.depth }));\n return {\n passages,\n edges: walked.hops.map((h) => edgeOf(ctx.graph, h)),\n truncated: budget(passages, maxChars),\n };\n };\n\n const matches = kept.map(\n (m): LookupMatch => ({\n ...passageOf(m.row),\n rank: m.rank,\n score: { lexical: m.ranked.lexical, vector: m.ranked.vector, fused: m.ranked.fused },\n }),\n );\n const matchesTruncated = budget(matches, maxChars);\n const traversal = await walk(\"out\", depth);\n const impact = await walk(\"in\", IMPACT_DEPTH);\n\n const served = [...matches, ...traversal.passages, ...impact.passages];\n const citations: Citation[] = [];\n const cited = new Set<string>();\n for (const p of served) {\n if (p.text === null || cited.has(p.iri)) continue;\n cited.add(p.iri);\n citations.push({ iri: p.iri, title: p.title, sourceUrl: p.page });\n }\n return {\n question: input.question,\n language,\n matches: { passages: matches, truncated: matchesTruncated },\n traversal,\n impact,\n pages: pagesOf(ctx.manifest, served.map((p) => p.page)),\n citations,\n trace,\n };\n}\n\n// ---- the shipped seams and parsers -------------------------------------------------\n\n/** Ranks rows by cosine in memory, among those meeting `where`. Rows without a vector are never ranked. */\nexport function createStaticVectorStore(rows: readonly ChunkRow[]): VectorStore {\n return {\n query(q) {\n if (q.vector === null) return Promise.resolve([]);\n const query = normalize(Float32Array.from(q.vector));\n const scored: VectorStoreMatch[] = [];\n for (const row of rows) {\n if (row.vector === undefined || row.vector.length !== query.length) continue;\n if (q.language !== null && row.language !== q.language) continue;\n // Before the `k` cut, as a server store does, so a strict filter cannot starve the pool.\n if (failedField(row, q.where) !== undefined) continue;\n const stored = normalize(Float32Array.from(row.vector));\n let score = 0;\n for (const [i, value] of query.entries()) score += value * (stored[i] ?? 0);\n scored.push({ id: row.id, score, row });\n }\n scored.sort((a, b) => (a.score === b.score ? byCodeUnit(a.id, b.id) : b.score - a.score));\n return Promise.resolve(scored.slice(0, q.k));\n },\n };\n}\n\n/**\n * A store behind a site's own server. It POSTs `{ text, vector, k, language,\n * where }` as JSON and expects `{ matches: [{ id, score, row? }] }`.\n */\nexport function createHttpVectorStore(options: { url: string; fetch?: RetrieverFetch }): VectorStore {\n const doFetch = options.fetch ?? defaultFetch;\n return {\n async query(q) {\n const response = await doFetch(options.url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ text: q.text, vector: q.vector, k: q.k, language: q.language, where: q.where }),\n });\n if (!response.ok) throw new Error(`${options.url} answered HTTP ${String(response.status)}.`);\n const body = JSON.parse(await response.text()) as { matches?: unknown };\n if (!Array.isArray(body.matches)) throw new Error(`${options.url} returned no matches array.`);\n return body.matches.filter(isMatch);\n },\n };\n}\n\nfunction isMatch(m: unknown): m is VectorStoreMatch {\n if (typeof m !== \"object\" || m === null) return false;\n const o = m as Record<string, unknown>;\n return typeof o.id === \"string\" && typeof o.score === \"number\";\n}\n\n/** The rows of one `chunks.<tag>.jsonl`, for ingestion into a vector DB. */\nexport function parseChunkRows(text: string): ChunkRow[] {\n const rows: ChunkRow[] = [];\n for (const [i, line] of text.split(/\\r?\\n/).entries()) {\n if (line.trim() === \"\") continue;\n const row: unknown = JSON.parse(line);\n if (!isChunkRow(row)) throw new Error(`Line ${String(i + 1)} is not a chunk row.`);\n rows.push(row);\n }\n return rows;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The fields the cores read, so a damaged row fails here and not deep in a query. */\nfunction isChunkRow(v: unknown): v is ChunkRow {\n return (\n isRecord(v) &&\n [\"id\", \"graph\", \"page\", \"lines\", \"language\", \"title\", \"text\"].every((k) => typeof v[k] === \"string\") &&\n (v.vector === undefined || Array.isArray(v.vector)) &&\n isRecord(v.metadata) &&\n isRecord(v.provenance)\n );\n}\n\n/** `chunks.json`, checked to be one, down to the fields the cores read. */\nexport function parseChunksManifest(input: string | object): ChunksManifest {\n const doc: unknown = typeof input === \"string\" ? JSON.parse(input) : input;\n const valid =\n isRecord(doc) &&\n doc.format === \"manni-graph-chunks\" &&\n doc.version === 1 &&\n [\"graph\", \"graphFile\", \"searchIndex\"].every((k) => typeof doc[k] === \"string\") &&\n !(\"model\" in doc) &&\n isRecord(doc.retrieve) &&\n isRecord(doc.pages) &&\n Array.isArray(doc.withheld) &&\n isRecord(doc.languages) &&\n Object.values(doc.languages).every((l) => isRecord(l) && typeof l.file === \"string\" && isModel(l.model));\n if (!valid) throw new Error('Not a manni graph chunk manifest: expected format \"manni-graph-chunks\", version 1.');\n return doc as unknown as ChunksManifest;\n}\n\nfunction isModel(v: unknown): boolean {\n return v === null || (isRecord(v) && typeof v.id === \"string\" && typeof v.dimensions === \"number\");\n}\n\n/** Reads one `chunks.<tag>.jsonl`, given as its text or its URL. */\nexport function createChunkFileSource(textOrUrl: string, options: { fetch?: RetrieverFetch } = {}): ChunkSource {\n const isText = textOrUrl.trim() === \"\" || textOrUrl.trimStart().startsWith(\"{\");\n let rows: Promise<ChunkRow[]> | undefined;\n const load = (): Promise<ChunkRow[]> =>\n (rows ??= isText\n ? Promise.resolve(parseChunkRows(textOrUrl))\n : fetchText(options.fetch ?? defaultFetch, textOrUrl).then(parseChunkRows));\n return {\n async get(ids, language) {\n const want = new Set(ids);\n return (await load()).filter((r) => want.has(r.id) && (language === null || r.language === language));\n },\n };\n}\n\n// ---- the context, from an artifact -------------------------------------------------\n\nfunction defaultFetch(url: string, init?: Parameters<RetrieverFetch>[1]): ReturnType<RetrieverFetch> {\n return globalThis.fetch(url, init);\n}\n\nasync function fetchText(doFetch: RetrieverFetch, url: string): Promise<string> {\n const response = await doFetch(url);\n if (!response.ok) throw new Error(`${url} answered HTTP ${String(response.status)}.`);\n return response.text();\n}\n\n/**\n * The context over one artifact, with `read` resolving a path relative to the\n * manifest. The CLI reads files and `createRetriever` fetches, through this\n * one function, so both serve the same rows, stores and indexes.\n */\nexport function artifactContext(\n manifest: ChunksManifest,\n graph: GraphIndex,\n read: (path: string) => Promise<string>,\n seams: { store?: VectorStore; chunks?: ChunkSource; embedder: RetrieverContext[\"embedder\"] },\n): RetrieverContext {\n // Each model loads once, when a language that needs it is first queried.\n const embedders = new Map<string, Promise<QueryEmbedder | null>>();\n const embedder = (model: EmbeddingModel): Promise<QueryEmbedder | null> => {\n let pending = embedders.get(model.id);\n if (pending === undefined) {\n pending = seams.embedder(model);\n embedders.set(model.id, pending);\n }\n return pending;\n };\n\n const loaded = new Map<string, Promise<ChunkRow[]>>();\n const rowsOf = (language: string): Promise<ChunkRow[]> => {\n let pending = loaded.get(language);\n if (pending === undefined) {\n const entry = manifest.languages[language];\n pending = entry === undefined ? Promise.resolve([]) : read(entry.file).then(parseChunkRows);\n loaded.set(language, pending);\n }\n return pending;\n };\n const allRows = async (language: string | null): Promise<ChunkRow[]> =>\n language === null ? (await Promise.all(languagesOf(manifest).map(rowsOf))).flat() : rowsOf(language);\n\n const chunks: ChunkSource = seams.chunks ?? {\n async get(ids, language) {\n const want = new Set(ids);\n return (await allRows(language)).filter((r) => want.has(r.id));\n },\n };\n const store: VectorStore = seams.store ?? {\n async query(q) {\n return createStaticVectorStore(await allRows(q.language)).query(q);\n },\n };\n\n let localizations: Promise<ReturnType<typeof parseLocalizations>> | undefined;\n const lexicons = new Map<string, Promise<LexicalIndex | undefined>>();\n const lexical = (language: string): Promise<LexicalIndex | undefined> => {\n let pending = lexicons.get(language);\n if (pending === undefined) {\n pending = (async () => {\n localizations ??= read(manifest.searchIndex).then(parseLocalizations);\n const doc = await localizations;\n const wanted = canonicalLanguageTag(language);\n const entry = doc?.languages.find((l) => canonicalLanguageTag(l.language) === wanted);\n return entry === undefined ? undefined : createLexicalIndex(await read(entry.search.path));\n })();\n lexicons.set(language, pending);\n }\n return pending;\n };\n\n return { manifest, graph, lexical, store, chunks, embedder };\n}\n\n// ---- the script surface --------------------------------------------------------------\n\nexport interface CreateRetrieverOptions {\n /** `chunks.json`: its URL, or the parsed manifest. Every other file resolves from its directory. */\n manifest: string | object;\n /** Default: the static store over the rows' vectors. */\n store?: VectorStore;\n /** Default: the chunk files the manifest names. */\n chunks?: ChunkSource;\n /** Default: `graph/embed` with each language's model, loaded when first queried. `false` forces lexical entry. */\n embed?: QueryEmbedder | false;\n /** Default: the global `fetch`. */\n fetch?: RetrieverFetch;\n}\n\n/**\n * The cores over one artifact. `withhold` on `retrieve`, `traverse` and\n * `impact` tightens the floor the artifact was exported with, per call, as\n * the CLI's `--withhold` does. It never lowers it: exported rows stay out.\n * `lookup` takes only a question and serves the exported floor.\n */\nexport interface Retriever {\n readonly manifest: ChunksManifest;\n lookup(question: string): Promise<LookupResult>;\n retrieve(\n question: string,\n options?: Pick<\n RetrieveOptions,\n \"lang\" | \"variant\" | \"softwareSubject\" | \"depth\" | \"maxChars\" | \"mode\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n traverse(\n node: string,\n options?: Pick<\n WalkOptions,\n \"depth\" | \"predicates\" | \"reverse\" | \"lang\" | \"variant\" | \"softwareSubject\" | \"limit\" | \"maxChars\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n impact(\n node: string,\n options?: Pick<\n WalkOptions,\n \"depth\" | \"lang\" | \"variant\" | \"softwareSubject\" | \"limit\" | \"maxChars\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n}\n\ninterface EmbedModule {\n createLocalEmbedder(o: { model: string; role: \"query\" }): Promise<QueryEmbedder>;\n createMockEmbedder(o: { dims: number }): QueryEmbedder;\n}\n\n/**\n * One language's model, loaded from the `graph/embed` file beside this one.\n * The specifier is not a literal, so a bundler leaves it alone, and a host\n * that cannot load it gets `null`: lexical entry, traced as a fallback.\n */\nasync function defaultEmbedder(model: EmbeddingModel): Promise<QueryEmbedder | null> {\n try {\n const specifier = \"./embed.js\";\n const embed = (await import(/* @vite-ignore */ specifier)) as EmbedModule;\n return model.id === \"mock\"\n ? embed.createMockEmbedder({ dims: model.dimensions })\n : await embed.createLocalEmbedder({ model: model.id, role: \"query\" });\n } catch {\n return null;\n }\n}\n\n/** The retrieval cores over a published artifact. Returns data and calls no model but the embedder. */\nexport async function createRetriever(options: CreateRetrieverOptions): Promise<Retriever> {\n const doFetch = options.fetch ?? defaultFetch;\n const fromUrl = typeof options.manifest === \"string\";\n const manifest = parseChunksManifest(\n typeof options.manifest === \"string\" ? await fetchText(doFetch, options.manifest) : options.manifest,\n );\n const base = typeof options.manifest === \"string\" ? options.manifest.slice(0, options.manifest.lastIndexOf(\"/\") + 1) : \"\";\n const resolvePath = (path: string): string => (fromUrl && !/^[a-z][a-z0-9+.-]*:/i.test(path) ? base + path : path);\n const read = (path: string): Promise<string> => fetchText(doFetch, resolvePath(path));\n\n const graphText = await read(manifest.graphFile);\n const digest = `sha256-${(await searchIndexDigest(graphText)).slice(\"sha256:\".length)}`;\n if (digest !== manifest.graph) throw new StaleArtifactError(manifest.graph, digest);\n const graph = GraphIndex.fromJsonLd(graphText);\n\n const embed = options.embed;\n const embedder: RetrieverContext[\"embedder\"] =\n embed === false ? () => Promise.resolve(null) : embed === undefined ? defaultEmbedder : () => Promise.resolve(embed);\n const ctx = artifactContext(manifest, graph, read, {\n ...(options.store === undefined ? {} : { store: options.store }),\n ...(options.chunks === undefined ? {} : { chunks: options.chunks }),\n embedder,\n });\n\n return {\n manifest,\n lookup: (question) => lookup({ ...ctx, question }),\n retrieve: (question, o = {}) => retrieve({ ...ctx, ...o, question }),\n traverse: (node, o = {}) => walkPassages({ ...ctx, ...o, node }),\n impact: (node, o = {}) => walkPassages({ ...ctx, ...o, node, impact: true }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmCA,IAAM,QAAQ,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,EAAI,CAAC;AAIrD,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AA8Bf,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,UAAU,QAAoC;AAC5D,MAAI,MAAM;AAGV,aAAW,SAAS,OAAQ,QAAO,QAAQ;AAC3C,MAAI,QAAQ,EAAG,QAAO;AACtB,QAAM,MAAM,IAAI,KAAK,KAAK,GAAG;AAG7B,SAAO,IAAI,OAAO,IAAI,CAAC,UAAU,QAAQ,GAAG,CAAC;AAC7C,SAAO;AACT;AAMO,SAAS,kBACd,SACA,MACY;AACZ,QAAM,SAAS,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;AACjE,QAAM,OAAO,OAAO,CAAC,GAAG,OAAO,UAAU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AC,MAAM,aAAa,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM,QAAQ,KAAK,CAAC;AAAA,EAC7E;AACF;","names":["language","entry","impact"]}
|
|
1
|
+
{"version":3,"sources":["../src/graph/core/vector-index.ts","../src/graph/runtime/chunks.ts","../src/graph/runtime/graph.ts","../src/graph/runtime/vector.ts","../src/graph/runtime/trace.ts","../src/graph/runtime/entry.ts","../src/graph/runtime/lexical.ts","../src/graph/runtime/traverse.ts","../src/graph/runtime/retrieve.ts"],"sourcesContent":["/**\n * The vector sidecar (ADR 01020) — `graph/vectors.<lang>.bin`, embeddings for the\n * same text that language's lexical index covers (ADR 01038).\n *\n * Layout, fixed. The magic is four ASCII bytes in file order; every number\n * after it is little-endian:\n *\n * ```\n * 0 magic \"MGRV\" 4 bytes\n * 4 format version (u32) 4 bytes\n * 8 header length (u32) 4 bytes\n * 12 header JSON (UTF-8) headerLength bytes\n * . float32 payload count * dims * 4 bytes\n * ```\n *\n * The header names the model, dtype, dimensions, the node IRIs in payload order\n * (sorted), and a digest of the `search.json` the vectors were built from — so\n * the runtime can refuse to rank against vectors from a different model or a\n * stale corpus rather than returning quietly wrong results.\n *\n * Vectors are **L2-normalized at build time and stored as float32**. Normalizing\n * makes cosine collapse to a dot product at query time; float32 rather than int8\n * because int8 retains only ~91% of retrieval quality at 384 dimensions — see\n * ADR 01020, where that correction is recorded.\n *\n * No `node:` imports: the encoder runs in the CLI, the decoder in the browser.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/**\n * \"MGRV\", manni graph vectors, as the bytes a hex dump shows first. It read\n * \"DKGV\" while the tool was dockg and \"MKGV\" while it was manni kg. Nothing was\n * published under either name, so no sidecar in the wild carries the old bytes.\n * Raw bytes rather than a little-endian u32: a u32 lands on disk reversed.\n */\nconst MAGIC = new Uint8Array([0x4d, 0x47, 0x52, 0x56]);\n// 2 since ADR 01038: the header names the language its vectors cover, so a\n// consumer cannot pair a sidecar with the wrong locale's index. A version-1\n// file is refused by `decodeVectorIndex` rather than read as if it had one.\nconst FORMAT_VERSION = 2;\nconst HEADER_OFFSET = 12;\n\nexport interface VectorIndexHeader {\n /** Embedding model id, e.g. an HF repo path. */\n model: string;\n /** Model-weight quantization the vectors were produced under. */\n dtype: string;\n /** Vector dimensions. Never assumed — always read from here. */\n dims: number;\n /** Number of vectors; equals `ids.length`. */\n count: number;\n /** Node IRIs, sorted, in payload order. */\n ids: string[];\n /** Digest of the `search.<lang>.json` these were built from (staleness detection). */\n source: string;\n /**\n * BCP-47 tag of the index these cover, or `und` (ADR 01038). Recorded so a\n * host that fetched the wrong pair is refused rather than ranked against a\n * model that never saw the language.\n */\n language: string;\n}\n\nexport interface VectorIndexDoc {\n header: VectorIndexHeader;\n /** `count * dims` floats, L2-normalized, row-major in `ids` order. */\n vectors: Float32Array;\n}\n\n/** Thrown for malformed input so callers can map it to an exit code / refusal. */\nexport class VectorIndexError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexError\";\n }\n}\n\n/**\n * L2-normalize a vector in place and return it. A zero vector is left alone —\n * dividing by its norm would produce NaNs that silently poison every later dot\n * product.\n */\nexport function normalize(vector: Float32Array): Float32Array {\n let sum = 0;\n // Iterating rather than indexing: every element is an element, which is what\n // the assertions here used to say.\n for (const value of vector) sum += value * value;\n if (sum === 0) return vector;\n const inv = 1 / Math.sqrt(sum);\n // `set(map(…))` scales every element in place with the same per-element\n // float32 rounding the indexed loop had, and without an index to assert.\n vector.set(vector.map((value) => value * inv));\n return vector;\n}\n\n/**\n * Encode entries into the sidecar. Entries are sorted by IRI first, so the bytes\n * depend on the set of entries and not on the order they were produced in.\n */\nexport function encodeVectorIndex(\n entries: Array<{ id: string; vector: Float32Array }>,\n meta: { model: string; dtype: string; source: string; language: string },\n): Uint8Array {\n const sorted = [...entries].sort((a, b) => byCodeUnit(a.id, b.id));\n const dims = sorted[0]?.vector.length ?? 0;\n for (const entry of sorted) {\n if (entry.vector.length !== dims) {\n throw new VectorIndexError(\n `Inconsistent vector dimensions: ${entry.id} has ${entry.vector.length}, expected ${dims}.`,\n );\n }\n }\n\n const header: VectorIndexHeader = {\n model: meta.model,\n dtype: meta.dtype,\n dims,\n count: sorted.length,\n ids: sorted.map((e) => e.id),\n source: meta.source,\n language: meta.language,\n };\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n\n const payloadBytes = sorted.length * dims * 4;\n const out = new Uint8Array(HEADER_OFFSET + headerBytes.length + payloadBytes);\n const view = new DataView(out.buffer);\n out.set(MAGIC, 0);\n view.setUint32(4, FORMAT_VERSION, true);\n view.setUint32(8, headerBytes.length, true);\n out.set(headerBytes, HEADER_OFFSET);\n\n let offset = HEADER_OFFSET + headerBytes.length;\n for (const entry of sorted) {\n // Normalize a copy: the caller's array is not ours to mutate.\n const vector = normalize(Float32Array.from(entry.vector));\n // Exactly `dims` elements: the loop above rejected any entry of another\n // length, so iterating the vector is the same walk without the index.\n for (const value of vector) {\n view.setFloat32(offset, value, true);\n offset += 4;\n }\n }\n return out;\n}\n\n/** Decode a sidecar, rejecting anything malformed rather than mis-reading it. */\nexport function decodeVectorIndex(bytes: Uint8Array): VectorIndexDoc {\n if (bytes.length < HEADER_OFFSET) {\n throw new VectorIndexError(\"Not a manni graph vector index: file is too short.\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (!MAGIC.every((byte, i) => bytes[i] === byte)) {\n throw new VectorIndexError(\n \"Not a manni graph vector index: bad magic — is this the right file?\",\n );\n }\n const version = view.getUint32(4, true);\n if (version !== FORMAT_VERSION) {\n throw new VectorIndexError(\n `Unsupported vector index version ${version} (this build reads ${FORMAT_VERSION}) — re-run \\`manni graph embed\\`.`,\n );\n }\n\n const headerLength = view.getUint32(8, true);\n if (HEADER_OFFSET + headerLength > bytes.length) {\n throw new VectorIndexError(\"Vector index is truncated: header overruns.\");\n }\n\n let header: VectorIndexHeader;\n try {\n header = JSON.parse(\n new TextDecoder().decode(\n bytes.subarray(HEADER_OFFSET, HEADER_OFFSET + headerLength),\n ),\n ) as VectorIndexHeader;\n } catch {\n throw new VectorIndexError(\"Vector index header is not valid JSON.\");\n }\n if (\n !Array.isArray(header.ids) ||\n typeof header.dims !== \"number\" ||\n header.ids.length !== header.count\n ) {\n throw new VectorIndexError(\"Vector index header is malformed.\");\n }\n\n const start = HEADER_OFFSET + headerLength;\n const expected = header.count * header.dims * 4;\n if (bytes.length - start !== expected) {\n throw new VectorIndexError(\n `Vector index is truncated: expected ${expected} payload bytes, found ${bytes.length - start}.`,\n );\n }\n\n // Copy rather than aliasing: `bytes` may be a view into a larger buffer whose\n // byteOffset is not 4-aligned, which Float32Array construction rejects.\n const vectors = new Float32Array(header.count * header.dims);\n for (let i = 0; i < vectors.length; i++) {\n vectors[i] = view.getFloat32(start + i * 4, true);\n }\n return { header, vectors };\n}\n","/**\n * The chunk artifact's shapes (proposal 0090): `chunks.json`, the manifest,\n * and one `chunks.<tag>.jsonl` row per servable passage, each carrying its\n * provenance record. `manni graph export chunks` writes them on the Node side;\n * every host reads them. Types only, so the runtime bundle stays\n * platform-neutral.\n */\n\n/** What a pin's finding says: cite's rule, at the severity `cite.severity` resolves. */\nexport interface PinFinding {\n rule: string;\n severity: \"notice\" | \"warning\" | \"error\";\n}\n\n/** One citation pin whose claim overlaps the passage. */\nexport interface PinItem {\n /** The citation's `id`, when it has one. */\n id: string | null;\n /** The body lines the claim occupies now: `N` or `N-M`. */\n claim: string;\n /** `path:lines` as the entry spells it; an encrypted path stays its token. */\n source: string;\n /** The commit the source end was recorded at, as recorded, or `null`. */\n commit: string | null;\n /** Empty means current. */\n findings: PinFinding[];\n /** The entry's `last-verified` as written, or `null`. */\n lastVerified: string | null;\n /** The entry's `verified-by` entries, or `[]`. */\n verifiedBy: unknown[];\n}\n\nexport interface PinSummary {\n total: number;\n current: number;\n notice: number;\n warning: number;\n error: number;\n items: PinItem[];\n}\n\n/**\n * A merge-safe date (proposals 0069, 0072): the derived UTC day, and whether\n * the page names it. `stamp` is `null` exactly when `day` is: with no derived\n * day there is nothing to compare the page against.\n */\nexport interface DerivedDate {\n day: string | null;\n stamp: \"current\" | \"stale\" | \"absent\" | null;\n}\n\nexport interface ProvenanceDates {\n created: DerivedDate;\n lastUpdated: DerivedDate;\n /** The page's `last-verified` as written, or `null`. */\n lastVerified: string | null;\n /** The page's `verified-by` entries, or `[]`. */\n verifiedBy: unknown[];\n}\n\nexport interface EvalItem {\n name: string;\n suite: string;\n grader: string;\n outcome: \"pass\" | \"fail\" | \"needs-review\" | \"skipped\" | \"error\";\n confidence?: number;\n}\n\nexport interface ProvenanceEvals {\n /** `sha256-<64 hex>` of the report the verdicts came from. */\n report: string;\n /** Whether the page still has the bytes the verdicts judged. */\n current: boolean;\n pass: number;\n fail: number;\n needsReview: number;\n skipped: number;\n error: number;\n items: EvalItem[];\n}\n\n/** A statement (proposal 0099) anchored inside the passage: on a block, or on a section's heading. */\nexport interface PassageStatement {\n /** Body lines, `N-M`. */\n lines: string;\n status: \"current\" | \"changed\" | \"unpinned\";\n /** Its delivered fields. */\n data: Record<string, unknown>;\n}\n\n/** The proof one served passage carries. Self-contained: copied out alone, it still says what it describes. */\nexport interface ProvenanceRecord {\n node: string;\n page: string;\n lines: string;\n /** The docs commit, or `null` outside git. */\n commit: string | null;\n worktree: \"clean\" | \"modified\" | null;\n pins: PinSummary;\n dates: ProvenanceDates;\n /** `null` when no docevals report was given. */\n evals: ProvenanceEvals | null;\n statements: PassageStatement[];\n}\n\n/** One line of `chunks.<tag>.jsonl`. */\nexport interface ChunkRow {\n /** The graph node IRI. */\n id: string;\n /** The digest of the graph the row was built from. */\n graph: string;\n page: string;\n /** Body lines, `N-M`. */\n lines: string;\n language: string;\n title: string;\n text: string;\n /** Present when the manifest names a model for the row's language. */\n vector?: number[];\n /** The page's delivered fields, overlaid by its heading statements down to this section. */\n metadata: Record<string, unknown>;\n provenance: ProvenanceRecord;\n}\n\nexport type WithholdReason = \"drifted\" | \"failing\";\n\n/** `chunks.json`. Keys are sorted, and nothing in it reads the wall clock. */\nexport interface ChunksManifest {\n format: \"manni-graph-chunks\";\n version: 1;\n /** `sha256-<64 hex>` of `graphFile`. */\n graph: string;\n graphFile: string;\n searchIndex: string;\n commit: string | null;\n worktree: \"clean\" | \"modified\" | null;\n retrieve: { seeds: number; depth: number; maxChars: number; withhold: WithholdReason[] };\n evals: { report: string; digest: string } | null;\n /** Each language's rows, and the model its vector sidecar was embedded with, or `null` without one. */\n languages: Record<string, { file: string; rows: number; model: { id: string; dimensions: number } | null }>;\n pages: Record<string, { metadata: Record<string, unknown> }>;\n withheld: { id: string; page: string; because: WithholdReason[] }[];\n}\n\n/** A cite line spec, `N` or `N-M`, as a span; `undefined` when it is not one or runs backwards. */\nexport function range(spec: string): { start: number; end: number } | undefined {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(spec.trim());\n if (m?.[1] === undefined) return undefined;\n const start = Number(m[1]);\n const end = m[2] === undefined ? start : Number(m[2]);\n return end < start ? undefined : { start, end };\n}\n","/**\n * `GraphIndex` — the browser-native in-memory graph (ADR 01018).\n *\n * Built from `graph.jsonld` (the Phase 6 export) with **no RDF parser**: that\n * artifact is plain `JSON.parse`-able, deterministically sorted, and free of\n * blank nodes, so a `Map`-based adjacency index is all the runtime needs. Node\n * callers can also build from quads (`fromQuads`) so the CLI can read Turtle.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies, no I/O — the\n * caller supplies the bytes. Type-only imports are erased at build time.\n *\n * Every accessor returns deterministically sorted results, so traversal order\n * (and therefore the trace) is byte-stable for a given graph.\n */\nimport type { Quad } from \"../core/derive.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { RDF_TYPE } from \"../core/vocab.js\";\n\n/** An object value: an IRI reference or a literal. */\nexport type Value =\n | { kind: \"iri\"; value: string }\n | { kind: \"literal\"; value: string; datatype?: string; language?: string };\n\nexport interface GraphNode {\n id: string;\n /** Full class IRIs, sorted. */\n types: string[];\n /** Full predicate IRI → values, in insertion-normalized sorted order. */\n props: Map<string, Value[]>;\n}\n\n/** The parsed shape of a `graph.jsonld` document. */\ninterface JsonLdDoc {\n \"@context\"?: Record<string, string>;\n \"@graph\"?: unknown[];\n}\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\n\nfunction compareValues(a: Value, b: Value): number {\n if (a.kind !== b.kind) return a.kind === \"iri\" ? -1 : 1;\n const v = byCodeUnit(a.value, b.value);\n if (v !== 0) return v;\n const da = a.kind === \"literal\" ? (a.datatype ?? \"\") : \"\";\n const db = b.kind === \"literal\" ? (b.datatype ?? \"\") : \"\";\n const la = a.kind === \"literal\" ? (a.language ?? \"\") : \"\";\n const lb = b.kind === \"literal\" ? (b.language ?? \"\") : \"\";\n return byCodeUnit(da, db) || byCodeUnit(la, lb);\n}\n\nexport class GraphIndex {\n private readonly nodes = new Map<string, GraphNode>();\n /** subject → predicate → object IRIs (sorted). */\n private readonly outbound = new Map<string, Map<string, string[]>>();\n /** object → predicate → subject IRIs (sorted). */\n private readonly inbound = new Map<string, Map<string, string[]>>();\n /** class IRI → instance IRIs (sorted). */\n private readonly byType = new Map<string, string[]>();\n /** prefix → namespace, from the artifact's own `@context`. */\n readonly context: Record<string, string>;\n\n private constructor(context: Record<string, string>) {\n this.context = context;\n }\n\n /**\n * Build from a `graph.jsonld` document — a JSON string or the parsed object.\n * CURIE keys and `@type` values are expanded using the document's own\n * `@context`, so the index is self-describing.\n */\n static fromJsonLd(input: string | object): GraphIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as JsonLdDoc) : input\n ) as JsonLdDoc;\n const context = doc[\"@context\"] ?? {};\n const index = new GraphIndex({ ...context });\n for (const raw of doc[\"@graph\"] ?? []) {\n index.addJsonLdNode(raw as Record<string, unknown>);\n }\n index.finalize();\n return index;\n }\n\n /** Build from dockg's internal quad shape (the Node/CLI path). */\n static fromQuads(quads: Quad[], context: Record<string, string> = {}) {\n const index = new GraphIndex({ ...context });\n for (const q of quads) {\n const o = q.o;\n const value: Value =\n o.kind === \"iri\"\n ? { kind: \"iri\", value: o.value }\n : o.language\n ? { kind: \"literal\", value: o.value, language: o.language }\n : o.datatype && o.datatype !== XSD_STRING\n ? { kind: \"literal\", value: o.value, datatype: o.datatype }\n : { kind: \"literal\", value: o.value };\n index.addTriple(q.s, q.p, value);\n }\n index.finalize();\n return index;\n }\n\n /** Expand a CURIE (`dcterms:title`) to a full IRI using `@context`. */\n expand(term: string): string {\n const colon = term.indexOf(\":\");\n if (colon <= 0) return term;\n const ns = this.context[term.slice(0, colon)];\n return ns ? `${ns}${term.slice(colon + 1)}` : term;\n }\n\n /** Compact a full IRI to a CURIE when a context namespace matches. */\n compact(iri: string): string {\n let best = iri;\n let bestNs = \"\";\n for (const [prefix, ns] of Object.entries(this.context)) {\n if (\n iri.startsWith(ns) &&\n iri.length > ns.length &&\n ns.length > bestNs.length\n ) {\n best = `${prefix}:${iri.slice(ns.length)}`;\n bestNs = ns;\n }\n }\n return best;\n }\n\n private addJsonLdNode(raw: Record<string, unknown>): void {\n const id = typeof raw[\"@id\"] === \"string\" ? this.expand(raw[\"@id\"]) : \"\";\n if (!id) return;\n this.ensureNode(id);\n\n const rawTypes = raw[\"@type\"];\n for (const t of toArray(rawTypes)) {\n if (typeof t === \"string\") {\n this.addTriple(id, RDF_TYPE, { kind: \"iri\", value: this.expand(t) });\n }\n }\n\n for (const [key, rawValue] of Object.entries(raw)) {\n if (key === \"@id\" || key === \"@type\") continue;\n const predicate = this.expand(key);\n for (const v of toArray(rawValue)) {\n const value = this.toValue(v);\n if (value) this.addTriple(id, predicate, value);\n }\n }\n }\n\n private toValue(v: unknown): Value | undefined {\n if (typeof v === \"string\") return { kind: \"literal\", value: v };\n if (typeof v === \"number\" || typeof v === \"boolean\") {\n return { kind: \"literal\", value: String(v) };\n }\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (typeof o[\"@id\"] === \"string\") {\n return { kind: \"iri\", value: this.expand(o[\"@id\"]) };\n }\n if (o[\"@value\"] !== undefined) {\n const raw = o[\"@value\"];\n // JSON.stringify spells a number or boolean the way String() would,\n // and gives an object a lexical form instead of \"[object Object]\".\n const lexical = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n if (typeof o[\"@language\"] === \"string\") {\n return { kind: \"literal\", value: lexical, language: o[\"@language\"] };\n }\n const dt =\n typeof o[\"@type\"] === \"string\" ? this.expand(o[\"@type\"]) : undefined;\n return dt && dt !== XSD_STRING\n ? { kind: \"literal\", value: lexical, datatype: dt }\n : { kind: \"literal\", value: lexical };\n }\n }\n return undefined;\n }\n\n private ensureNode(id: string): GraphNode {\n let node = this.nodes.get(id);\n if (!node) {\n node = { id, types: [], props: new Map() };\n this.nodes.set(id, node);\n }\n return node;\n }\n\n private addTriple(s: string, p: string, o: Value): void {\n const node = this.ensureNode(s);\n let values = node.props.get(p);\n if (!values) {\n values = [];\n node.props.set(p, values);\n }\n values.push(o);\n\n if (p === RDF_TYPE && o.kind === \"iri\") {\n node.types.push(o.value);\n const instances = this.byType.get(o.value);\n if (instances) instances.push(s);\n else this.byType.set(o.value, [s]);\n }\n\n if (o.kind === \"iri\") {\n addEdge(this.outbound, s, p, o.value);\n addEdge(this.inbound, o.value, p, s);\n // Referenced-only IRIs still resolve as (empty) nodes.\n this.ensureNode(o.value);\n }\n }\n\n /** Sort every collection so traversal order is deterministic. */\n private finalize(): void {\n for (const node of this.nodes.values()) {\n node.types.sort(byCodeUnit);\n for (const values of node.props.values()) values.sort(compareValues);\n }\n for (const instances of this.byType.values()) instances.sort(byCodeUnit);\n for (const map of [this.outbound, this.inbound]) {\n for (const preds of map.values()) {\n for (const targets of preds.values()) targets.sort(byCodeUnit);\n }\n }\n }\n\n /** Every node IRI, sorted. */\n ids(): string[] {\n return [...this.nodes.keys()].sort(byCodeUnit);\n }\n\n size(): number {\n return this.nodes.size;\n }\n\n node(iri: string): GraphNode | undefined {\n return this.nodes.get(iri);\n }\n\n has(iri: string): boolean {\n return this.nodes.has(iri);\n }\n\n /** Class IRIs of a node, sorted. */\n types(iri: string): string[] {\n return this.nodes.get(iri)?.types ?? [];\n }\n\n /** Instances of a class, sorted. */\n instancesOf(classIri: string): string[] {\n return this.byType.get(classIri) ?? [];\n }\n\n /** All values for a predicate, sorted. */\n values(iri: string, predicate: string): Value[] {\n return this.nodes.get(iri)?.props.get(predicate) ?? [];\n }\n\n /** Literal lexical forms for a predicate, sorted. */\n literals(iri: string, predicate: string): string[] {\n return this.values(iri, predicate)\n .filter((v) => v.kind === \"literal\")\n .map((v) => v.value);\n }\n\n /** The first literal for a predicate, if any. */\n literal(iri: string, predicate: string): string | undefined {\n return this.literals(iri, predicate)[0];\n }\n\n /** Outbound IRI targets: all predicates, or one. Sorted. */\n out(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.outbound, iri, predicate);\n }\n\n /** Inbound IRI sources (who points at this node). Sorted. */\n in(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.inbound, iri, predicate);\n }\n}\n\nfunction addEdge(\n map: Map<string, Map<string, string[]>>,\n key: string,\n predicate: string,\n target: string,\n): void {\n let preds = map.get(key);\n if (!preds) {\n preds = new Map();\n map.set(key, preds);\n }\n const targets = preds.get(predicate);\n if (targets) targets.push(target);\n else preds.set(predicate, [target]);\n}\n\nfunction edges(\n map: Map<string, Map<string, string[]>>,\n iri: string,\n predicate?: string,\n): Array<{ predicate: string; target: string }> {\n const preds = map.get(iri);\n if (!preds) return [];\n const out: Array<{ predicate: string; target: string }> = [];\n const keys = predicate ? [predicate] : [...preds.keys()].sort(byCodeUnit);\n for (const p of keys) {\n for (const target of preds.get(p) ?? []) out.push({ predicate: p, target });\n }\n return out;\n}\n\nfunction toArray(v: unknown): unknown[] {\n if (v === undefined || v === null) return [];\n return Array.isArray(v) ? v : [v];\n}\n","/**\n * Vector search (ADR 01020) — semantic entry, and a standalone capability.\n *\n * `search()` is usable on its own: give it a query vector and it ranks nodes by\n * meaning, with no lexical index and no graph involved. `findEntry` composes it\n * with the lexical leg, but does not own it.\n *\n * Hand-written rather than taken from a library, on evidence: the dedicated\n * browser vector libraries are 3 years stale, no maintained micro-package does\n * cosine top-k over typed arrays (the popular one throws on `Float32Array`), and\n * the engines that do exist run this same brute-force loop internally. See ADR\n * 01020 for the full survey.\n *\n * Vectors are L2-normalized at build time, so cosine similarity **is** the dot\n * product — no norms, no division, at query time. The loop is indexed rather\n * than `.reduce()`, which measures ~13× slower on typed arrays.\n *\n * Platform-neutral: no `node:` imports, no dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport {\n decodeVectorIndex,\n normalize,\n type VectorIndexHeader,\n} from \"../core/vector-index.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface VectorSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n /**\n * Drop candidates scoring below this. Default 0 — every model has its own\n * useful range, so dockg does not impose a threshold the user did not choose.\n */\n minScore?: number;\n}\n\n/** Why a vector index cannot be used with the embedder or corpus at hand. */\nexport interface VectorMismatch {\n reason: \"model\" | \"dtype\" | \"dims\" | \"stale-source\";\n detail: string;\n}\n\n/**\n * Thrown when a query would be ranked against vectors it cannot be compared to.\n *\n * A distinct type so hosts can catch exactly this — and so it cannot be mistaken\n * for \"no results\". Ranking on regardless is the silent-wrong-answer failure\n * ADR 01020 exists to prevent, so this is loud by design.\n */\nexport class VectorMismatchError extends Error {\n readonly reason: VectorMismatch[\"reason\"];\n constructor(mismatch: VectorMismatch) {\n super(mismatch.detail);\n this.name = \"VectorMismatchError\";\n this.reason = mismatch.reason;\n }\n}\n\n/**\n * The digest `manni graph embed` records as a sidecar's `source`, computed the same\n * way in a browser — SHA-256 over the **raw bytes of `search.json` exactly as\n * fetched**, hex, prefixed `sha256:`.\n *\n * Exists so a host can pass `source` to `findEntry` and get the staleness half\n * of the refusal (ADR 01020) without reconstructing the recipe. Re-serializing\n * the parsed JSON would change the bytes and so the digest — pass the response\n * text, not `JSON.stringify(doc)`.\n *\n * Uses Web Crypto, which is platform-neutral: browsers and Node 18+ both have\n * it on `globalThis`.\n */\nexport async function searchIndexDigest(raw: string): Promise<string> {\n // `lib.dom` and @types/node both declare `globalThis.crypto.subtle` as\n // always present. A page served over plain HTTP gets `crypto` without\n // `subtle`, which is the case this throw exists for: the declaration is the\n // optimistic one, and reading through `Partial` is how the guard gets to say\n // so instead of reading as a test that cannot fail.\n const webCrypto = globalThis.crypto as\n | Partial<typeof globalThis.crypto>\n | undefined;\n const subtle = webCrypto?.subtle;\n if (!subtle) {\n throw new Error(\n \"searchIndexDigest needs Web Crypto (globalThis.crypto.subtle), which is unavailable here — a page served over plain HTTP does not get it.\",\n );\n }\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(raw));\n const hex = [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nexport interface VectorIndex {\n /**\n * Rank nodes against a query vector. The vector is normalized here, so\n * callers need not — an unnormalized query would otherwise scale every score.\n */\n search(query: Float32Array, options?: VectorSearchOptions): EntryCandidate[];\n /**\n * Check this index against the embedder and corpus in play. Returns the\n * mismatch, or undefined when they agree. Ranking against vectors from a\n * different model compares outputs of two different functions (ADR 01020), so\n * callers should refuse rather than proceed.\n */\n check(expected: {\n model?: string;\n dtype?: string;\n dims?: number;\n source?: string;\n }): VectorMismatch | undefined;\n readonly model: string;\n /**\n * Weight quantization the corpus vectors were produced under. The query side\n * must embed at the *same* dtype — q8 and fp32 weights are different\n * functions, so mixing them compares incomparable vectors (ADR 01020).\n */\n readonly dtype: string;\n readonly dims: number;\n readonly source: string;\n size(): number;\n /** The IRI at a payload row, for callers walking the index directly. */\n idAt(row: number): string | undefined;\n}\n\n/** Build a vector index from encoded sidecar bytes. */\nexport function createVectorIndex(bytes: Uint8Array): VectorIndex {\n const { header, vectors } = decodeVectorIndex(bytes);\n const { dims, ids } = header;\n\n return {\n model: header.model,\n dtype: header.dtype,\n dims,\n source: header.source,\n size: () => ids.length,\n idAt: (row) => ids[row],\n\n check(expected) {\n if (expected.model !== undefined && expected.model !== header.model) {\n return {\n reason: \"model\",\n detail: `Vector index was built with ${header.model}, but the embedder is ${expected.model}. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dtype !== undefined && expected.dtype !== header.dtype) {\n return {\n reason: \"dtype\",\n detail: `Vector index was built at dtype ${header.dtype}, but the embedder is at ${expected.dtype} — different weights are a different function. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dims !== undefined && expected.dims !== dims) {\n return {\n reason: \"dims\",\n detail: `Vector index has ${dims} dimensions, but the embedder produces ${expected.dims}.`,\n };\n }\n if (expected.source !== undefined && expected.source !== header.source) {\n return {\n reason: \"stale-source\",\n detail:\n \"Vector index was built from a different search index — the corpus changed. Re-run `manni graph embed`.\",\n };\n }\n return undefined;\n },\n\n search(query, options = {}) {\n if (dims === 0 || ids.length === 0) return [];\n if (query.length !== dims) {\n // A silent zero-fill or truncate here would return confident nonsense.\n // Typed like every other mismatch so a caller (and the CLI's exit-code\n // mapping) handles it the same way rather than seeing a raw stack.\n throw new VectorMismatchError({\n reason: \"dims\",\n detail: `Query vector has ${query.length} dimensions, but the index has ${dims}.`,\n });\n }\n const limit = normalizeLimit(options.limit);\n if (limit === 0) return [];\n const minScore = options.minScore ?? 0;\n\n // Copy before normalizing: the caller's vector is not ours to mutate.\n const q = normalize(Float32Array.from(query));\n\n const scored: EntryCandidate[] = [];\n // `entries()` pairs each row with its IRI, so the id is proven present\n // by the iteration rather than asserted after an index.\n for (const [row, iri] of ids.entries()) {\n // The payload is `count × dims` floats, so this row is exactly these\n // `dims` of them — and `q` was checked to be `dims` long above. Both\n // walks are therefore in range; `?? 0` spells that a term outside the\n // row contributes nothing, which is what out of range means for a dot\n // product.\n const stored = vectors.subarray(row * dims, (row + 1) * dims);\n let score = 0;\n for (const [i, value] of q.entries()) score += value * (stored[i] ?? 0);\n if (score >= minScore) {\n scored.push({ iri, score, via: \"vector\" });\n }\n }\n\n scored.sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n return scored.slice(0, limit);\n },\n };\n}\n\n/**\n * A limit that is not a non-negative integer falls back to the documented\n * default — `slice(0, NaN)` is empty, which would report a confident \"no\n * results\" for a query that does match.\n */\nfunction normalizeLimit(limit: number | undefined): number {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit >= 0\n ? limit\n : 10;\n}\n\nexport type { VectorIndexHeader };\n","/**\n * Query trace — the explainability contract (ADR 01018). Every runtime stage\n * appends to a trace, and no API returns results without one: retrieval\n * provenance is part of the contract exactly as PROV provenance is part of the\n * build. The trace answers \"how and why did this result come back\": which nodes\n * were seeded, every hop walked, every node scope excluded (and by which rule),\n * and every content resolution attempted.\n *\n * Events are appended in traversal order, which is itself deterministic, so the\n * trace is byte-stable for a given graph + query.\n */\n\n/** How a seed was found. `hybrid` means several legs agreed on it. */\nexport type EntryVia = \"explicit\" | \"lexical\" | \"vector\" | \"hybrid\";\n\n/** A starting node, with the score/reason that made it a seed. */\nexport interface EntryCandidate {\n iri: string;\n /**\n * Relevance score: 1 for an explicitly requested seed, otherwise the fused\n * `rrfMerge` score. Note that fusion is **rank**-based, so a searched seed's\n * score reflects its position (1/(60 + rank)), not the engine's relevance —\n * it orders candidates but is not a magnitude to threshold on.\n */\n score: number;\n via: EntryVia;\n}\n\n/** One edge walked, in either direction. */\nexport interface Hop {\n from: string;\n predicate: string;\n to: string;\n /** Hops from the nearest seed (seeds are depth 0; their neighbors are 1). */\n depth: number;\n direction: \"out\" | \"in\";\n}\n\n/** A node the scope filter removed, and why. */\nexport interface ScopeExclusion {\n node: string;\n /**\n * The predicate that disqualified the node: a `graph:not*` IRI when an\n * explicit negative named the target, or the positive predicate (e.g.\n * `iirds:relates-to-product-variant`) when the node declared a scope set that\n * omits the target.\n */\n rule: string;\n /**\n * The filter target being applied — the variant or subject IRI the query\n * asked for. Under a `graph:not*` rule the node named this explicitly; under\n * a positive rule this is what the node's declared set was missing.\n */\n value: string;\n}\n\n/** One content-resolution attempt. */\nexport interface Resolution {\n iri: string;\n sourceUrl: string;\n ok: boolean;\n /** Present when `ok` is false. */\n error?: string;\n}\n\nexport interface QueryTrace {\n entry: EntryCandidate[];\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n}\n\nexport function createTrace(): QueryTrace {\n return { entry: [], hops: [], exclusions: [], resolutions: [] };\n}\n\n/**\n * Every node named anywhere in the trace as reached — seeds plus hop targets.\n * The trace-completeness contract: a traversal's results must be a subset of\n * this, so every returned node is explainable by recorded events.\n */\nexport function reachedNodes(trace: QueryTrace): Set<string> {\n const reached = new Set<string>();\n for (const e of trace.entry) reached.add(e.iri);\n for (const h of trace.hops) reached.add(h.to);\n return reached;\n}\n","/**\n * Entry-point finding (ADR 01019, extended by ADR 01020) — the stage that turns\n * a question into seed nodes for the walker.\n *\n * Two rankings now: lexical (BM25 over the search artifact) and, when the host\n * supplies an embedder, vector (cosine over the sidecar). `rrfMerge` fuses them.\n *\n * **Each leg is returned separately as well as fused.** A caller rendering a\n * search UI wants to show \"text matches\" and \"semantic matches\" as distinct\n * things, and either leg is usable on its own — `lexical.search` and\n * `vectors.search` are public and independent of this function.\n *\n * Every candidate is appended to the trace, so \"why did retrieval start here?\"\n * is answerable alongside \"why did it walk there?\" (ADR 01018 invariant 2).\n *\n * Platform-neutral: no `node:` imports.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { LexicalIndex } from \"./lexical.js\";\nimport { VectorMismatchError, type VectorIndex } from \"./vector.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type QueryTrace,\n} from \"./trace.js\";\n\n/**\n * Enough of an embedder to verify it against a vector index. Structural rather\n * than the `Embedder` interface itself, so the runtime stays independent of\n * `@hawkeyexl/manni/graph/embed` — any object with these three fields works.\n */\nexport interface QueryEmbedder {\n readonly model: string;\n readonly dtype: string;\n embed(text: string): Promise<Float32Array> | Float32Array;\n}\n\nexport interface FindEntryOptions {\n /** The lexical index to query. */\n lexical: LexicalIndex;\n /** The vector index. Without it (and an embedder), entry is lexical-only. */\n vectors?: VectorIndex;\n /**\n * The embedder for the query side. **Prefer this over `embedQuery`**: it\n * carries the model and dtype, so `findEntry` can verify they match the\n * vector index and refuse rather than rank against incomparable vectors.\n */\n embedder?: QueryEmbedder;\n /**\n * Embed the query with a bare function. An escape hatch for hosts wiring\n * their own model — but it carries no identity, so **the model/dtype match\n * cannot be verified**; only the dimension check inside `search` applies.\n * Prefer `embedder`.\n */\n embedQuery?: (query: string) => Promise<Float32Array> | Float32Array;\n /**\n * Digest of the `search.json` this caller loaded, from `searchIndexDigest`.\n * Supplied, a sidecar built from a *different* corpus is refused rather than\n * ranked — its IRIs may no longer exist, and it misses everything added\n * since. Omitted, that half of the check simply does not run: the runtime\n * cannot derive the digest, since it never sees the raw bytes.\n */\n source?: string;\n /** Maximum seeds to return. Default 10. */\n limit?: number;\n /** Append candidates here instead of starting a new trace. */\n trace?: QueryTrace;\n}\n\nexport interface EntryResult {\n /** The fused ranking — what seeds traversal. */\n candidates: EntryCandidate[];\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was supplied. */\n vector: EntryCandidate[];\n trace: QueryTrace;\n}\n\n/**\n * Reciprocal rank fusion over N ranked lists: score = Σ 1/(k + rank).\n *\n * Rank-based rather than score-based on purpose — lexical BM25 scores and\n * cosine similarities are not on a comparable scale, so fusing raw scores would\n * let whichever leg happens to produce bigger numbers dominate. `k = 60` is the\n * standard damping constant.\n *\n * Deterministic: input list order does not affect the result, and ties break by\n * IRI.\n */\nexport function rrfMerge(\n rankings: EntryCandidate[][],\n k = 60,\n): EntryCandidate[] {\n const fused = new Map<string, { score: number; vias: Set<EntryVia> }>();\n for (const ranking of rankings) {\n ranking.forEach((candidate, i) => {\n const current = fused.get(candidate.iri) ?? {\n score: 0,\n vias: new Set<EntryVia>(),\n };\n current.score += 1 / (k + i + 1);\n current.vias.add(candidate.via);\n fused.set(candidate.iri, current);\n });\n }\n\n return [...fused.entries()]\n .map(([iri, { score, vias }]) => {\n // One leg keeps its own provenance; several means the seed was fused.\n // Destructuring rather than `[...vias][0]!` so the single-leg case needs\n // no non-null assertion — an empty set simply falls through to \"hybrid\",\n // which is unreachable anyway (a set only exists once a leg added to it).\n const [only] = vias;\n return {\n iri,\n score,\n via: vias.size === 1 && only !== undefined ? only : \"hybrid\",\n };\n })\n .sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n}\n\n/**\n * Find seed nodes for a question, returning each ranking leg and their fusion.\n *\n * Async because embedding a query is: local models are a WASM forward pass.\n * Uniformly async rather than sync-when-lexical-only, so callers have one\n * contract to hold rather than a return type that changes with the options.\n *\n * The vector leg runs only when both a `vectors` index and an `embedQuery` are\n * supplied. Absent either, this is lexical entry exactly as Phase 8 shipped it —\n * additive, never a new failure mode (ADR 01009's degrade-don't-fail rule).\n */\nexport async function findEntry(\n query: string,\n options: FindEntryOptions,\n): Promise<EntryResult> {\n const trace = options.trace ?? createTrace();\n // `--limit abc` parses to NaN, and `slice(0, NaN)` is empty — a typo'd flag\n // would report a confident \"0 results\" for a query that does match. Anything\n // that is not a non-negative integer falls back to the documented default.\n const limit =\n typeof options.limit === \"number\" &&\n Number.isInteger(options.limit) &&\n options.limit >= 0\n ? options.limit\n : 10;\n\n const lexical = options.lexical.search(query, { limit });\n\n // Bound first: the closure then captures the embedder the test found, rather\n // than re-reading a property the type cannot know is still the same one.\n const embedder = options.embedder;\n const embed = embedder ? (q: string) => embedder.embed(q) : options.embedQuery;\n\n let vector: EntryCandidate[] = [];\n if (options.vectors && embed && query.trim() !== \"\") {\n // Verify *before* embedding. The refusal is enforced here, not only in the\n // CLI, because this is the browser-facing surface — and the whole reason\n // ADR 01020 exists is that the browser must embed with a function that\n // agrees with the one that embedded the corpus. Ranking a stale or\n // wrong-model index would be the silent wrong answer this design prevents.\n const mismatch = options.vectors.check({\n ...(options.embedder\n ? { model: options.embedder.model, dtype: options.embedder.dtype }\n : {}),\n // Staleness is checked whichever way the query is embedded — it is a\n // property of the corpus, not of the embedder, so even the unverified\n // `embedQuery` path gets it when the caller supplies a digest.\n ...(options.source === undefined ? {} : { source: options.source }),\n });\n if (mismatch) throw new VectorMismatchError(mismatch);\n const queryVector = await embed(query);\n vector = options.vectors.search(queryVector, { limit });\n }\n\n const rankings = vector.length > 0 ? [lexical, vector] : [lexical];\n const candidates = rrfMerge(rankings).slice(0, limit);\n\n for (const candidate of candidates) trace.entry.push(candidate);\n return { candidates, lexical, vector, trace };\n}\n","/**\n * Lexical entry (ADR 01019) — text query → ranked seed nodes.\n *\n * Loads the `search.json` artifact (produced by `manni graph export search`)\n * and scores it with MiniSearch. The artifact carries body text, which the graph\n * deliberately does not (ADR 01008), so a query can match what a document *says*\n * and not merely what it is titled.\n *\n * MiniSearch is this runtime's one production dependency; the bundle-purity gate\n * allow-lists exactly it. Two guards keep ranking a dockg contract rather than a\n * library's: ties are broken by IRI here (MiniSearch does not define tie order),\n * and the on-disk artifact format is ours, so upgrading MiniSearch can never\n * change a committed artifact.\n *\n * Platform-neutral: no `node:` imports.\n */\nimport MiniSearch from \"minisearch\";\nimport type { SearchEntry, SearchIndexDoc } from \"../core/search-index.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface LexicalSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n}\n\nexport interface LexicalIndex {\n /** Ranked candidates, best first, ties broken by IRI. */\n search(query: string, options?: LexicalSearchOptions): EntryCandidate[];\n /** Indexed entry count. */\n size(): number;\n /** The entry behind an IRI, for callers that want its title/type. */\n entry(iri: string): SearchEntry | undefined;\n}\n\n/**\n * Build a lexical index from the search artifact — a JSON string or the parsed\n * document.\n */\nexport function createLexicalIndex(\n input: string | SearchIndexDoc,\n): LexicalIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as SearchIndexDoc) : input\n ) as SearchIndexDoc | null;\n // Shape-check rather than trust: handed something that is valid JSON but not\n // a search artifact, MiniSearch's `addAll` throws \"documents is not\n // iterable\" from inside the library. An empty index is the honest answer.\n const entries = Array.isArray(doc?.entries) ? doc.entries : [];\n\n const mini = new MiniSearch<SearchEntry>({\n fields: [\"title\", \"labels\", \"description\", \"text\"],\n storeFields: [\"id\"],\n idField: \"id\",\n // Titles and labels are the strongest signal that a node *is* the subject;\n // body text is evidence it merely mentions it.\n searchOptions: {\n boost: { title: 3, labels: 2, description: 1.5 },\n prefix: true,\n fuzzy: 0.2,\n },\n });\n mini.addAll(entries);\n\n const byIri = new Map(entries.map((e) => [e.id, e]));\n\n return {\n size: () => entries.length,\n entry: (iri) => byIri.get(iri),\n search(query, options = {}) {\n const trimmed = query.trim();\n if (trimmed === \"\") return [];\n const hits = mini.search(trimmed);\n // MiniSearch does not define an order for equal scores; sort explicitly so\n // the same query against the same artifact always ranks identically.\n hits.sort((a, b) =>\n a.score === b.score\n ? byCodeUnit(String(a.id), String(b.id))\n : b.score - a.score,\n );\n return hits\n .slice(0, options.limit ?? 10)\n .map((h) => ({ iri: String(h.id), score: h.score, via: \"lexical\" }));\n },\n };\n}\n","/**\n * The deterministic walker (ADR 01018) — breadth-first traversal over a\n * `GraphIndex` with scope filtering, recording every hop and every exclusion\n * into a `QueryTrace`. This is the engine: generic RDF engines return bindings\n * without the path that produced them, and dockg's scope rules (ADR 01014)\n * are domain semantics no general engine knows.\n *\n * Determinism: neighbors come back sorted from the index, the frontier is\n * processed in (depth, IRI) order, and results are emitted in discovery order —\n * so the same graph + query always yields the same nodes *and* the same trace.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { NS, RDF_TYPE } from \"../core/vocab.js\";\nimport { canonicalLanguageTag } from \"../core/localizations.js\";\nimport {\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n GRAPH_NOT_SOFTWARE_SUBJECT,\n IIRDS_HAS_SUBJECT,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n SOFTWARE_SUBJECT_IRIS,\n} from \"../core/iirds.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport { createTrace, type QueryTrace, type ScopeExclusion } from \"./trace.js\";\n\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_REFERENCES = `${NS.dcterms}references`;\nconst DCTERMS_LANGUAGE = `${NS.dcterms}language`;\n\n/**\n * Block and verification nodes (proposal 0099) are graph data, not passages:\n * a walk never steps into one. `graph query` still sees them all.\n */\nconst STATEMENT_DATA = new Set([`${NS.graph}Block`, `${NS.graph}Verification`]);\n\nfunction isStatementData(graph: GraphIndex, iri: string): boolean {\n return graph.types(iri).some((t) => STATEMENT_DATA.has(t));\n}\n\n/** A section IRI's document, or the IRI itself when it has no fragment. */\nfunction documentOf(iri: string): string {\n const hash = iri.indexOf(\"#\");\n return hash === -1 ? iri : iri.slice(0, hash);\n}\n\nexport type Direction = \"out\" | \"in\" | \"both\";\n\nexport interface ScopeFilter {\n /** Product variant: an IRI, a `dcterms:title` (e.g. \"SP-X100\"), or a slug. */\n variant?: string;\n /** Software subject: an IRI or a `graph.about-product-aspect` value (e.g. \"architecture\"). */\n subject?: string;\n /**\n * BCP-47 tag (ADR 01037). Matched against `dcterms:language` after both are\n * canonicalized, since tags are case-insensitive. There is no fallback:\n * `de-AT` is not `de`, because relatedness between locales is an inference\n * and this runtime does not infer.\n */\n language?: string;\n}\n\nexport interface TraverseOptions extends ScopeFilter {\n /** Starting nodes (IRIs). */\n seeds: string[];\n /** Maximum hops from a seed. Default 1. */\n depth?: number;\n /** Restrict to these predicates (full IRIs). Default: every predicate. */\n predicates?: string[];\n /** Which edge directions to follow. Default \"out\". */\n direction?: Direction;\n /** Stop after this many nodes (seeds included). */\n limit?: number;\n /**\n * Follow `rdf:type` edges into class nodes. Default false, deliberately:\n * class nodes are schema, not content, and every document shares them — so\n * traversing them makes every document reachable from every other in two\n * hops (`a → graph:Document → b`). That is exactly the edge contamination\n * graph-governed retrieval exists to avoid. A `predicates` list that names\n * `rdf:type` follows them too, because it asked for them by name.\n */\n includeTypeEdges?: boolean;\n /** Append to an existing trace instead of starting a new one. */\n trace?: QueryTrace;\n}\n\nexport interface TraversedNode {\n iri: string;\n /** Hops from the nearest seed; seeds are 0. */\n depth: number;\n}\n\nexport interface TraverseResult {\n nodes: TraversedNode[];\n trace: QueryTrace;\n}\n\n/**\n * Resolve a variant input to its IRI: an exact node IRI, a `dcterms:title`\n * match on an `iirds:ProductVariant`, or a trailing-segment slug match.\n */\nexport function resolveVariant(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n if (graph.has(input)) return input;\n const wanted = input.toLowerCase();\n const variants = graph.instancesOf(`${NS.iirds}ProductVariant`);\n for (const v of variants) {\n if (graph.literal(v, DCTERMS_TITLE)?.toLowerCase() === wanted) return v;\n }\n for (const v of variants) {\n if (v.slice(v.lastIndexOf(\"/\") + 1).toLowerCase() === wanted) return v;\n }\n return undefined;\n}\n\n/** Resolve a software-subject input to its iiRDS IRI. */\nexport function resolveSubject(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n const mapped = SOFTWARE_SUBJECT_IRIS[input.toLowerCase()];\n if (mapped) return mapped;\n const expanded = graph.expand(input);\n return expanded.startsWith(\"http\") ? expanded : undefined;\n}\n\n/**\n * Decide whether a node survives the scope filter, and if not, why.\n *\n * Rules, in the spirit of ADR 01014 (absence of a positive claim is not a\n * negative claim, so both polarities are explicit):\n * - An explicit negative (`graph:notApplicableToVariant` /\n * `graph:notSoftwareSubject`) naming the target **excludes** the node.\n * - A node that declares a positive set which omits the target is **excluded**\n * — it scoped itself elsewhere — recorded under the positive predicate so\n * the trace distinguishes this from an explicit negative.\n * - A node that makes no claim is **kept**: unscoped content applies broadly.\n */\nexport function scopeExclusion(\n graph: GraphIndex,\n iri: string,\n scope: { variantIri?: string; subjectIri?: string; language?: string },\n): ScopeExclusion | undefined {\n // [target, positive predicate, negative predicate, object kind]. Language\n // joins the same table with two differences, both deliberate: its objects are\n // literals, and it has **no negative predicate** — a document has one\n // language (`sh:maxCount 1`), so \"not in German\" is not a claim an author\n // makes and there is nothing for a `graph:not*` term to express (ADR 01037).\n const checks: Array<\n [string | undefined, string, string | undefined, \"iri\" | \"literal\"]\n > = [\n [\n scope.variantIri,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n \"iri\",\n ],\n [scope.subjectIri, IIRDS_HAS_SUBJECT, GRAPH_NOT_SOFTWARE_SUBJECT, \"iri\"],\n [scope.language, DCTERMS_LANGUAGE, undefined, \"literal\"],\n ];\n for (const [target, positive, negative, kind] of checks) {\n if (!target) continue;\n if (negative !== undefined) {\n const denied = graph\n .values(iri, negative)\n .some((v) => v.kind === kind && v.value === target);\n if (denied) return { node: iri, rule: negative, value: target };\n }\n\n // Language is the one dimension a section inherits. Applicability is\n // explicit-only by ADR 01013 — a section may legitimately scope itself\n // differently from its document — but a section's *text* is in its\n // document's language and cannot differ, and the per-locale indexes file it\n // that way (`partitionByLanguage`). Without this a link with an anchor\n // reaches a section directly (derive.ts mints section IRIs as\n // `dcterms:references` targets) and carries English prose past a `de`\n // filter that excluded the document it belongs to.\n const subject = positive === DCTERMS_LANGUAGE ? documentOf(iri) : iri;\n const claimed = graph.values(subject, positive);\n if (claimed.length > 0) {\n const matches = claimed.some(\n (v) => v.kind === kind && v.value === target,\n );\n if (!matches) return { node: iri, rule: positive, value: target };\n }\n }\n return undefined;\n}\n\n/** Breadth-first traversal with scope filtering and full trace recording. */\nexport function traverse(\n graph: GraphIndex,\n options: TraverseOptions,\n): TraverseResult {\n const trace = options.trace ?? createTrace();\n const maxDepth = options.depth ?? 1;\n const direction: Direction = options.direction ?? \"out\";\n const allowed =\n options.predicates && options.predicates.length > 0\n ? new Set(options.predicates.map((p) => graph.expand(p)))\n : undefined;\n\n const variantIri = options.variant\n ? resolveVariant(graph, options.variant)\n : undefined;\n const subjectIri = options.subject\n ? resolveSubject(graph, options.subject)\n : undefined;\n // Language needs no resolution step, only a spelling: the filter value and\n // the graph value are both BCP-47 tags, and `derive` writes the canonical one.\n const language =\n options.language === undefined\n ? undefined\n : canonicalLanguageTag(options.language);\n const scope = { variantIri, subjectIri, language };\n // A predicate list that names `rdf:type` asked for type edges. Dropping them\n // anyway answered a question nobody asked, with an empty result.\n const followTypes =\n options.includeTypeEdges === true || allowed?.has(RDF_TYPE) === true;\n\n const excluded = new Set<string>();\n const keep = (iri: string): boolean => {\n if (excluded.has(iri)) return false;\n const exclusion = scopeExclusion(graph, iri, scope);\n if (exclusion) {\n excluded.add(iri);\n trace.exclusions.push(exclusion);\n return false;\n }\n return true;\n };\n\n const nodes: TraversedNode[] = [];\n const seen = new Set<string>();\n let frontier: string[] = [];\n\n // A seed `findEntry` already recorded keeps its real provenance. Re-recording\n // it as `explicit`/1 would leave the trace answering \"why did retrieval start\n // here?\" twice, with the lexical/vector score contradicted by a flat 1.\n const alreadySeeded = new Set(trace.entry.map((e) => e.iri));\n\n for (const seed of [...options.seeds].sort(byCodeUnit)) {\n if (!graph.has(seed) || seen.has(seed)) continue;\n seen.add(seed);\n if (!alreadySeeded.has(seed)) {\n trace.entry.push({ iri: seed, score: 1, via: \"explicit\" });\n }\n // A seed always expands, even when the scope filter excludes it. The\n // filter governs what the walk *reaches*, not where the caller chose to\n // start — and the canonical query is exactly this shape: from an English\n // page, `--impact --lang de` asks what German content a change here\n // affects. Gating the seed made that return nothing at all, because the\n // seed excluded itself before the frontier was ever populated.\n //\n // It is still kept out of the results and recorded in the trace, so the\n // answer honors the filter even though the walk started outside it.\n if (keep(seed)) nodes.push({ iri: seed, depth: 0 });\n frontier.push(seed);\n }\n\n const limit = options.limit ?? Infinity;\n for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {\n const next: string[] = [];\n for (const from of frontier) {\n if (nodes.length >= limit) break;\n for (const { predicate, target, dir } of neighbors(\n graph,\n from,\n direction,\n )) {\n if (allowed && !allowed.has(predicate)) continue;\n if (!followTypes && predicate === RDF_TYPE) continue;\n if (isStatementData(graph, target)) continue;\n // The hop is recorded before filtering: the trace shows the edge was\n // walked even when the target is then scope-excluded.\n trace.hops.push({ from, predicate, to: target, depth, direction: dir });\n if (seen.has(target)) continue;\n seen.add(target);\n if (!keep(target)) continue;\n if (nodes.length >= limit) break;\n nodes.push({ iri: target, depth });\n next.push(target);\n }\n }\n frontier = next;\n }\n\n return { nodes, trace };\n}\n\nfunction neighbors(\n graph: GraphIndex,\n iri: string,\n direction: Direction,\n): Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> {\n const out: Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> =\n [];\n if (direction === \"out\" || direction === \"both\") {\n for (const e of graph.out(iri)) out.push({ ...e, dir: \"out\" });\n }\n if (direction === \"in\" || direction === \"both\") {\n for (const e of graph.in(iri)) out.push({ ...e, dir: \"in\" });\n }\n return out;\n}\n\n/** Who links to this node (one hop inbound over `dcterms:references`). */\nexport function reverseReferences(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\" | \"predicates\"> = {},\n): TraverseResult {\n return traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n predicates: [DCTERMS_REFERENCES],\n depth: options.depth ?? 1,\n });\n}\n\n/**\n * Transitive inbound reach — \"what is affected if this node changes\".\n * Excludes the node itself from the returned set. Defaults to depth 3 rather\n * than the walker's 1, because impact analysis is only useful transitively.\n */\nexport function impact(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\"> = {},\n): TraverseResult {\n const result = traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n depth: options.depth ?? 3,\n // The seed *may* occupy a slot in the walker's limit, so ask for one more:\n // `limit` means \"this many *affected* nodes\". Whether it actually takes\n // one depends on the scope filter — a seed the filter excludes still\n // expands but is not in `nodes` — so the slack is trimmed below rather\n // than assumed spent.\n limit: options.limit === undefined ? undefined : options.limit + 1,\n });\n const affected = result.nodes.filter((n) => n.iri !== iri);\n return {\n nodes:\n options.limit === undefined ? affected : affected.slice(0, options.limit),\n trace: result.trace,\n };\n}\n","/**\n * Served passages with their proof (proposal 0090): the cores every host\n * calls, the two seams a host supplies, and `createRetriever`, the script\n * surface.\n *\n * - `retrieve` ranks entry passages, walks outward from them, and assembles a\n * bundle within a character budget.\n * - `lookup` takes only a question. It picks the language, then returns three\n * full sections: the ranked matches, everything reached outward from them,\n * and everything that depends on them. Nothing is dropped; a passage past a\n * section's budget keeps its node and record and loses only its text.\n *\n * A host supplies a `VectorStore`, which ranks rows for a query, and a\n * `ChunkSource`, which reads rows by id. The CLI and `createRetriever` build\n * the same context over the same artifact, so both answer alike.\n *\n * Platform-neutral: no `node:` imports. Each language's rows name their own\n * model, and the query is embedded with the queried language's. The default\n * embedder loads each model from the sibling `graph/embed` file when a\n * language first needs it, and a host where that fails falls back to lexical\n * entry and says so in the trace.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { canonicalLanguageTag, parseLocalizations } from \"../core/localizations.js\";\nimport { normalize } from \"../core/vector-index.js\";\nimport type { Citation, ContextBlock, Refusal } from \"./assemble.js\";\nimport type { ChunkRow, ChunksManifest, ProvenanceRecord, WithholdReason } from \"./chunks.js\";\nimport { rrfMerge, type QueryEmbedder } from \"./entry.js\";\nimport { GraphIndex } from \"./graph.js\";\nimport { createLexicalIndex, type LexicalIndex } from \"./lexical.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type Hop,\n type QueryTrace,\n type Resolution,\n type ScopeExclusion,\n} from \"./trace.js\";\nimport { impact as impactWalk, resolveSubject, resolveVariant, traverse } from \"./traverse.js\";\nimport { searchIndexDigest } from \"./vector.js\";\n\n// ---- the seams ---------------------------------------------------------------\n\n/** One condition on a chunk row's `metadata`. A list field matches when it contains the value. */\nexport interface WhereCondition {\n field: string;\n value: string;\n}\n\n/** What a vector store is asked. `vector` is `null` when the host did not embed the query. */\nexport interface VectorStoreQuery {\n text: string;\n vector: number[] | null;\n k: number;\n language: string | null;\n /** Every condition must hold. Empty when the caller set none. */\n where: WhereCondition[];\n}\n\nexport interface VectorStoreMatch {\n id: string;\n score: number;\n /** The row, when the store holds it. Otherwise the id is read through the `ChunkSource`. */\n row?: ChunkRow;\n}\n\n/** Ranks chunk rows for a query. */\nexport interface VectorStore {\n query(q: VectorStoreQuery): Promise<VectorStoreMatch[]>;\n}\n\n/** Reads chunk rows by id, from one language or, with `null`, from every one. */\nexport interface ChunkSource {\n get(ids: string[], language: string | null): Promise<ChunkRow[]>;\n}\n\n/** A `fetch` as the runtime uses it: GET for files, POST for the HTTP store. */\nexport type RetrieverFetch = (\n url: string,\n init?: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n\n// ---- errors ------------------------------------------------------------------\n\n/** The rows or the graph were built from another graph than the manifest names. */\nexport class StaleArtifactError extends Error {\n constructor(manifestGraph: string, found: string, file = \"graph.jsonld\") {\n super(`chunks.json was built from graph ${manifestGraph}, and ${file} is ${found}; publish again.`);\n this.name = \"StaleArtifactError\";\n }\n}\n\n/** The query embedder is not the model the queried language's rows were embedded with. */\nexport class ModelMismatchError extends Error {\n readonly expected: string;\n readonly actual: string;\n constructor(expected: string, actual: string) {\n super(`chunks.json was embedded with ${expected}, and the embedder loads ${actual}.`);\n this.name = \"ModelMismatchError\";\n this.expected = expected;\n this.actual = actual;\n }\n}\n\n// ---- results -----------------------------------------------------------------\n\nexport type PassageRole = \"match\" | \"context\" | \"dependent\";\n\nexport interface WithheldNode {\n node: string;\n because: WithholdReason[];\n /** `export` when the rows left it out, `query` when this call did. */\n at: \"export\" | \"query\";\n}\n\nexport interface FilteredNode {\n node: string;\n /** The first `where` field the row did not satisfy. */\n field: string;\n}\n\n/** The trace a served result carries: the walk's, plus what the trust floor and the filter left out. */\nexport interface RetrievalTrace {\n entry: {\n /** The ranked entry candidates that became matches, or the node a walk started from. */\n candidates: EntryCandidate[];\n /** `\"lexical\"` when the vector path was wanted and unavailable. */\n fallback?: \"lexical\";\n /** On `lookup`: each language's best entry score. */\n languages?: Record<string, number>;\n /** On `lookup`: the language chosen. */\n chosen?: string;\n };\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n withheld: WithheldNode[];\n filtered: FilteredNode[];\n}\n\n/** One served passage in a bundle. */\nexport interface PassageBlock extends ContextBlock {\n title: string;\n page: string;\n provenance: ProvenanceRecord;\n role: PassageRole;\n}\n\n/** What `retrieve`, `traverse` and `impact` return. */\nexport interface PassageBundle {\n /** The question, on `retrieve`. */\n question?: string;\n /** The node the walk started from, on `traverse` and `impact`. */\n node?: string;\n language: string | null;\n context: PassageBlock[];\n citations: Citation[];\n /** The delivered fields of each cited page, once per page. */\n pages: Record<string, { metadata: Record<string, unknown> }>;\n trace: RetrievalTrace;\n /** Present when nothing could be served. `context` is then empty. */\n refusal?: Refusal;\n /** True when the budget dropped a passage. */\n truncated: boolean;\n}\n\nexport interface LookupPassage {\n iri: string;\n title: string;\n page: string;\n lines: string;\n /** `null` when the section's budget ran out before it. */\n text: string | null;\n truncated: boolean;\n provenance: ProvenanceRecord;\n}\n\nexport interface LookupMatch extends LookupPassage {\n rank: number;\n /** `null` where a path did not run, or did not rank the passage. */\n score: { lexical: number | null; vector: number | null; fused: number };\n}\n\nexport interface LookupReached extends LookupPassage {\n depth: number;\n}\n\n/** An edge in the graph's own direction. */\nexport interface LookupEdge {\n from: string;\n predicate: string;\n to: string;\n}\n\nexport interface LookupSection<P> {\n passages: P[];\n truncated: boolean;\n}\n\nexport interface LookupWalk extends LookupSection<LookupReached> {\n edges: LookupEdge[];\n}\n\n/** What `lookup` returns: three full sections, each with its proof. */\nexport interface LookupResult {\n question: string;\n language: string | null;\n matches: LookupSection<LookupMatch>;\n traversal: LookupWalk;\n impact: LookupWalk;\n pages: Record<string, { metadata: Record<string, unknown> }>;\n citations: Citation[];\n trace: RetrievalTrace;\n /** Present only when there are no matches, or every match was withheld. Every section is then empty. */\n refusal?: Refusal;\n}\n\n// ---- the context every core reads --------------------------------------------\n\n/** The model one language's rows were embedded with, as `chunks.json` records it. */\nexport interface EmbeddingModel {\n id: string;\n dimensions: number;\n}\n\nexport interface RetrieverContext {\n manifest: ChunksManifest;\n graph: GraphIndex;\n /** One language's lexical index, or `undefined` when it has none. */\n lexical(language: string): Promise<LexicalIndex | undefined>;\n store: VectorStore;\n chunks: ChunkSource;\n /** The query embedder for one model, or `null` to send no query vector. */\n embedder(model: EmbeddingModel): Promise<QueryEmbedder | null>;\n}\n\nexport type RetrieveMode = \"lexical\" | \"vector\" | \"hybrid\";\n\nexport interface RetrieveOptions {\n question: string;\n lang?: string;\n variant?: string;\n softwareSubject?: string;\n seeds?: number;\n depth?: number;\n maxChars?: number;\n mode?: RetrieveMode;\n /** Tightens the trust floor for this call. */\n withhold?: WithholdReason[];\n where?: WhereCondition[];\n}\n\nexport interface WalkOptions {\n node: string;\n /** Walk inward, to what depends on the node. */\n impact?: boolean;\n depth?: number;\n predicates?: string[];\n reverse?: boolean;\n lang?: string;\n variant?: string;\n softwareSubject?: string;\n limit?: number;\n maxChars?: number;\n withhold?: WithholdReason[];\n where?: WhereCondition[];\n}\n\nexport interface LookupOptions {\n question: string;\n /** The serve host's query-time floor. */\n withhold?: WithholdReason[];\n}\n\n/** The depth `graph traverse --impact` uses by default, and so `lookup`'s inward walk. */\nexport const IMPACT_DEPTH = 3;\n\n// ponytail: one fixed candidate pool per leg; raise it when filters routinely\n// exhaust the pool before `seeds` matches are found.\nconst ENTRY_POOL = 50;\n\n// ---- the trust floor and the filter --------------------------------------------\n\n/** Whether a record falls under one withhold reason. A stale verdict never counts. */\nexport function withholds(record: ProvenanceRecord, reason: WithholdReason): boolean {\n if (reason === \"drifted\") return record.pins.error > 0;\n return record.evals !== null && record.evals.current && record.evals.fail + record.evals.error > 0;\n}\n\n/** The first condition a row fails, or `undefined` when it meets them all. */\nfunction failedField(row: ChunkRow, where: readonly WhereCondition[]): string | undefined {\n for (const { field, value } of where) {\n const held = row.metadata[field];\n const values = Array.isArray(held) ? held : [held];\n if (!values.some((v) => v !== undefined && v !== null && scalarText(v) === value)) return field;\n }\n return undefined;\n}\n\nfunction scalarText(v: unknown): string {\n return typeof v === \"string\" ? v : JSON.stringify(v);\n}\n\n// ---- entry ---------------------------------------------------------------------\n\ninterface Ranked {\n iri: string;\n via: EntryVia;\n fused: number;\n lexical: number | null;\n vector: number | null;\n row?: ChunkRow;\n}\n\ninterface Entry {\n ranked: Ranked[];\n fallback: boolean;\n /** The lexical leg's best score, else the vector leg's: what `lookup` compares languages by. */\n best: number | undefined;\n}\n\nfunction modelOf(manifest: ChunksManifest, language: string): EmbeddingModel | null {\n return manifest.languages[language]?.model ?? null;\n}\n\nasync function rank(\n ctx: RetrieverContext,\n question: string,\n language: string,\n mode: RetrieveMode | undefined,\n where: WhereCondition[],\n): Promise<Entry> {\n const model = modelOf(ctx.manifest, language);\n const wantVector = mode === \"vector\" || mode === \"hybrid\" || (mode === undefined && model !== null);\n let vector: EntryCandidate[] = [];\n const storeRows = new Map<string, ChunkRow>();\n // A language with no model, in a corpus where another has one, enters\n // lexically as a host that cannot load the model does, and says so.\n let fallback =\n mode === undefined && model === null && Object.values(ctx.manifest.languages).some((l) => l.model !== null);\n if (wantVector && question.trim() !== \"\") {\n let queryVector: number[] | null = null;\n const embedder = model === null ? null : await ctx.embedder(model);\n if (model !== null && embedder !== null) {\n if (embedder.model !== model.id) throw new ModelMismatchError(model.id, embedder.model);\n queryVector = Array.from(await embedder.embed(question));\n }\n const found = await ctx.store.query({ text: question, vector: queryVector, k: ENTRY_POOL, language, where });\n for (const m of found) if (m.row !== undefined) storeRows.set(m.id, m.row);\n vector = found\n .map((m): EntryCandidate => ({ iri: m.id, score: m.score, via: \"vector\" }))\n .sort((a, b) => (a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score));\n fallback = queryVector === null && vector.length === 0;\n }\n let lexical: EntryCandidate[] = [];\n if (mode !== \"vector\" || fallback) {\n const index = await ctx.lexical(language);\n lexical = index?.search(question, { limit: ENTRY_POOL }) ?? [];\n }\n const lexicalScore = new Map(lexical.map((c) => [c.iri, c.score]));\n const vectorScore = new Map(vector.map((c) => [c.iri, c.score]));\n const ranked = rrfMerge([lexical, vector].filter((leg) => leg.length > 0)).map((c): Ranked => {\n const row = storeRows.get(c.iri);\n return {\n iri: c.iri,\n via: c.via,\n fused: c.score,\n lexical: lexicalScore.get(c.iri) ?? null,\n vector: vectorScore.get(c.iri) ?? null,\n ...(row === undefined ? {} : { row }),\n };\n });\n // Words shared with the question say which language it is in; a similarity\n // from a model trained on one language says less. So the lexical leg's best\n // score speaks for the language, and the vector leg's only without it.\n const best = lexical[0]?.score ?? vector[0]?.score;\n return { ranked, fallback, best };\n}\n\n// ---- rows ----------------------------------------------------------------------\n\n/** Reads rows and holds them to the manifest's graph. */\nasync function rowsFor(\n ctx: RetrieverContext,\n ids: readonly string[],\n language: string | null,\n): Promise<Map<string, ChunkRow>> {\n const out = new Map<string, ChunkRow>();\n if (ids.length === 0) return out;\n for (const row of await ctx.chunks.get([...ids], language)) {\n if (row.graph !== ctx.manifest.graph) {\n throw new StaleArtifactError(ctx.manifest.graph, row.graph, ctx.manifest.languages[row.language]?.file ?? \"a chunk row\");\n }\n out.set(row.id, row);\n }\n return out;\n}\n\nfunction chunkFile(ctx: RetrieverContext, language: string | null): string {\n return language === null ? \"\" : (ctx.manifest.languages[language]?.file ?? \"\");\n}\n\n/** What happened to one node on its way to being served. */\ntype Admission = { kind: \"row\"; row: ChunkRow } | { kind: \"withheld\" } | { kind: \"skipped\" };\n\n/**\n * One node through the trust floor, the filter and the chunk lookup, each\n * outcome traced. A node with no row and no export record is not a passage.\n */\nfunction admit(\n ctx: RetrieverContext,\n iri: string,\n row: ChunkRow | undefined,\n language: string | null,\n floor: { withhold: readonly WithholdReason[]; where: readonly WhereCondition[]; exported: ReadonlyMap<string, WithholdReason[]> },\n trace: RetrievalTrace,\n): Admission {\n const exported = floor.exported.get(iri);\n if (exported !== undefined) {\n trace.withheld.push({ node: iri, because: exported, at: \"export\" });\n return { kind: \"withheld\" };\n }\n const sourceUrl = row === undefined ? chunkFile(ctx, language) : chunkFile(ctx, row.language);\n if (row === undefined) {\n trace.resolutions.push({ iri, sourceUrl, ok: false, error: \"no chunk row\" });\n return { kind: \"skipped\" };\n }\n const field = failedField(row, floor.where);\n if (field !== undefined) {\n trace.filtered.push({ node: iri, field });\n return { kind: \"skipped\" };\n }\n const because = floor.withhold.filter((reason) => withholds(row.provenance, reason));\n if (because.length > 0) {\n trace.withheld.push({ node: iri, because, at: \"query\" });\n return { kind: \"withheld\" };\n }\n trace.resolutions.push({ iri, sourceUrl, ok: true });\n return { kind: \"row\", row };\n}\n\nfunction floorOf(\n ctx: RetrieverContext,\n withhold: readonly WithholdReason[] | undefined,\n where: readonly WhereCondition[] | undefined,\n): Parameters<typeof admit>[4] {\n return {\n withhold: withhold ?? [],\n where: where ?? [],\n exported: new Map(ctx.manifest.withheld.map((w) => [w.id, w.because])),\n };\n}\n\nfunction emptyTrace(): RetrievalTrace {\n return { entry: { candidates: [] }, hops: [], exclusions: [], resolutions: [], withheld: [], filtered: [] };\n}\n\ninterface Matched {\n ranked: Ranked;\n row: ChunkRow;\n rank: number;\n}\n\n/**\n * The top `seeds` passages among the ranked candidates. A candidate that is\n * not a passage, or that the filter rejects, gives its place to the next; a\n * withheld one keeps its place and is left out.\n */\nasync function selectMatches(\n ctx: RetrieverContext,\n entry: Entry,\n language: string,\n seeds: number,\n floor: Parameters<typeof admit>[4],\n trace: RetrievalTrace,\n): Promise<{ kept: Matched[]; withheld: number }> {\n const rows = await rowsFor(\n ctx,\n entry.ranked.filter((r) => r.row === undefined).map((r) => r.iri),\n language,\n );\n const kept: Matched[] = [];\n let withheld = 0;\n for (const ranked of entry.ranked) {\n if (kept.length + withheld >= seeds) break;\n const row = ranked.row ?? rows.get(ranked.iri);\n if (row !== undefined && row.graph !== ctx.manifest.graph) {\n throw new StaleArtifactError(ctx.manifest.graph, row.graph, chunkFile(ctx, language) || \"a chunk row\");\n }\n const admitted = admit(ctx, ranked.iri, row, language, floor, trace);\n if (admitted.kind === \"skipped\") continue;\n trace.entry.candidates.push({ iri: ranked.iri, score: ranked.fused, via: ranked.via });\n if (admitted.kind === \"withheld\") withheld += 1;\n else kept.push({ ranked, row: admitted.row, rank: kept.length + withheld + 1 });\n }\n // Ranks count the withheld places too, so a reader sees the gap.\n return { kept, withheld };\n}\n\n// ---- walks ---------------------------------------------------------------------\n\ninterface Reached {\n iri: string;\n depth: number;\n row: ChunkRow;\n}\n\n/** Copy a walk's events into the served trace. */\nfunction absorb(trace: RetrievalTrace, walked: QueryTrace): void {\n trace.hops.push(...walked.hops);\n trace.exclusions.push(...walked.exclusions);\n}\n\n/** Every reached node past the seeds that is a servable passage, in walk order. */\nasync function passagesOf(\n ctx: RetrieverContext,\n nodes: readonly { iri: string; depth: number }[],\n language: string | null,\n floor: Parameters<typeof admit>[4],\n trace: RetrievalTrace,\n): Promise<Reached[]> {\n const rows = await rowsFor(ctx, nodes.map((n) => n.iri), language);\n const out: Reached[] = [];\n for (const n of nodes) {\n const admitted = admit(ctx, n.iri, rows.get(n.iri), language, floor, trace);\n if (admitted.kind === \"row\") out.push({ iri: n.iri, depth: n.depth, row: admitted.row });\n }\n return out;\n}\n\n/** An edge as the graph holds it, from a hop in either direction. */\nfunction edgeOf(graph: GraphIndex, hop: Hop): LookupEdge {\n const predicate = graph.compact(hop.predicate);\n return hop.direction === \"out\"\n ? { from: hop.from, predicate, to: hop.to }\n : { from: hop.to, predicate, to: hop.from };\n}\n\n// ---- language and scope --------------------------------------------------------\n\nfunction languagesOf(manifest: ChunksManifest): string[] {\n return Object.keys(manifest.languages).sort(byCodeUnit);\n}\n\n/** The manifest's own spelling of a tag, matched in any case. */\nfunction languageNamed(manifest: ChunksManifest, tag: string): string | undefined {\n const wanted = canonicalLanguageTag(tag);\n return languagesOf(manifest).find((l) => canonicalLanguageTag(l) === wanted);\n}\n\nfunction refusal(reason: Refusal[\"reason\"], detail: string): Refusal {\n return { reason, detail };\n}\n\n/** The refusal an unresolvable scope earns, or `undefined` when every filter resolves. */\nfunction scopeRefusal(\n ctx: RetrieverContext,\n scope: { variant?: string; softwareSubject?: string; lang?: string },\n): Refusal | undefined {\n if (scope.variant !== undefined && resolveVariant(ctx.graph, scope.variant) === undefined) {\n return refusal(\"unknown-scope\", `No product variant matches ${scope.variant}.`);\n }\n if (scope.softwareSubject !== undefined && resolveSubject(ctx.graph, scope.softwareSubject) === undefined) {\n return refusal(\"unknown-scope\", `No software subject matches ${scope.softwareSubject}.`);\n }\n if (scope.lang !== undefined && languageNamed(ctx.manifest, scope.lang) === undefined) {\n const have = languagesOf(ctx.manifest).join(\", \") || \"none\";\n return refusal(\"unknown-scope\", `No localization ${scope.lang}; this corpus has ${have}.`);\n }\n return undefined;\n}\n\n// ---- assembly ------------------------------------------------------------------\n\nfunction pagesOf(\n manifest: ChunksManifest,\n pages: Iterable<string>,\n): Record<string, { metadata: Record<string, unknown> }> {\n const out: Record<string, { metadata: Record<string, unknown> }> = {};\n for (const page of [...new Set(pages)].sort(byCodeUnit)) {\n out[page] = { metadata: manifest.pages[page]?.metadata ?? {} };\n }\n return out;\n}\n\n/** Blocks in order within the budget; a block past it is dropped, as `assemble` drops it. */\nfunction bundleOf(\n ctx: RetrieverContext,\n head: { question: string } | { node: string },\n language: string | null,\n items: readonly { row: ChunkRow; depth: number; role: PassageRole }[],\n maxChars: number,\n trace: RetrievalTrace,\n empty: Refusal,\n): PassageBundle {\n const base = { ...head, language, trace };\n if (items.length === 0) {\n return { ...base, context: [], citations: [], pages: {}, truncated: false, refusal: empty };\n }\n const context: PassageBlock[] = [];\n let used = 0;\n let truncated = false;\n for (const { row, depth, role } of items) {\n if (used + row.text.length > maxChars) {\n truncated = true;\n continue;\n }\n used += row.text.length;\n context.push({\n iri: row.id,\n title: row.title,\n text: row.text,\n sourceUrl: row.page,\n depth,\n page: row.page,\n provenance: row.provenance,\n role,\n });\n }\n if (context.length === 0) {\n return {\n ...base,\n context: [],\n citations: [],\n pages: {},\n truncated,\n refusal: refusal(\"no-content\", \"Every matching passage exceeded the character budget.\"),\n };\n }\n return {\n ...base,\n context,\n citations: context.map((b) => ({ iri: b.iri, title: b.title, sourceUrl: b.sourceUrl })),\n pages: pagesOf(ctx.manifest, context.map((b) => b.page)),\n truncated,\n };\n}\n\n/** Lay a section's passages against its budget: past it, a passage keeps all but its text. */\nfunction budget(passages: { text: string | null; truncated: boolean }[], maxChars: number): boolean {\n let used = 0;\n let cut = false;\n for (const p of passages) {\n const n = p.text?.length ?? 0;\n if (used + n > maxChars) {\n p.text = null;\n p.truncated = true;\n cut = true;\n } else {\n used += n;\n }\n }\n return cut;\n}\n\nfunction passageOf(row: ChunkRow): LookupPassage {\n return {\n iri: row.id,\n title: row.title,\n page: row.page,\n lines: row.lines,\n text: row.text,\n truncated: false,\n provenance: row.provenance,\n };\n}\n\n// ---- the cores -----------------------------------------------------------------\n\n/** Rank, choose, walk outward, assemble: the bundle a steering caller asked for. */\nexport async function retrieve(input: RetrieverContext & RetrieveOptions): Promise<PassageBundle> {\n const ctx = input;\n const trace = emptyTrace();\n const settings = ctx.manifest.retrieve;\n const seeds = input.seeds ?? settings.seeds;\n const depth = input.depth ?? settings.depth;\n const maxChars = input.maxChars ?? settings.maxChars;\n const head = { question: input.question };\n const refuse = (r: Refusal, language: string | null): PassageBundle =>\n bundleOf(ctx, head, language, [], maxChars, trace, r);\n\n const scope = scopeRefusal(ctx, input);\n if (scope !== undefined) return refuse(scope, null);\n const languages = languagesOf(ctx.manifest);\n const language = input.lang === undefined ? languages[0] : languageNamed(ctx.manifest, input.lang);\n if (input.lang === undefined && languages.length > 1) {\n return refuse(\n refusal(\"lang-required\", `This corpus has more than one localization (${languages.join(\", \")}); pass lang to choose one.`),\n null,\n );\n }\n if (language === undefined) return refuse(refusal(\"no-route\", \"This artifact holds no passages.\"), null);\n\n const where = input.where ?? [];\n const entry = await rank(ctx, input.question, language, input.mode, where);\n if (entry.fallback) trace.entry.fallback = \"lexical\";\n const floor = floorOf(ctx, input.withhold, where);\n const { kept, withheld } = await selectMatches(ctx, entry, language, seeds, floor, trace);\n if (kept.length === 0) {\n return refuse(\n withheld > 0\n ? refusal(\"withheld\", \"Every match was withheld by the trust floor; trace.withheld names them.\")\n : refusal(\"no-route\", \"No passage in the docs matches this question.\"),\n language,\n );\n }\n\n const walked = createTrace();\n const { nodes } = traverse(ctx.graph, {\n seeds: kept.map((m) => m.row.id),\n depth,\n direction: \"out\",\n ...(input.variant === undefined ? {} : { variant: input.variant }),\n ...(input.softwareSubject === undefined ? {} : { subject: input.softwareSubject }),\n language,\n trace: walked,\n });\n absorb(trace, walked);\n const inScope = new Set(nodes.filter((n) => n.depth === 0).map((n) => n.iri));\n const reached = await passagesOf(ctx, nodes.filter((n) => n.depth > 0), language, floor, trace);\n const items = [\n ...kept.filter((m) => inScope.has(m.row.id)).map((m) => ({ row: m.row, depth: 0, role: \"match\" as const })),\n ...reached.map((r) => ({ row: r.row, depth: r.depth, role: \"context\" as const })),\n ];\n return bundleOf(ctx, head, language, items, maxChars, trace, refusal(\"no-route\", \"Every match is outside the requested scope.\"));\n}\n\n/** A walk from one node, as a bundle: `traverse`, or `impact` with `impact: true`. */\nexport async function walkPassages(input: RetrieverContext & WalkOptions): Promise<PassageBundle> {\n const ctx = input;\n const trace = emptyTrace();\n const maxChars = input.maxChars ?? ctx.manifest.retrieve.maxChars;\n const node = ctx.graph.expand(input.node);\n const head = { node };\n const refuse = (r: Refusal): PassageBundle => bundleOf(ctx, head, null, [], maxChars, trace, r);\n if (!ctx.graph.has(node)) return refuse(refusal(\"unknown-node\", `No node ${input.node} in the graph.`));\n const scope = scopeRefusal(ctx, input);\n if (scope !== undefined) return refuse(scope);\n const language = input.lang === undefined ? null : (languageNamed(ctx.manifest, input.lang) ?? null);\n\n const walked = createTrace();\n const options = {\n ...(input.depth === undefined ? {} : { depth: input.depth }),\n ...(input.predicates === undefined ? {} : { predicates: input.predicates }),\n ...(input.variant === undefined ? {} : { variant: input.variant }),\n ...(input.softwareSubject === undefined ? {} : { subject: input.softwareSubject }),\n ...(input.lang === undefined ? {} : { language: input.lang }),\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n trace: walked,\n };\n const { nodes } =\n input.impact === true\n ? impactWalk(ctx.graph, node, options)\n : traverse(ctx.graph, { ...options, seeds: [node], direction: input.reverse === true ? \"in\" : \"out\" });\n absorb(trace, walked);\n trace.entry.candidates.push({ iri: node, score: 1, via: \"explicit\" });\n\n const floor = floorOf(ctx, input.withhold, input.where);\n const start = await passagesOf(ctx, [{ iri: node, depth: 0 }], language, floor, trace);\n const reached = await passagesOf(ctx, nodes.filter((n) => n.iri !== node), language, floor, trace);\n const inward = input.impact === true || input.reverse === true;\n const items = [\n ...start.map((r) => ({ row: r.row, depth: 0, role: \"match\" as const })),\n ...reached.map((r) => ({ row: r.row, depth: r.depth, role: inward ? (\"dependent\" as const) : (\"context\" as const) })),\n ];\n const languageOut = language ?? start[0]?.row.language ?? null;\n return bundleOf(\n ctx,\n head,\n languageOut,\n items,\n maxChars,\n trace,\n refusal(\"no-route\", \"No passage was reachable from this node under the active scope filter.\"),\n );\n}\n\n/**\n * The one call: a question in, three full sections out. It enters every\n * localization, keeps the one whose best match scores highest, and never asks\n * for a language.\n */\nexport async function lookup(input: RetrieverContext & LookupOptions): Promise<LookupResult> {\n const ctx = input;\n const trace = emptyTrace();\n const { seeds, depth, maxChars } = ctx.manifest.retrieve;\n const empty = (language: string | null, r: Refusal): LookupResult => ({\n question: input.question,\n language,\n matches: { passages: [], truncated: false },\n traversal: { passages: [], edges: [], truncated: false },\n impact: { passages: [], edges: [], truncated: false },\n pages: {},\n citations: [],\n trace,\n refusal: r,\n });\n\n // The language first, by its lexical scores, so only its model loads. With\n // no lexical match anywhere, each language's vector leg speaks for it.\n const choose = async (mode: RetrieveMode | undefined) => {\n const scores: Record<string, number> = {};\n let chosen: { language: string; entry: Entry; best: number } | undefined;\n for (const language of languagesOf(ctx.manifest)) {\n const entry = await rank(ctx, input.question, language, mode, []);\n if (entry.best === undefined) continue;\n scores[language] = entry.best;\n if (chosen === undefined || entry.best > chosen.best) chosen = { language, entry, best: entry.best };\n }\n return { scores, chosen };\n };\n let picked = await choose(\"lexical\");\n if (picked.chosen === undefined) picked = await choose(undefined);\n else picked.chosen.entry = await rank(ctx, input.question, picked.chosen.language, undefined, []);\n trace.entry.languages = picked.scores;\n if (picked.chosen === undefined) return empty(null, refusal(\"no-route\", \"No passage in the docs matches this question.\"));\n const { language, entry } = picked.chosen;\n trace.entry.chosen = language;\n if (entry.fallback) trace.entry.fallback = \"lexical\";\n\n const floor = floorOf(ctx, input.withhold, []);\n const { kept, withheld } = await selectMatches(ctx, entry, language, seeds, floor, trace);\n if (kept.length === 0) {\n return empty(\n language,\n withheld > 0\n ? refusal(\"withheld\", \"Every match was withheld by the trust floor; trace.withheld names them.\")\n : refusal(\"no-route\", \"No passage in the docs matches this question.\"),\n );\n }\n\n const seedIris = kept.map((m) => m.row.id);\n const walk = async (direction: \"out\" | \"in\", reach: number): Promise<LookupWalk> => {\n const walked = createTrace();\n const { nodes } = traverse(ctx.graph, { seeds: seedIris, depth: reach, direction, language, trace: walked });\n absorb(trace, walked);\n const reached = await passagesOf(ctx, nodes.filter((n) => n.depth > 0), language, floor, trace);\n const passages = reached.map((r): LookupReached => ({ ...passageOf(r.row), depth: r.depth }));\n return {\n passages,\n edges: walked.hops.map((h) => edgeOf(ctx.graph, h)),\n truncated: budget(passages, maxChars),\n };\n };\n\n const matches = kept.map(\n (m): LookupMatch => ({\n ...passageOf(m.row),\n rank: m.rank,\n score: { lexical: m.ranked.lexical, vector: m.ranked.vector, fused: m.ranked.fused },\n }),\n );\n const matchesTruncated = budget(matches, maxChars);\n const traversal = await walk(\"out\", depth);\n const impact = await walk(\"in\", IMPACT_DEPTH);\n\n const served = [...matches, ...traversal.passages, ...impact.passages];\n const citations: Citation[] = [];\n const cited = new Set<string>();\n for (const p of served) {\n if (p.text === null || cited.has(p.iri)) continue;\n cited.add(p.iri);\n citations.push({ iri: p.iri, title: p.title, sourceUrl: p.page });\n }\n return {\n question: input.question,\n language,\n matches: { passages: matches, truncated: matchesTruncated },\n traversal,\n impact,\n pages: pagesOf(ctx.manifest, served.map((p) => p.page)),\n citations,\n trace,\n };\n}\n\n// ---- the shipped seams and parsers -------------------------------------------------\n\n/** Ranks rows by cosine in memory, among those meeting `where`. Rows without a vector are never ranked. */\nexport function createStaticVectorStore(rows: readonly ChunkRow[]): VectorStore {\n return {\n query(q) {\n if (q.vector === null) return Promise.resolve([]);\n const query = normalize(Float32Array.from(q.vector));\n const scored: VectorStoreMatch[] = [];\n for (const row of rows) {\n if (row.vector === undefined || row.vector.length !== query.length) continue;\n if (q.language !== null && row.language !== q.language) continue;\n // Before the `k` cut, as a server store does, so a strict filter cannot starve the pool.\n if (failedField(row, q.where) !== undefined) continue;\n const stored = normalize(Float32Array.from(row.vector));\n let score = 0;\n for (const [i, value] of query.entries()) score += value * (stored[i] ?? 0);\n scored.push({ id: row.id, score, row });\n }\n scored.sort((a, b) => (a.score === b.score ? byCodeUnit(a.id, b.id) : b.score - a.score));\n return Promise.resolve(scored.slice(0, q.k));\n },\n };\n}\n\n/**\n * A store behind a site's own server. It POSTs `{ text, vector, k, language,\n * where }` as JSON and expects `{ matches: [{ id, score, row? }] }`.\n */\nexport function createHttpVectorStore(options: { url: string; fetch?: RetrieverFetch }): VectorStore {\n const doFetch = options.fetch ?? defaultFetch;\n return {\n async query(q) {\n const response = await doFetch(options.url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ text: q.text, vector: q.vector, k: q.k, language: q.language, where: q.where }),\n });\n if (!response.ok) throw new Error(`${options.url} answered HTTP ${String(response.status)}.`);\n const body = JSON.parse(await response.text()) as { matches?: unknown };\n if (!Array.isArray(body.matches)) throw new Error(`${options.url} returned no matches array.`);\n return body.matches.filter(isMatch);\n },\n };\n}\n\nfunction isMatch(m: unknown): m is VectorStoreMatch {\n if (typeof m !== \"object\" || m === null) return false;\n const o = m as Record<string, unknown>;\n return typeof o.id === \"string\" && typeof o.score === \"number\";\n}\n\n/** The rows of one `chunks.<tag>.jsonl`, for ingestion into a vector DB. */\nexport function parseChunkRows(text: string): ChunkRow[] {\n const rows: ChunkRow[] = [];\n for (const [i, line] of text.split(/\\r?\\n/).entries()) {\n if (line.trim() === \"\") continue;\n const row: unknown = JSON.parse(line);\n if (!isChunkRow(row)) throw new Error(`Line ${String(i + 1)} is not a chunk row.`);\n rows.push(row);\n }\n return rows;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The fields the cores read, so a damaged row fails here and not deep in a query. */\nfunction isChunkRow(v: unknown): v is ChunkRow {\n return (\n isRecord(v) &&\n [\"id\", \"graph\", \"page\", \"lines\", \"language\", \"title\", \"text\"].every((k) => typeof v[k] === \"string\") &&\n (v.vector === undefined || Array.isArray(v.vector)) &&\n isRecord(v.metadata) &&\n isRecord(v.provenance)\n );\n}\n\n/** `chunks.json`, checked to be one, down to the fields the cores read. */\nexport function parseChunksManifest(input: string | object): ChunksManifest {\n const doc: unknown = typeof input === \"string\" ? JSON.parse(input) : input;\n const valid =\n isRecord(doc) &&\n doc.format === \"manni-graph-chunks\" &&\n doc.version === 1 &&\n [\"graph\", \"graphFile\", \"searchIndex\"].every((k) => typeof doc[k] === \"string\") &&\n !(\"model\" in doc) &&\n isRecord(doc.retrieve) &&\n isRecord(doc.pages) &&\n Array.isArray(doc.withheld) &&\n isRecord(doc.languages) &&\n Object.values(doc.languages).every((l) => isRecord(l) && typeof l.file === \"string\" && isModel(l.model));\n if (!valid) throw new Error('Not a manni graph chunk manifest: expected format \"manni-graph-chunks\", version 1.');\n return doc as unknown as ChunksManifest;\n}\n\nfunction isModel(v: unknown): boolean {\n return v === null || (isRecord(v) && typeof v.id === \"string\" && typeof v.dimensions === \"number\");\n}\n\n/** Reads one `chunks.<tag>.jsonl`, given as its text or its URL. */\nexport function createChunkFileSource(textOrUrl: string, options: { fetch?: RetrieverFetch } = {}): ChunkSource {\n const isText = textOrUrl.trim() === \"\" || textOrUrl.trimStart().startsWith(\"{\");\n let rows: Promise<ChunkRow[]> | undefined;\n const load = (): Promise<ChunkRow[]> =>\n (rows ??= isText\n ? Promise.resolve(parseChunkRows(textOrUrl))\n : fetchText(options.fetch ?? defaultFetch, textOrUrl).then(parseChunkRows));\n return {\n async get(ids, language) {\n const want = new Set(ids);\n return (await load()).filter((r) => want.has(r.id) && (language === null || r.language === language));\n },\n };\n}\n\n// ---- the context, from an artifact -------------------------------------------------\n\nfunction defaultFetch(url: string, init?: Parameters<RetrieverFetch>[1]): ReturnType<RetrieverFetch> {\n return globalThis.fetch(url, init);\n}\n\nasync function fetchText(doFetch: RetrieverFetch, url: string): Promise<string> {\n const response = await doFetch(url);\n if (!response.ok) throw new Error(`${url} answered HTTP ${String(response.status)}.`);\n return response.text();\n}\n\n/**\n * The context over one artifact, with `read` resolving a path relative to the\n * manifest. The CLI reads files and `createRetriever` fetches, through this\n * one function, so both serve the same rows, stores and indexes.\n */\nexport function artifactContext(\n manifest: ChunksManifest,\n graph: GraphIndex,\n read: (path: string) => Promise<string>,\n seams: { store?: VectorStore; chunks?: ChunkSource; embedder: RetrieverContext[\"embedder\"] },\n): RetrieverContext {\n // Each model loads once, when a language that needs it is first queried.\n const embedders = new Map<string, Promise<QueryEmbedder | null>>();\n const embedder = (model: EmbeddingModel): Promise<QueryEmbedder | null> => {\n let pending = embedders.get(model.id);\n if (pending === undefined) {\n pending = seams.embedder(model);\n embedders.set(model.id, pending);\n }\n return pending;\n };\n\n const loaded = new Map<string, Promise<ChunkRow[]>>();\n const rowsOf = (language: string): Promise<ChunkRow[]> => {\n let pending = loaded.get(language);\n if (pending === undefined) {\n const entry = manifest.languages[language];\n pending = entry === undefined ? Promise.resolve([]) : read(entry.file).then(parseChunkRows);\n loaded.set(language, pending);\n }\n return pending;\n };\n const allRows = async (language: string | null): Promise<ChunkRow[]> =>\n language === null ? (await Promise.all(languagesOf(manifest).map(rowsOf))).flat() : rowsOf(language);\n\n const chunks: ChunkSource = seams.chunks ?? {\n async get(ids, language) {\n const want = new Set(ids);\n return (await allRows(language)).filter((r) => want.has(r.id));\n },\n };\n const store: VectorStore = seams.store ?? {\n async query(q) {\n return createStaticVectorStore(await allRows(q.language)).query(q);\n },\n };\n\n let localizations: Promise<ReturnType<typeof parseLocalizations>> | undefined;\n const lexicons = new Map<string, Promise<LexicalIndex | undefined>>();\n const lexical = (language: string): Promise<LexicalIndex | undefined> => {\n let pending = lexicons.get(language);\n if (pending === undefined) {\n pending = (async () => {\n localizations ??= read(manifest.searchIndex).then(parseLocalizations);\n const doc = await localizations;\n const wanted = canonicalLanguageTag(language);\n const entry = doc?.languages.find((l) => canonicalLanguageTag(l.language) === wanted);\n return entry === undefined ? undefined : createLexicalIndex(await read(entry.search.path));\n })();\n lexicons.set(language, pending);\n }\n return pending;\n };\n\n return { manifest, graph, lexical, store, chunks, embedder };\n}\n\n// ---- the script surface --------------------------------------------------------------\n\nexport interface CreateRetrieverOptions {\n /** `chunks.json`: its URL, or the parsed manifest. Every other file resolves from its directory. */\n manifest: string | object;\n /** Default: the static store over the rows' vectors. */\n store?: VectorStore;\n /** Default: the chunk files the manifest names. */\n chunks?: ChunkSource;\n /** Default: `graph/embed` with each language's model, loaded when first queried. `false` forces lexical entry. */\n embed?: QueryEmbedder | false;\n /** Default: the global `fetch`. */\n fetch?: RetrieverFetch;\n}\n\n/**\n * The cores over one artifact. `withhold` on `retrieve`, `traverse` and\n * `impact` tightens the floor the artifact was exported with, per call, as\n * the CLI's `--withhold` does. It never lowers it: exported rows stay out.\n * `lookup` takes only a question and serves the exported floor.\n */\nexport interface Retriever {\n readonly manifest: ChunksManifest;\n lookup(question: string): Promise<LookupResult>;\n retrieve(\n question: string,\n options?: Pick<\n RetrieveOptions,\n \"lang\" | \"variant\" | \"softwareSubject\" | \"depth\" | \"maxChars\" | \"mode\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n traverse(\n node: string,\n options?: Pick<\n WalkOptions,\n \"depth\" | \"predicates\" | \"reverse\" | \"lang\" | \"variant\" | \"softwareSubject\" | \"limit\" | \"maxChars\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n impact(\n node: string,\n options?: Pick<\n WalkOptions,\n \"depth\" | \"lang\" | \"variant\" | \"softwareSubject\" | \"limit\" | \"maxChars\" | \"where\" | \"withhold\"\n >,\n ): Promise<PassageBundle>;\n}\n\ninterface EmbedModule {\n createLocalEmbedder(o: { model: string; role: \"query\" }): Promise<QueryEmbedder>;\n createMockEmbedder(o: { dims: number }): QueryEmbedder;\n}\n\n/**\n * One language's model, loaded from the `graph/embed` file beside this one.\n * The specifier is not a literal, so a bundler leaves it alone, and a host\n * that cannot load it gets `null`: lexical entry, traced as a fallback.\n */\nasync function defaultEmbedder(model: EmbeddingModel): Promise<QueryEmbedder | null> {\n try {\n const specifier = \"./embed.js\";\n const embed = (await import(/* @vite-ignore */ specifier)) as EmbedModule;\n return model.id === \"mock\"\n ? embed.createMockEmbedder({ dims: model.dimensions })\n : await embed.createLocalEmbedder({ model: model.id, role: \"query\" });\n } catch {\n return null;\n }\n}\n\n/** The retrieval cores over a published artifact. Returns data and calls no model but the embedder. */\nexport async function createRetriever(options: CreateRetrieverOptions): Promise<Retriever> {\n const doFetch = options.fetch ?? defaultFetch;\n const fromUrl = typeof options.manifest === \"string\";\n const manifest = parseChunksManifest(\n typeof options.manifest === \"string\" ? await fetchText(doFetch, options.manifest) : options.manifest,\n );\n const base = typeof options.manifest === \"string\" ? options.manifest.slice(0, options.manifest.lastIndexOf(\"/\") + 1) : \"\";\n const resolvePath = (path: string): string => (fromUrl && !/^[a-z][a-z0-9+.-]*:/i.test(path) ? base + path : path);\n const read = (path: string): Promise<string> => fetchText(doFetch, resolvePath(path));\n\n const graphText = await read(manifest.graphFile);\n const digest = `sha256-${(await searchIndexDigest(graphText)).slice(\"sha256:\".length)}`;\n if (digest !== manifest.graph) throw new StaleArtifactError(manifest.graph, digest);\n const graph = GraphIndex.fromJsonLd(graphText);\n\n const embed = options.embed;\n const embedder: RetrieverContext[\"embedder\"] =\n embed === false ? () => Promise.resolve(null) : embed === undefined ? defaultEmbedder : () => Promise.resolve(embed);\n const ctx = artifactContext(manifest, graph, read, {\n ...(options.store === undefined ? {} : { store: options.store }),\n ...(options.chunks === undefined ? {} : { chunks: options.chunks }),\n embedder,\n });\n\n return {\n manifest,\n lookup: (question) => lookup({ ...ctx, question }),\n retrieve: (question, o = {}) => retrieve({ ...ctx, ...o, question }),\n traverse: (node, o = {}) => walkPassages({ ...ctx, ...o, node }),\n impact: (node, o = {}) => walkPassages({ ...ctx, ...o, node, impact: true }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,IAAM,QAAQ,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,EAAI,CAAC;AAIrD,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AA8Bf,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,UAAU,QAAoC;AAC5D,MAAI,MAAM;AAGV,aAAW,SAAS,OAAQ,QAAO,QAAQ;AAC3C,MAAI,QAAQ,EAAG,QAAO;AACtB,QAAM,MAAM,IAAI,KAAK,KAAK,GAAG;AAG7B,SAAO,IAAI,OAAO,IAAI,CAAC,UAAU,QAAQ,GAAG,CAAC;AAC7C,SAAO;AACT;AAMO,SAAS,kBACd,SACA,MACY;AACZ,QAAM,SAAS,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,IAAI,EAAE,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