agentic-qe 3.15.11 → 3.15.12
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/.claude/hooks/aqe-hook.cjs +38 -2
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +149 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-HL7MOCQN.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-TIDSQ3ZK.js → agent-booster-wasm-5VZCKTIJ.js} +2 -2
- package/dist/cli/chunks/{agent-handler-G3EPBVA7.js → agent-handler-K3C6CQCD.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-ARC5C7GW.js → agent-memory-branch-NVFQ25WS.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-OZ2DXB4G.js +2 -0
- package/dist/cli/chunks/{arena-K4I4QDXB.js → arena-QGWIJADQ.js} +2 -2
- package/dist/cli/chunks/{arena-36DTATJV.js → arena-TSZVDSXS.js} +4 -4
- package/dist/cli/chunks/{audit-WQSJSJZF.js → audit-KIEE2SHJ.js} +3 -3
- package/dist/cli/chunks/base-WIM7G3HC.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-BB4K67MT.js → better-sqlite3-BNB32NW3.js} +2 -2
- package/dist/cli/chunks/{brain-handler-CU3GOIU3.js → brain-handler-MPC5SPYI.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-NJQX7ZNB.js → branch-enumerator-LZ7UXKAY.js} +2 -2
- package/dist/cli/chunks/{browser-6YJF4FQW.js → browser-VDHAW4RK.js} +2 -2
- package/dist/cli/chunks/browser-workflow-QRKCFVR3.js +2 -0
- package/dist/cli/chunks/{chunk-V7DA4HAK.js → chunk-23PQF7NN.js} +1 -1
- package/dist/cli/chunks/{chunk-IENZSO3K.js → chunk-26672ISV.js} +2 -2
- package/dist/cli/chunks/{chunk-OURITHFV.js → chunk-2ASQRBK2.js} +2 -2
- package/dist/cli/chunks/{chunk-VBK2YAYY.js → chunk-2E2QO44T.js} +2 -2
- package/dist/cli/chunks/{chunk-NT7JRHMH.js → chunk-2IVE5AR3.js} +1 -1
- package/dist/cli/chunks/{chunk-672XOJDG.js → chunk-2JYUA27M.js} +1 -1
- package/dist/cli/chunks/{chunk-OHR7C777.js → chunk-2PPSS4JD.js} +2 -2
- package/dist/cli/chunks/{chunk-FUYOOKTH.js → chunk-32UTHIY5.js} +3 -3
- package/dist/cli/chunks/{chunk-UKKYMW3S.js → chunk-33I2ZP6E.js} +2 -2
- package/dist/cli/chunks/{chunk-76SNL7GU.js → chunk-35MIUSXQ.js} +2 -2
- package/dist/cli/chunks/{chunk-4X4MWMHB.js → chunk-35NW676P.js} +2 -2
- package/dist/cli/chunks/{chunk-BZPE3LDO.js → chunk-3EWQN37E.js} +2 -2
- package/dist/cli/chunks/{chunk-5N25I53C.js → chunk-3IU4LDZR.js} +2 -2
- package/dist/cli/chunks/{chunk-NKTWKYHB.js → chunk-47RMGDG4.js} +2 -2
- package/dist/cli/chunks/chunk-4A76VPU4.js +3 -0
- package/dist/cli/chunks/{chunk-4RH5I24Q.js → chunk-4CB3QPZM.js} +2 -2
- package/dist/cli/chunks/{chunk-U3LJNNVJ.js → chunk-4HWUECVD.js} +2 -2
- package/dist/cli/chunks/{chunk-T5KHJ3J7.js → chunk-4KUOYDY2.js} +2 -2
- package/dist/cli/chunks/{chunk-XNLIWQYE.js → chunk-4LWMAAWK.js} +2 -2
- package/dist/cli/chunks/{chunk-KKYO2NKV.js → chunk-4PU5GTZW.js} +2 -2
- package/dist/cli/chunks/{chunk-VWUZSNVC.js → chunk-4SA7M34P.js} +1 -1
- package/dist/cli/chunks/{chunk-5WYZHDIZ.js → chunk-4Y6OEBJZ.js} +1 -1
- package/dist/cli/chunks/{chunk-J4JMCZVA.js → chunk-5A66EGEW.js} +2 -2
- package/dist/cli/chunks/{chunk-HFFPYC4G.js → chunk-5ADXFUMO.js} +2 -2
- package/dist/cli/chunks/{chunk-KJCIMNHS.js → chunk-5S4UIDFK.js} +1 -1
- package/dist/cli/chunks/{chunk-YBBT3YYG.js → chunk-5TAEW5OV.js} +1 -1
- package/dist/cli/chunks/{chunk-FLU5FDSC.js → chunk-5Z23ZMXZ.js} +59 -59
- package/dist/cli/chunks/{chunk-YNOCQ2SL.js → chunk-65TH6RPD.js} +1 -1
- package/dist/cli/chunks/{chunk-XGPTZUKQ.js → chunk-66PXR3NI.js} +2 -2
- package/dist/cli/chunks/{chunk-ITPGWGQS.js → chunk-6E6HB4N4.js} +4 -4
- package/dist/cli/chunks/{chunk-EJPK7OTR.js → chunk-6QRI3JVE.js} +2 -2
- package/dist/cli/chunks/{chunk-ZP75ASUU.js → chunk-7DNR4KKR.js} +1 -1
- package/dist/cli/chunks/{chunk-V5AADCBC.js → chunk-7JFDLL2F.js} +1 -1
- package/dist/cli/chunks/chunk-7OEFBWAG.js +5 -0
- package/dist/cli/chunks/{chunk-EIDJNT5C.js → chunk-7QEUHNKO.js} +1 -1
- package/dist/cli/chunks/{chunk-7R5HC56U.js → chunk-7TA5MUPW.js} +1 -1
- package/dist/cli/chunks/{chunk-LCVEEII4.js → chunk-A2JCRXTK.js} +2 -2
- package/dist/cli/chunks/{chunk-JUMICXM6.js → chunk-A5Y7DAVQ.js} +2 -2
- package/dist/cli/chunks/{chunk-FZHSG75I.js → chunk-ADUAJIAU.js} +2 -2
- package/dist/cli/chunks/{chunk-TFW7CCKS.js → chunk-AJEXPFAB.js} +1 -1
- package/dist/cli/chunks/{chunk-JGJXXAS6.js → chunk-BC4T6SCV.js} +4 -4
- package/dist/cli/chunks/{chunk-4RAQ7PJA.js → chunk-BMG2JLSQ.js} +2 -2
- package/dist/cli/chunks/{chunk-Y7B5EUIJ.js → chunk-BOSMELJX.js} +2 -2
- package/dist/cli/chunks/{chunk-CIAL4YRY.js → chunk-BYRCB5JT.js} +2 -2
- package/dist/cli/chunks/{chunk-XS2XF3YG.js → chunk-C3YOVASQ.js} +1 -1
- package/dist/cli/chunks/{chunk-FL32MTKT.js → chunk-C74M4WUI.js} +2 -2
- package/dist/cli/chunks/{chunk-S6IYEBAI.js → chunk-CA5UNWQF.js} +2 -2
- package/dist/cli/chunks/{chunk-5MTWCCZJ.js → chunk-CDA5Z74H.js} +2 -2
- package/dist/cli/chunks/{chunk-DOFREOPQ.js → chunk-CPIBIR3X.js} +2 -2
- package/dist/cli/chunks/{chunk-UMVSWQNB.js → chunk-CU36D7TN.js} +2 -2
- package/dist/cli/chunks/{chunk-G4CKPWF6.js → chunk-DAUEK66C.js} +1 -1
- package/dist/cli/chunks/{chunk-2KFFEKSI.js → chunk-DRCBRUGN.js} +2 -2
- package/dist/cli/chunks/{chunk-EH2S6AOR.js → chunk-DZGPUGUG.js} +2 -2
- package/dist/cli/chunks/{chunk-HYXUN7BW.js → chunk-EF6OERRR.js} +1 -1
- package/dist/cli/chunks/{chunk-G77MLBDF.js → chunk-EN7GRVEQ.js} +2 -2
- package/dist/cli/chunks/{chunk-XDI5X3FR.js → chunk-ENGL7FIJ.js} +1 -1
- package/dist/cli/chunks/{chunk-HDNWSKHA.js → chunk-FAGKBOX2.js} +2 -2
- package/dist/cli/chunks/{chunk-FWSGPE3V.js → chunk-FNUFTWEO.js} +3 -3
- package/dist/cli/chunks/{chunk-AUUJBXWX.js → chunk-FZJCBSN4.js} +2 -2
- package/dist/cli/chunks/{chunk-ERN43HOX.js → chunk-G24SWTAX.js} +35 -35
- package/dist/cli/chunks/{chunk-VEEYL2CZ.js → chunk-G3AABG4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-35M2X3C5.js → chunk-GJKZ7UQO.js} +2 -2
- package/dist/cli/chunks/{chunk-OV5RPLKV.js → chunk-GKFV6CUD.js} +2 -2
- package/dist/cli/chunks/{chunk-4HJKQIX5.js → chunk-HLGFHHWV.js} +2 -2
- package/dist/cli/chunks/{chunk-R5LGV6GZ.js → chunk-HM3LSFTY.js} +2 -2
- package/dist/cli/chunks/{chunk-M7XFBSIK.js → chunk-HSA5IGGW.js} +2 -2
- package/dist/cli/chunks/{chunk-GWJWSLDA.js → chunk-HZBXJFGN.js} +2 -2
- package/dist/cli/chunks/{chunk-4MUBW4RT.js → chunk-IA55PFLG.js} +2 -2
- package/dist/cli/chunks/{chunk-RBZCA7SD.js → chunk-ICKUINKD.js} +2 -2
- package/dist/cli/chunks/{chunk-KDI5JOYZ.js → chunk-IETBWYHW.js} +2 -2
- package/dist/cli/chunks/{chunk-325QCVDI.js → chunk-IL7GQNNE.js} +2 -2
- package/dist/cli/chunks/{chunk-BTVWA35P.js → chunk-INZARYUD.js} +2 -2
- package/dist/cli/chunks/{chunk-G2IJFNZS.js → chunk-IPA7K556.js} +2 -2
- package/dist/cli/chunks/{chunk-UTTSH4NH.js → chunk-IVTQF55W.js} +3 -3
- package/dist/cli/chunks/{chunk-2CW7VRPH.js → chunk-J7Y7ZBIT.js} +5 -5
- package/dist/cli/chunks/{chunk-M5RQ6U3G.js → chunk-JGIJPDGD.js} +2 -2
- package/dist/cli/chunks/{chunk-RQMCZQN2.js → chunk-JNXK47OL.js} +2 -2
- package/dist/cli/chunks/{chunk-X4J73KP3.js → chunk-JOWUS2X5.js} +1 -1
- package/dist/cli/chunks/{chunk-ZMC543GI.js → chunk-JR6CUKAI.js} +2 -2
- package/dist/cli/chunks/chunk-JRYWLOBD.js +21 -0
- package/dist/cli/chunks/{chunk-ETVAYGCB.js → chunk-JW5PDJ5O.js} +3 -3
- package/dist/cli/chunks/{chunk-OD5D4LSZ.js → chunk-K3A3NWT3.js} +2 -2
- package/dist/cli/chunks/{chunk-LPU6PAJE.js → chunk-KA5SHLMW.js} +2 -2
- package/dist/cli/chunks/{chunk-NPZOBSAN.js → chunk-KGA7VAI4.js} +2 -2
- package/dist/cli/chunks/{chunk-ZMHCMJ4J.js → chunk-KJDI5CHX.js} +2 -2
- package/dist/cli/chunks/{chunk-KSLLHFVY.js → chunk-L3PV7VXK.js} +1 -1
- package/dist/cli/chunks/{chunk-LD5CFK53.js → chunk-L7NGKANW.js} +2 -2
- package/dist/cli/chunks/{chunk-6NA3KZZT.js → chunk-LFBA735S.js} +7 -7
- package/dist/cli/chunks/{chunk-Z2EA7A4Z.js → chunk-MAJXZYGK.js} +1 -1
- package/dist/cli/chunks/{chunk-TCYSBC7Y.js → chunk-MCPEC6OO.js} +1 -1
- package/dist/cli/chunks/{chunk-LBX7M4LW.js → chunk-MCPXNUDK.js} +2 -2
- package/dist/cli/chunks/{chunk-5YLOLACR.js → chunk-MMEALJ4D.js} +2 -2
- package/dist/cli/chunks/{chunk-IOZRKXR5.js → chunk-MYF5CNGV.js} +2 -2
- package/dist/cli/chunks/{chunk-X3PZCXWG.js → chunk-MYUMJ2ZI.js} +1 -1
- package/dist/cli/chunks/{chunk-VYTILW4R.js → chunk-N7O3PF6Y.js} +2 -2
- package/dist/cli/chunks/{chunk-GVKVJJQX.js → chunk-NA3F6FEO.js} +2 -2
- package/dist/cli/chunks/{chunk-TL6OFMXF.js → chunk-NNBQZR73.js} +2 -2
- package/dist/cli/chunks/{chunk-KXS3Y2AX.js → chunk-NV74SICL.js} +2 -2
- package/dist/cli/chunks/chunk-NVRYELCY.js +13 -0
- package/dist/cli/chunks/{chunk-OH5V5EJW.js → chunk-NX4BCSOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-XJKZ7FTR.js → chunk-O3IM4WRZ.js} +2 -2
- package/dist/cli/chunks/{chunk-3RHOPP7A.js → chunk-O4QJMANM.js} +1 -1
- package/dist/cli/chunks/{chunk-O4JAKWWM.js → chunk-OHVYINGM.js} +17 -17
- package/dist/cli/chunks/{chunk-APPZATXA.js → chunk-P5E26N2X.js} +2 -2
- package/dist/cli/chunks/{chunk-5ERFHEEE.js → chunk-P7UFJ6DO.js} +1 -1
- package/dist/cli/chunks/{chunk-5MNASJOH.js → chunk-PGSJBXTD.js} +2 -2
- package/dist/cli/chunks/{chunk-WCAVIJ64.js → chunk-PT2NXS43.js} +1 -1
- package/dist/cli/chunks/{chunk-EWPUQCN4.js → chunk-PTBOLBM4.js} +2 -2
- package/dist/cli/chunks/{chunk-EK5GMOSO.js → chunk-PX5OPXY6.js} +1 -1
- package/dist/cli/chunks/chunk-QCPVUNN3.js +2 -0
- package/dist/cli/chunks/{chunk-K2HBNYAZ.js → chunk-QSGEBCDB.js} +2 -2
- package/dist/cli/chunks/{chunk-G4FAPO57.js → chunk-QUJJYTJH.js} +2 -2
- package/dist/cli/chunks/{chunk-H7BLYMNU.js → chunk-QWG3SILX.js} +3 -3
- package/dist/cli/chunks/{chunk-LXQ3B4RY.js → chunk-RCOLPF3B.js} +2 -2
- package/dist/cli/chunks/{chunk-E44NNCEU.js → chunk-RYHG3I7J.js} +2 -2
- package/dist/cli/chunks/{chunk-RTFKTKSO.js → chunk-SBHM5X2S.js} +2 -2
- package/dist/cli/chunks/{chunk-DOBZPSKE.js → chunk-SDRJJUPO.js} +1 -1
- package/dist/cli/chunks/{chunk-RTY7VSZB.js → chunk-SG2TX72G.js} +2 -2
- package/dist/cli/chunks/{chunk-NTB342NJ.js → chunk-SITL5YZV.js} +4 -4
- package/dist/cli/chunks/{chunk-WM3SRRA6.js → chunk-SPC4RBLF.js} +2 -2
- package/dist/cli/chunks/{chunk-ITL3IN2E.js → chunk-SQVZ3TRU.js} +2 -2
- package/dist/cli/chunks/{chunk-CO3DX2AX.js → chunk-SUX5XB2Z.js} +2 -2
- package/dist/cli/chunks/{chunk-KSE5TDM5.js → chunk-T4EN5VVK.js} +2 -2
- package/dist/cli/chunks/{chunk-5HQP4SLM.js → chunk-TGMXUZZC.js} +2 -2
- package/dist/cli/chunks/{chunk-YOCULVHR.js → chunk-TLRHAMX5.js} +1 -1
- package/dist/cli/chunks/{chunk-GBFUANTC.js → chunk-TOWOJGEI.js} +1 -1
- package/dist/cli/chunks/{chunk-4UBVAJFO.js → chunk-TSOQ2QLT.js} +2 -2
- package/dist/cli/chunks/{chunk-SMVVAVN2.js → chunk-TVA5GRIU.js} +2 -2
- package/dist/cli/chunks/{chunk-K7V2WZNF.js → chunk-TXEUVUMO.js} +1 -1
- package/dist/cli/chunks/{chunk-LQ4NUC6Q.js → chunk-U6IXYQO4.js} +2 -2
- package/dist/cli/chunks/{chunk-HDJUYAZG.js → chunk-U7ZHDGXG.js} +1 -1
- package/dist/cli/chunks/{chunk-2VLYUF7U.js → chunk-UCSK2RMI.js} +2 -2
- package/dist/cli/chunks/{chunk-4UX35V7P.js → chunk-UIKQPO4Y.js} +2 -2
- package/dist/cli/chunks/chunk-UJNGGFGX.js +2 -0
- package/dist/cli/chunks/{chunk-AFFN6E6Q.js → chunk-ULCW6IVQ.js} +2 -2
- package/dist/cli/chunks/{chunk-WCVCOT4E.js → chunk-UREDS662.js} +2 -2
- package/dist/cli/chunks/{chunk-E6PF35JZ.js → chunk-URSTP3WI.js} +2 -2
- package/dist/cli/chunks/{chunk-I36CRDHF.js → chunk-UUZZXHUF.js} +2 -2
- package/dist/cli/chunks/{chunk-MIK4RBEH.js → chunk-UZED4YZ5.js} +1 -1
- package/dist/cli/chunks/{chunk-ZQHDA4O7.js → chunk-VF7FTD64.js} +1 -1
- package/dist/cli/chunks/{chunk-AMZKAJLJ.js → chunk-VUR5THML.js} +2 -2
- package/dist/cli/chunks/{chunk-H43AFUKL.js → chunk-VXVTFKRA.js} +2 -2
- package/dist/cli/chunks/chunk-VZBC6DP7.js +2 -0
- package/dist/cli/chunks/{chunk-DDEOZPWJ.js → chunk-W4II6SIH.js} +2 -2
- package/dist/cli/chunks/{chunk-55CH76ZO.js → chunk-W5HQIYQU.js} +3 -3
- package/dist/cli/chunks/{chunk-YPX2TV3M.js → chunk-W7H55PY4.js} +1 -1
- package/dist/cli/chunks/{chunk-CFWGGRE7.js → chunk-WDEXOLK2.js} +1 -1
- package/dist/cli/chunks/{chunk-XGBU3KEM.js → chunk-WGTEZT7G.js} +2 -2
- package/dist/cli/chunks/{chunk-NC6K7SCQ.js → chunk-WLRU6ESI.js} +2 -2
- package/dist/cli/chunks/{chunk-JFLU7L3W.js → chunk-WTAUF6O4.js} +2 -2
- package/dist/cli/chunks/chunk-XCNSGSKV.js +3 -0
- package/dist/cli/chunks/{chunk-57LNKSW7.js → chunk-XZOYKB22.js} +2 -2
- package/dist/cli/chunks/chunk-YIDAXOUX.js +8 -0
- package/dist/cli/chunks/{chunk-25P77WA5.js → chunk-YLKIXEPP.js} +1 -1
- package/dist/cli/chunks/{chunk-R5GRABPQ.js → chunk-YNVEDFPQ.js} +1 -1
- package/dist/cli/chunks/{chunk-NQZNMCZU.js → chunk-YUA6ZKKY.js} +2 -2
- package/dist/cli/chunks/{chunk-OYJC3YON.js → chunk-YVJEUX3I.js} +2 -2
- package/dist/cli/chunks/{chunk-QDESWOZP.js → chunk-YWWMNTBF.js} +2 -2
- package/dist/cli/chunks/{chunk-7HEMJHPP.js → chunk-ZGROHCOW.js} +1 -1
- package/dist/cli/chunks/{chunk-AP3ADWDK.js → chunk-ZPVGX4DI.js} +2 -2
- package/dist/cli/chunks/{chunk-M5XYIQYZ.js → chunk-ZROAMFX2.js} +2 -2
- package/dist/cli/chunks/{chunk-I4K2HTQU.js → chunk-ZYOYR3UR.js} +1 -1
- package/dist/cli/chunks/ci-BZNWW3I3.js +81 -0
- package/dist/cli/chunks/{ci-config-J665XNOX.js → ci-config-LOHNXOKV.js} +2 -2
- package/dist/cli/chunks/{ci-output-PEQQQWVD.js → ci-output-LCOQBSJL.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-HHB2JSKH.js → circuit-breaker-7LRXTLFE.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-JKUJRWPN.js → claude-flow-setup-HBU4VWC3.js} +2 -2
- package/dist/cli/chunks/client-4PNYDFYS.js +2 -0
- package/dist/cli/chunks/{cline-installer-Y77BWTAN.js → cline-installer-CO6MLH6X.js} +2 -2
- package/dist/cli/chunks/{code-LV2HAGJY.js → code-SIXBS6JM.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-4GKKSETB.js → code-index-extractor-GWJKZ2IQ.js} +2 -2
- package/dist/cli/chunks/{codex-installer-WMKBYE5Y.js → codex-installer-6NINVWXJ.js} +2 -2
- package/dist/cli/chunks/{completions-SBGFAOIJ.js → completions-7VIX3GML.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-AQHFIJXC.js → complexity-analyzer-FBQR6ZP2.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-26AYFS2E.js → continuedev-installer-VA7RIXW5.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-4UD3DK55.js → copilot-installer-4QEBC4MU.js} +2 -2
- package/dist/cli/chunks/core-handlers-ODO6LUWQ.js +2 -0
- package/dist/cli/chunks/{cost-tracker-TP4NZCG4.js → cost-tracker-GRYKHPWL.js} +2 -2
- package/dist/cli/chunks/{coverage-B2KIXHAI.js → coverage-USPMNKOU.js} +11 -10
- package/dist/cli/chunks/cross-domain-router-DT4MHJKK.js +2 -0
- package/dist/cli/chunks/{cursor-installer-AVZEQZ4W.js → cursor-installer-ZXIPSZVH.js} +2 -2
- package/dist/cli/chunks/{daemon-XM2A7LQU.js → daemon-D7F3RGI5.js} +3 -3
- package/dist/cli/chunks/{daemon-P574WWBW.js → daemon-N2VRHPSJ.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-MIWOZ6ET.js → dag-attention-scheduler-NL6BA7BY.js} +2 -2
- package/dist/cli/chunks/{detect-TYR7HT23.js → detect-XC2HCIIT.js} +2 -2
- package/dist/cli/chunks/{dist-node-2DGVQGLS.js → dist-node-A3Y26MEI.js} +2 -2
- package/dist/cli/chunks/{domain-handler-RRA4ZOMF.js → domain-handler-WV6SFXRB.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-IVZEZ5RB.js → domain-plugins-KJIF6Z2B.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-DOBI67K6.js → domain-transfer-L3F6AES2.js} +2 -2
- package/dist/cli/chunks/dream-QOB3JCOM.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-VNIEOVPO.js → embed-and-insert-pattern-PA3Y4KGO.js} +2 -2
- package/dist/cli/chunks/{eval-QV4LVPUF.js → eval-YGEZNUVE.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-DAPKT763.js → experience-capture-middleware-D4T7NW6B.js} +3 -3
- package/dist/cli/chunks/{fast-paths-WVRFPHX7.js → fast-paths-6JYK7RYQ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-O7ZXDDCD.js → feature-flags-DKXMDVPE.js} +2 -2
- package/dist/cli/chunks/{feature-flags-DEFTUIYT.js → feature-flags-RBH2GDSR.js} +2 -2
- package/dist/cli/chunks/file-discovery-BN76S2PR.js +2 -0
- package/dist/cli/chunks/fleet-43YMXACN.js +46 -0
- package/dist/cli/chunks/{gnn-wrapper-LS4LZJDR.js → gnn-wrapper-MV54UC4C.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-RFTERD4K.js → heartbeat-handler-7DKMVQQH.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-3NNP4WCP.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-MZR7Y4WF.js +2 -0
- package/dist/cli/chunks/hnsw-index-HE4AX22U.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-GPKGFFHY.js → hnsw-legacy-bridge-6IWREDQC.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-PHL3F2PR.js → hnswlib-node-5BIESSCK.js} +2 -2
- package/dist/cli/chunks/{hooks-GYJ6D4QM.js → hooks-3EETRM62.js} +28 -28
- package/dist/cli/chunks/hybrid-backend-IHUHB3Y2.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-YGEQPCKJ.js → hypergraph-engine-RSWCB2D3.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-ZIMM647V.js → hypergraph-handler-552LXKL3.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-FI6GI6PD.js +2 -0
- package/dist/cli/chunks/{init-guard-VOMBXJXG.js → init-guard-OTDBJ5HD.js} +2 -2
- package/dist/cli/chunks/{init-handler-PSMUBWK5.js → init-handler-3FK3TKEA.js} +6 -6
- package/dist/cli/chunks/init-wizard-WLQKH5Y5.js +2 -0
- package/dist/cli/chunks/kernel-2WZOQEZS.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-2YNTFBWJ.js → kilocode-installer-KZ2O4LF3.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-XHJDPVAZ.js → kiro-installer-MLCCXRF7.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-G3LVKK6P.js +2 -0
- package/dist/cli/chunks/{learning-GNSIDRNG.js → learning-QUCMBD77.js} +3 -3
- package/dist/cli/chunks/{llm-router-LQDM7IU2.js → llm-router-PDEV3UP2.js} +4 -4
- package/dist/cli/chunks/llm-router-service-MM75HKWJ.js +2 -0
- package/dist/cli/chunks/{load-YATHI72E.js → load-XFVVLO7E.js} +2 -2
- package/dist/cli/chunks/load-test-BEWEE44J.js +2 -0
- package/dist/cli/chunks/{mcp-4Y6GDLYK.js → mcp-74G3CL2S.js} +2 -2
- package/dist/cli/chunks/{memory-OUW3L7H2.js → memory-XIFM6JNX.js} +5 -5
- package/dist/cli/chunks/memory-backend-NYKBBKZR.js +2 -0
- package/dist/cli/chunks/{memory-handlers-G3LFF53U.js → memory-handlers-ZCKURV6S.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-UBZJXAD2.js → multi-model-executor-7L4W3O2Q.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-AMMNWVH5.js → opencode-installer-BPG422LF.js} +2 -2
- package/dist/cli/chunks/{orchestrator-Y44WDOER.js → orchestrator-OEAFLAEV.js} +58 -20
- package/dist/cli/chunks/pattern-null-store-QGPUIV6M.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-ESR42RME.js → pattern-usage-recorder-LOPNCULT.js} +2 -2
- package/dist/cli/chunks/{pipeline-EDTS6OSC.js → pipeline-VWTYUZB7.js} +2 -2
- package/dist/cli/chunks/{platform-5WONJSUX.js → platform-WFJJ3X2E.js} +2 -2
- package/dist/cli/chunks/{plugin-IJXPCLD4.js → plugin-744TPUSG.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-5ECKGZK6.js → prime-radiant-advanced-wasm-BD5BLNDR.js} +2 -2
- package/dist/cli/chunks/project-root-C7ELXZRK.js +2 -0
- package/dist/cli/chunks/protocol-executor-SUVE33BM.js +2 -0
- package/dist/cli/chunks/{protocol-handler-DRD3GVNW.js → protocol-handler-JIBILI74.js} +2 -2
- package/dist/cli/chunks/{prove-KTGW2HMJ.js → prove-MNOL5FYW.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-YWZMMGJB.js +2 -0
- package/dist/cli/chunks/{quality-DV2WPRRS.js → quality-JEGBDGGX.js} +2 -2
- package/dist/cli/chunks/{quality-gate-HFUAFVZC.js → quality-gate-SYJ6ROMI.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-ZFAKXRN7.js +2 -0
- package/dist/cli/chunks/real-embeddings-ZWXS5ZFV.js +2 -0
- package/dist/cli/chunks/{ref-validation-QWSKS5OY.js → ref-validation-RRHUFW2N.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-RBAYRCHX.js → roocode-installer-XFO6JSVN.js} +2 -2
- package/dist/cli/chunks/router-4FTAVYLJ.js +2 -0
- package/dist/cli/chunks/routing-feedback-IO2KOWMJ.js +2 -0
- package/dist/cli/chunks/{routing-handler-FMPP3XKO.js → routing-handler-L2K3JASE.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-KZZT4HWF.js → ruvector-commands-A6CINHGM.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-KCIRNE7C.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-MFC5WTJU.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-7CHEV35N.js → rvf-migration-coordinator-T4RY7L53.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-I3KWHE7X.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-Q2TH52SN.js → rvf-store-integrity-IR33TGQS.js} +2 -2
- package/dist/cli/chunks/safe-db-QXDZ6QY3.js +2 -0
- package/dist/cli/chunks/schedule-CZKD6RIY.js +2 -0
- package/dist/cli/chunks/scheduler-BLA3Q4CH.js +2 -0
- package/dist/cli/chunks/{security-CUEA3UIM.js → security-Z5GDE2IH.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-DROMBRV2.js → shared-rvf-adapter-SIZMEHPM.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-DBNABOP7.js → shared-rvf-dual-writer-HLM65RDS.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-XIUYDJC4.js +2 -0
- package/dist/cli/chunks/{standalone-memory-IAHA3M6B.js → standalone-memory-SKSZG7P5.js} +2 -2
- package/dist/cli/chunks/{status-handler-AFUCASTX.js → status-handler-766YOOMJ.js} +2 -2
- package/dist/cli/chunks/{structural-health-AQRV6JJ6.js → structural-health-M45FNOLT.js} +2 -2
- package/dist/cli/chunks/{sync-GX7FMJHL.js → sync-6CJ24B5T.js} +2 -2
- package/dist/cli/chunks/{sync-XW5TLZ7M.js → sync-B2U366I3.js} +2 -2
- package/dist/cli/chunks/{task-handler-TFKVUTNF.js → task-handler-P6IFLCKP.js} +17 -15
- package/dist/cli/chunks/task-handlers-DPWMUKFC.js +9 -0
- package/dist/cli/chunks/{test-D2XDJNDX.js → test-TODH7KRF.js} +4 -4
- package/dist/cli/chunks/test-runner-process-46IPK3GH.js +2 -0
- package/dist/cli/chunks/{test-scheduling-TS6I2PR7.js → test-scheduling-VMVMVRHT.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-HBBLPCZ3.js → token-bootstrap-XQW7BMCK.js} +2 -2
- package/dist/cli/chunks/{token-usage-3MBUX4PR.js → token-usage-JCZEIRKO.js} +2 -2
- package/dist/cli/chunks/{transformers-ZWMQO3L2.js → transformers-U2ML3OHE.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-MOI2WWNJ.js +2 -0
- package/dist/cli/chunks/{types-5YEMGPSQ.js → types-GGEPCHP6.js} +2 -2
- package/dist/cli/chunks/unified-memory-FL26RTV3.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-E2BPTH3U.js +2 -0
- package/dist/cli/chunks/unified-persistence-5ZOUPKHF.js +2 -0
- package/dist/cli/chunks/{upgrade-2TPBKIHI.js → upgrade-T5GRM7HS.js} +2 -2
- package/dist/cli/chunks/{validate-XRAXXFW6.js → validate-XMUJPLP3.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-IYSCS3BZ.js → validate-swarm-KJLF7JEH.js} +2 -2
- package/dist/cli/chunks/visual-security-IJVPO5FA.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-PZQ3ZG2P.js → web-tree-sitter-LOHVZ7G5.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-U6XWFRVT.js → windsurf-installer-33FBTXJU.js} +2 -2
- package/dist/cli/chunks/witness-chain-5FAFCQKP.js +2 -0
- package/dist/cli/chunks/witness-chain-V2M32W5D.js +2 -0
- package/dist/cli/chunks/{witness-chain-repair-K7YX2AO6.js → witness-chain-repair-VWBO4NXE.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-GUTC3W7N.js → witness-chain-verifier-BHJ3ZAEK.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-YBNKMOP6.js → witness-key-manager-WNVPH2Z3.js} +2 -2
- package/dist/cli/chunks/{workflow-UAJUILFQ.js → workflow-6QR5MQTO.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-3JLF3IX7.js +2 -0
- package/dist/cli/chunks/{wrappers-AVZ3GPAL.js → wrappers-EHOL62TS.js} +2 -2
- package/dist/cli/commands/ci.js +7 -0
- package/dist/cli/commands/coverage.js +7 -1
- package/dist/cli/commands/fleet.js +2 -2
- package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +4 -3
- package/dist/cli/commands/hooks-handlers/stats-hooks.js +22 -4
- package/dist/cli/handlers/task-handler.js +6 -0
- package/dist/cli/utils/coverage-verdict.d.ts +11 -2
- package/dist/cli/utils/coverage-verdict.js +26 -6
- package/dist/cli/utils/fleet-operation.d.ts +5 -0
- package/dist/cli/utils/fleet-operation.js +7 -1
- package/dist/cli/utils/fleet-result.d.ts +5 -3
- package/dist/cli/utils/fleet-result.js +9 -3
- package/dist/coordination/handlers/coverage-collection.d.ts +2 -0
- package/dist/coordination/handlers/coverage-collection.js +2 -1
- package/dist/coordination/handlers/coverage-evidence.d.ts +75 -0
- package/dist/coordination/handlers/coverage-evidence.js +159 -0
- package/dist/coordination/handlers/coverage-handlers.js +16 -3
- package/dist/coordination/handlers/coverage-scope.d.ts +40 -0
- package/dist/coordination/handlers/coverage-scope.js +321 -0
- package/dist/coordination/handlers/coverage-target.d.ts +9 -0
- package/dist/coordination/handlers/coverage-target.js +15 -5
- package/dist/coordination/handlers/handler-utils.d.ts +5 -0
- package/dist/coordination/handlers/handler-utils.js +8 -4
- package/dist/domains/code-intelligence/services/metric-collector/listing-process-owner.js +4 -1
- package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +8 -0
- package/dist/domains/code-intelligence/services/semantic-analyzer.js +10 -7
- package/dist/init/phases/10-workers.js +42 -4
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +23 -1
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +50 -15
- package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +7 -2
- package/dist/integrations/agentic-flow/reasoning-bank/index.js +8 -0
- package/dist/learning/embedder-endpoint-client.d.ts +8 -0
- package/dist/learning/embedder-endpoint-client.js +20 -0
- package/dist/learning/embedder-recovery.d.ts +63 -0
- package/dist/learning/embedder-recovery.js +94 -0
- package/dist/learning/qe-reasoning-bank-types.d.ts +5 -0
- package/dist/learning/qe-reasoning-bank.d.ts +21 -0
- package/dist/learning/qe-reasoning-bank.js +54 -8
- package/dist/learning/real-embeddings.d.ts +23 -0
- package/dist/learning/real-embeddings.js +69 -2
- package/dist/learning/real-qe-reasoning-bank.d.ts +24 -4
- package/dist/learning/real-qe-reasoning-bank.js +58 -20
- package/dist/logging/redaction.js +142 -12
- package/dist/mcp/bundle.js +504 -492
- package/dist/mcp/daemon-mode.d.ts +126 -0
- package/dist/mcp/daemon-mode.js +257 -0
- package/dist/mcp/entry.d.ts +4 -0
- package/dist/mcp/entry.js +50 -2
- package/dist/mcp/handlers/domain-handler-configs.js +5 -0
- package/dist/mcp/handlers/orchestrate-routes.d.ts +6 -1
- package/dist/mcp/handlers/orchestrate-routes.js +53 -0
- package/dist/mcp/handlers/task-handlers.d.ts +11 -2
- package/dist/mcp/handlers/task-handlers.js +50 -5
- package/dist/mcp/protocol-server.js +3 -0
- package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
- package/dist/mcp/services/reasoning-bank-service.js +9 -0
- package/dist/mcp/types.d.ts +14 -0
- package/dist/routing/advisor/redaction.js +22 -2
- package/dist/shared/llm/providers/response-deadline.js +16 -2
- package/dist/shared/types/index.js +3 -1
- package/dist/strange-loop/infra-healing/infra-aware-agent-provider.js +8 -1
- package/package.json +3 -3
- package/dist/cli/chunks/adapter-V4GSGOOK.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-6WQTM5YR.js +0 -2
- package/dist/cli/chunks/base-AK7BXBX2.js +0 -2
- package/dist/cli/chunks/browser-workflow-VTDFBW7T.js +0 -2
- package/dist/cli/chunks/chunk-2DTX7YAZ.js +0 -6
- package/dist/cli/chunks/chunk-72ZBJD2E.js +0 -3
- package/dist/cli/chunks/chunk-EBPJY4DI.js +0 -3
- package/dist/cli/chunks/chunk-HJ3XNTTJ.js +0 -2
- package/dist/cli/chunks/chunk-IO5537OM.js +0 -2
- package/dist/cli/chunks/chunk-IW6WDGHM.js +0 -2
- package/dist/cli/chunks/chunk-LRL56ZYL.js +0 -21
- package/dist/cli/chunks/chunk-VLD7Z2ED.js +0 -13
- package/dist/cli/chunks/chunk-VO3DRK4P.js +0 -3
- package/dist/cli/chunks/ci-6GUFAZMJ.js +0 -81
- package/dist/cli/chunks/client-HL2COSFM.js +0 -2
- package/dist/cli/chunks/core-handlers-IX7ATLM6.js +0 -2
- package/dist/cli/chunks/cross-domain-router-YYKLAPJO.js +0 -2
- package/dist/cli/chunks/dream-T6EP7B3F.js +0 -2
- package/dist/cli/chunks/file-discovery-JYMVTDMU.js +0 -2
- package/dist/cli/chunks/fleet-FVAUMKUT.js +0 -46
- package/dist/cli/chunks/heartbeat-scheduler-4N5MUJ7S.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-ZPAJDSLR.js +0 -2
- package/dist/cli/chunks/hnsw-index-4CTH6RHB.js +0 -2
- package/dist/cli/chunks/hybrid-backend-AW6UTXQS.js +0 -2
- package/dist/cli/chunks/impact-analyzer-MZK3JMSV.js +0 -2
- package/dist/cli/chunks/init-wizard-FUC7KDVX.js +0 -2
- package/dist/cli/chunks/kernel-ZCPMCVMW.js +0 -2
- package/dist/cli/chunks/knowledge-graph-NUJKEDNF.js +0 -2
- package/dist/cli/chunks/llm-router-service-B2BFBQ76.js +0 -2
- package/dist/cli/chunks/load-test-ZHQ2MUGO.js +0 -2
- package/dist/cli/chunks/memory-backend-AAMQG6WH.js +0 -2
- package/dist/cli/chunks/pattern-null-store-RFNVA46O.js +0 -2
- package/dist/cli/chunks/project-root-7QL4KP5C.js +0 -2
- package/dist/cli/chunks/protocol-executor-2NW5BD4R.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-G2JZOGKD.js +0 -2
- package/dist/cli/chunks/queen-coordinator-GRG5FT2A.js +0 -2
- package/dist/cli/chunks/real-embeddings-RQRVOKVM.js +0 -2
- package/dist/cli/chunks/router-LQB5SWAF.js +0 -2
- package/dist/cli/chunks/routing-feedback-OEEXA55N.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-BZK4M7BO.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-EZZUJL2E.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-6COXTQZ3.js +0 -2
- package/dist/cli/chunks/safe-db-PE6G3L55.js +0 -2
- package/dist/cli/chunks/schedule-OLKQ6QYW.js +0 -2
- package/dist/cli/chunks/scheduler-LSGBDFAT.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-HH4DNTYH.js +0 -2
- package/dist/cli/chunks/task-handlers-SS4ZDXNF.js +0 -9
- package/dist/cli/chunks/test-runner-process-PSSBNNGR.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-TYRQRJ2W.js +0 -2
- package/dist/cli/chunks/unified-memory-AGDZQ5XD.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-X5TJ3JDE.js +0 -2
- package/dist/cli/chunks/unified-persistence-UCV7YETW.js +0 -2
- package/dist/cli/chunks/visual-security-ZLXRIQZV.js +0 -2
- package/dist/cli/chunks/witness-chain-CVIWYTD2.js +0 -2
- package/dist/cli/chunks/witness-chain-VBKORKOX.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3ZN7MVCE.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a as m}from"./chunk-2JYUA27M.js";import{c,e as y}from"./chunk-SPC4RBLF.js";import"./chunk-WDEXOLK2.js";import{readFile as w,readdir as W}from"fs/promises";import{join as f,basename as b,dirname as v}from"path";import{fileURLToPath as E}from"url";import{parse as d}from"yaml";y();var x=E(import.meta.url),O=v(x),l=class{templatesDir;cache=new Map;constructor(t){this.templatesDir=t||f(O,"templates")}async load(t){if(this.cache.has(t))return this.cache.get(t);try{let e=f(this.templatesDir,`${t}.yaml`),n=await w(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${t}:
|
|
3
3
|
${i.errors.join(`
|
|
4
4
|
`)}`);return this.cache.set(t,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${t}`):e}}async list(){try{return(await W(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>b(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(t){if(t.code==="ENOENT")return[];throw t}}async validate(t){let e=[],n=[];if(t.name||e.push("Workflow must have a name"),t.version||e.push("Workflow must have a version"),t.description||n.push("Workflow should have a description"),Array.isArray(t.variables)?t.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(t.steps))e.push("Workflow must have a steps array");else if(t.steps.length===0)e.push("Workflow must have at least one step");else{t.steps.forEach((r,s)=>{r.name||e.push(`Step at index ${s} must have a name`),r.action||e.push(`Step ${r.name||s} must have an action`),(!r.config||typeof r.config!="object")&&e.push(`Step ${r.name||s} must have a config object`),r.assertions&&Array.isArray(r.assertions)&&r.assertions.forEach((u,p)=>{u.condition||e.push(`Assertion ${p} in step ${r.name||s} must have a condition`),u.message||n.push(`Assertion ${p} in step ${r.name||s} should have a message`)})});let o=t.steps.map(r=>r.name),i=o.filter((r,s)=>o.indexOf(r)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(t,e){let n=await this.load(t),o=n.variables.filter(r=>r.required&&!Object.hasOwn(e,r.name)).map(r=>r.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(r=>{Object.hasOwn(e,r.name)?c(i,r.name,e[r.name]):"default"in r&&c(i,r.name,r.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:t}}}async getMetadata(t){try{let e=f(this.templatesDir,`${t}.yaml`),n=await w(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${t}`):e}}clearCache(){this.cache.clear()}async reload(t){return this.cache.delete(t),this.load(t)}},T=new l;function g(a,t){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),r=t;for(let s of i)if(r&&typeof r=="object"&&Object.hasOwn(r,s))r=r[s];else return e;return r!=null?String(r):e})}function A(a,t){let e={...t.variables,result:t.results.get("__last_result__")},n=g(a,e);return m(n,e,!1)}var h=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],R={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},k={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function L(a){return k[a]}function N(a){return h.includes(a)}function B(){return h.map(a=>{let t=Object.entries(k).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:R[a],category:t}})}export{k as WORKFLOW_CATEGORIES,R as WORKFLOW_DESCRIPTIONS,h as WORKFLOW_TEMPLATES,l as WorkflowLoader,T as defaultWorkflowLoader,A as evaluateCondition,B as getAllWorkflowTemplates,L as getWorkflowsByCategory,g as interpolateVariables,N as isValidWorkflowTemplate};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a}from"./chunk-5ADXFUMO.js";import"./chunk-KJDI5CHX.js";import"./chunk-SG2TX72G.js";import"./chunk-GKFV6CUD.js";import"./chunk-L7NGKANW.js";import"./chunk-66PXR3NI.js";import"./chunk-WTAUF6O4.js";import"./chunk-SPC4RBLF.js";import"./chunk-WGTEZT7G.js";import"./chunk-IPA7K556.js";import"./chunk-ZROAMFX2.js";import"./chunk-YUA6ZKKY.js";import"./chunk-3IU4LDZR.js";import"./chunk-YVJEUX3I.js";import"./chunk-6QRI3JVE.js";import"./chunk-7TA5MUPW.js";import"./chunk-YWWMNTBF.js";import"./chunk-UJNGGFGX.js";import"./chunk-ADUAJIAU.js";import"./chunk-7OEFBWAG.js";import"./chunk-QCPVUNN3.js";import"./chunk-35MIUSXQ.js";import"./chunk-DZGPUGUG.js";import"./chunk-4LWMAAWK.js";import"./chunk-IA55PFLG.js";import"./chunk-W4II6SIH.js";import"./chunk-O3IM4WRZ.js";import"./chunk-WDEXOLK2.js";export{a as BrowserWorkflowTool};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
2
|
var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a,d as R}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a,d as R}from"./chunk-7OEFBWAG.js";R();var c=class extends Error{constructor(t){super(a(t,Number.POSITIVE_INFINITY)),this.name="TestRunnerExecutionError"}};function x(e,t=4e3){return a(e,Number.POSITIVE_INFINITY).slice(0,t)}function O(e,t,r,n,s,i){let l=(i?.testResults??[]).filter(u=>u.status==="failed"&&(e==="vitest"&&u.message||!u.assertionResults?.some(g=>g.status==="failed"))),o;if(r===null?o="terminated without an exit code":n.passed+n.failed+n.skipped===0?o="reported zero tests":l.length>0||(i?.numRuntimeErrorTestSuites??0)>0||(i?.numFailedTestSuites??0)>0&&n.failed===0?o="reported a suite execution error":(r!==0||i?.success===!1)&&n.failed===0&&(o="failed without a failed assertion"),!o)return;let d=[...l.map(u=>u.message).filter(Boolean),s.trim()].filter(Boolean).join(`
|
|
3
3
|
`);return new c(`${e} ${o} for ${t} (exit code ${r??"unknown"}).`+(d?`
|
|
4
4
|
${x(d)}`:""))}import{mkdtempSync as y,readFileSync as h,rmSync as E}from"node:fs";import{tmpdir as $}from"node:os";import{join as p}from"node:path";function j(e,t){if(!t)return;let r;try{r=h(t,"utf-8")}catch(n){if(n.code==="ENOENT")return;throw new Error("Could not read the current Vitest JSON report.")}try{let n=JSON.parse(r);if(!n||!Array.isArray(n.testResults))throw new Error("Invalid report")}catch{throw new Error("The current Vitest JSON report is malformed.")}return r}function _(){let e=y(p($(),"aqe-vitest-report-")),t=p(e,"report.json"),r=!1;return{path:t,args:[`--outputFile=${t}`],read:n=>j(n,t),cleanup:()=>{if(!r){r=!0;try{E(e,{recursive:!0,force:!0})}catch{}}}}}function z(e){let t=e.some(s=>/(^|[\\/])vitest(\.cmd|\.js|\.mjs)?$/i.test(s)),r=e.some((s,i)=>s==="--reporter=json"||s==="--reporter"&&e[i+1]==="json"),n=e.some(s=>s.startsWith("--outputFile"));return t&&r&&!n}import{realpathSync as N,statSync as S}from"node:fs";import{basename as b,dirname as T,extname as F,resolve as m,sep as w}from"node:path";function f(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I(e,t=process.cwd()){let r=m(t,e);try{return m(N(T(r)),b(r))}catch{return r}}function J(e){try{return S(e).isDirectory()}catch{return F(e)===""}}function Y(e,t=process.cwd()){let r=I(e,t),n=r.split(w).join("/"),s=J(r)?"(?:/|$)":"$";return`^${f(n)}${s}`}function q(e,t){let r=`^${t.split(" ").map(f).join("(?: > | )")}$`;return e==="mocha"?`--grep=${r}`:`--testNamePattern=${r}`}function W(e){return e.some(t=>/(^|[\\/])jest(\.cmd|\.js|\.mjs)?$/i.test(t))}export{c as a,x as b,O as c,_ as d,z as e,I as f,Y as g,q as h,W as i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{i as t,j as s,l as a,n as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{i as t,j as s,l as a,n as m}from"./chunk-PGSJBXTD.js";m();var p={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:[a[1],"gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:[t,"gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:[t],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:[s,"gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},c={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},b={budgetConfig:c,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",...a}},r=class extends Error{constructor(e,i,y){super(e);this.code=i;this.cause=y;this.name="ModelRouterError"}code;cause},l=class extends r{constructor(e,i,y){super(e,"BUDGET_EXCEEDED");this.tier=i;this.usage=y;this.name="BudgetExceededError"}tier;usage},d=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},u=class extends r{constructor(e,i){super(e,"ROUTING_TIMEOUT");this.timeoutMs=i;this.name="RoutingTimeoutError"}timeoutMs};export{p as a,c as b,b as c,r as d,l as e,d as f,u as g};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a as p}from"./chunk-UJNGGFGX.js";import{c as g}from"./chunk-ADUAJIAU.js";p();import{format as R}from"node:util";var c=2,E={debug:0,info:1,warn:2,warning:2,error:3,silent:4,none:4,off:4},C=new Set(["1","true","yes","on"]),b=/\x1b\[[0-9;]*m/g,N=/^\[(?:\d{2}:\d{2}:\d{2}\.\d{3}|\d{4}-\d{2}-\d{2}T[^\]]+)\]\s+\[(DEBUG|INFO|WARN|ERROR)\s*\]/,O=/^\[[A-Za-z][\w./:-]*\]\s/,S={debug:0,log:1,info:1,warn:2,error:3},d=c;function s(o){if(o)return E[o.trim().toLowerCase()]}function _(o=process.env,e=c){let t=s(o.AQE_LOG_LEVEL)??s(o.LOG_LEVEL);return t!==void 0?t:o.AQE_VERBOSE&&C.has(o.AQE_VERBOSE.trim().toLowerCase())?1:e}function x(o,e){if(typeof e!="string")return null;let t=e.replace(b,""),r=N.exec(t.trimStart());return r?E[r[1].toLowerCase()]:O.test(t)?S[o]:null}function I(o=process.env){return s(o.AQE_LOG_LEVEL)!==void 0||s(o.LOG_LEVEL)!==void 0}function m(o,e=process.env){return o.verbose!==!0||I(e)||a(1)?!1:(f(1),!0)}function a(o){return o>=d&&d!==4}function f(o){d=o,g.setLevel(o)}function k(o={}){let e=o.target??console,t=o.writeStderr??(n=>{process.stderr.write(n)});f(o.level??_());let r={log:e.log.bind(e),info:e.info.bind(e),debug:e.debug.bind(e),warn:e.warn.bind(e),error:e.error.bind(e)},l=n=>t(R(...n)+`
|
|
3
3
|
`),i=(n,v,w)=>(...L)=>{let u=x(n,L[0]);u===null?v(L):a(u)&&w(L)};return e.log=i("log",n=>r.log(...n),l),e.debug=i("debug",n=>r.debug(...n),l),e.info=i("info",l,l),e.warn=i("warn",n=>r.warn(...n),n=>r.warn(...n)),e.error=i("error",n=>r.error(...n),n=>r.error(...n)),()=>{e.log=r.log,e.info=r.info,e.debug=r.debug,e.warn=r.warn,e.error=r.error}}export{_ as a,m as b,a as c,f as d,k as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
2
|
import{createHash as l}from"crypto";var u="0".repeat(64);function k(t){return l("sha256").update(t,"utf-8").digest("hex")}function v(t){try{return l("shake256",{outputLength:32}).update(t,"utf-8").digest("hex")}catch{return k(t)}}function o(t,e){return t==="shake256"?v(e):k(e)}function h(t){return JSON.stringify({id:t.id,prev_hash:t.prev_hash,action_hash:t.action_hash,action_type:t.action_type,action_data:t.action_data,timestamp:t.timestamp,actor:t.actor})}function c(t){return Buffer.from(t.prev_hash+t.action_hash+t.action_type+t.timestamp+t.actor,"utf-8")}var m="CHAIN_REANCHOR";function y(t){return o(t.hash_algo||"sha256",h(t))}var f=class{constructor(e,n,i={}){this.db=e;this.keyManager=n;this.options=i}db;keyManager;options;archiveRows=null;parentIndex=new Map;acks=new Map;pins=[];forks=[];tamper;signatureFailures=0;firstSignatureFailure;entriesChecked=0;archiveExists;run(){let e=g(this.db,"witness_chain")?this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all():[];return e.length===0?this.getArchive().length>0?(this.tamper={id:1,reason:"live-chain-missing"},this.result(1)):{valid:!0,entriesChecked:0,status:"valid",tampered:!1,forks:[],acknowledgedForks:[],forkDetails:[]}:(this.walk(e,"live")&&this.options.includeArchive&&this.walk(this.getArchive(),"archive"),this.tamper||this.checkPins(),this.result(e[0].id))}walk(e,n){for(let i=0;i<e.length;i++){let r=e[i];this.entriesChecked++;let s=this.classify(r,i>0?e[i-1]:void 0);if(s.kind==="tamper")return this.tamper={id:r.id,reason:s.reason},!1;if(s.kind==="fork")this.forks.push({id:r.id,parentId:s.parentId,prevHash:r.prev_hash,actionHash:r.action_hash,table:n,acknowledged:!1});else if(r.action_type===m){if(this.checkSignature(r)==="invalid")return this.tamper={id:r.id,reason:"reanchor-signature-invalid"},!1;this.registerReanchor(r)}this.checkAllSignatures(r)}return!0}classify(e,n){let i=e.hash_algo||"sha256";if(e.action_hash!==o(i,e.action_data))return{kind:"tamper",reason:"action-hash-mismatch"};if(e.id===1)return e.prev_hash===u?{kind:"linked"}:{kind:"tamper",reason:"genesis-link-mismatch"};if(n&&e.prev_hash===o(i,h(n)))return this.idsContiguous(n.id,e.id)?{kind:"linked"}:{kind:"tamper",reason:"id-gap"};let r=this.findEntryById(e.id-1);if(r&&e.prev_hash===o(i,h(r)))return{kind:"linked"};let s=this.lookupParent(i,e.prev_hash);return s!==void 0&&s<e.id?this.idsContiguous(s,e.id)?this.checkSignature(e)==="invalid"?{kind:"tamper",reason:"fork-signature-invalid"}:{kind:"fork",parentId:s}:{kind:"tamper",reason:"id-gap"}:{kind:"tamper",reason:e.prev_hash===u?"unlinked-genesis-prev-hash":"unlinked-prev-hash"}}findEntryById(e){return this.db.prepare("SELECT * FROM witness_chain WHERE id = ?").get(e)??(this.hasArchive()?this.db.prepare("SELECT * FROM witness_chain_archive WHERE id = ?").get(e):void 0)}getArchive(){return this.archiveRows||(this.archiveRows=this.hasArchive()?this.db.prepare("SELECT * FROM witness_chain_archive ORDER BY id ASC").all():[]),this.archiveRows}hasArchive(){return this.archiveExists===void 0&&(this.archiveExists=g(this.db,"witness_chain_archive")),this.archiveExists}lookupParent(e,n){let i=this.parentIndex.get(e);if(!i){i=new Map;let r=this.db.prepare("SELECT * FROM witness_chain").iterate();for(let s of r)i.set(o(e,h(s)),s.id);for(let s of this.getArchive()){let d=o(e,h(s));i.has(d)||i.set(d,s.id)}this.parentIndex.set(e,i)}return i.get(n)}idsContiguous(e,n){let i=n-e-1;return i<=0?!0:(this.hasArchive()?this.db.prepare(`SELECT COUNT(*) AS n FROM (
|
|
3
3
|
SELECT id FROM witness_chain WHERE id > ? AND id < ?
|
|
4
4
|
UNION SELECT id FROM witness_chain_archive WHERE id > ? AND id < ?)`).get(e,n,e,n):this.db.prepare("SELECT COUNT(*) AS n FROM witness_chain WHERE id > ? AND id < ?").get(e,n)).n===i}checkSignature(e){return!e.signature||!e.signer_key_id?"unsigned":!this.keyManager||!this.keyManager.hasKey(e.signer_key_id)?"unverifiable":this.keyManager.verify(c(e),Buffer.from(e.signature,"hex"),e.signer_key_id)?"ok":"invalid"}checkAllSignatures(e){if(this.options.checkSignatures!==!0||!this.keyManager||!e.signature||!e.signer_key_id)return;this.keyManager.verify(c(e),Buffer.from(e.signature,"hex"),e.signer_key_id)||(this.signatureFailures++,this.firstSignatureFailure??=e.id)}registerReanchor(e){let n;try{n=JSON.parse(e.action_data)??{}}catch{return}if(Array.isArray(n.forks))for(let i of n.forks){if(typeof i?.id!="number"||i.id>=e.id||typeof i.parentId!="number"||typeof i.prevHash!="string"||typeof i.actionHash!="string")continue;let r=this.acks.get(i.id)??[];r.push({id:i.id,parentId:i.parentId,prevHash:i.prevHash,actionHash:i.actionHash}),this.acks.set(i.id,r)}if(Array.isArray(n.pins))for(let i of n.pins)typeof i?.id=="number"&&typeof i.hash=="string"&&this.pins.push({id:i.id,hash:i.hash})}checkPins(){for(let e of this.pins){let n=this.findEntryById(e.id);if(!n||y(n)!==e.hash){this.tamper={id:e.id,reason:"reanchored-row-changed"};return}}}result(e){for(let a of this.forks)a.acknowledged=(this.acks.get(a.id)??[]).some(p=>p.parentId===a.parentId&&p.prevHash===a.prevHash&&p.actionHash===a.actionHash);let n=this.forks.filter(a=>!a.acknowledged),i=this.tamper!==void 0||this.signatureFailures>0,r=i?"tampered":n.length>0?"forked":this.forks.length>0?"valid-with-forks":"valid",s=r==="valid"||r==="valid-with-forks",d=n[0]?.id??this.tamper?.id??(this.signatureFailures>0?e:void 0);return{valid:s,entriesChecked:this.entriesChecked,signatureFailures:this.signatureFailures,status:r,tampered:i,forks:this.forks.map(a=>a.id),acknowledgedForks:this.forks.filter(a=>a.acknowledged).map(a=>a.id),forkDetails:this.forks,...d!==void 0&&!s?{brokenAt:d}:{},...i?{tamperedAt:this.tamper?.id??this.firstSignatureFailure,tamperReason:this.tamper?.reason??"signature-invalid"}:{}}}};function R(t,e,n){return new f(t,e,n).run()}function g(t,e){return t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}export{u as a,k as b,v as c,o as d,h as e,c as f,m as g,y as h,f as i,R as j,g as k};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
2
|
var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
|
|
3
3
|
`;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":{this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e}default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&Object.hasOwn(n,e)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"&&Object.hasOwn(n,t)?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function b(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function E(r,n={},e=!1){try{return!!b(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{E as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a as h}from"./chunk-UJNGGFGX.js";import{c as m}from"./chunk-ADUAJIAU.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as w,c as E,d as A,r as de,v as ue}from"./chunk-LD5CFK53.js";import{a as Ce,b as _,d as ee}from"./chunk-JFLU7L3W.js";import{a as le,d as Te}from"./chunk-EJPK7OTR.js";import{i as j}from"./chunk-7R5HC56U.js";import{a as v}from"./chunk-IO5537OM.js";import{c as b}from"./chunk-FZHSG75I.js";import{c as I}from"./chunk-EH2S6AOR.js";import{d as T,e as z}from"./chunk-4MUBW4RT.js";import{a as d,b as L,e as P}from"./chunk-DDEOZPWJ.js";import{e as Ee}from"./chunk-CFWGGRE7.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Re={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as me from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=me.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var pe=Ee(Ce(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&Object.hasOwn(r,i))r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=_e({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=ve("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return he(this.getConnectionString())}};function Ae(l){return new $(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}A();P();v();import{createRequire as ke}from"module";var N=b.create("postgres-writer"),$e=ke(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{b as w,c as E,d as A,r as de,v as ue}from"./chunk-L7NGKANW.js";import{a as Ce,b as _,d as ee}from"./chunk-WTAUF6O4.js";import{a as le,d as Te}from"./chunk-6QRI3JVE.js";import{i as j}from"./chunk-7TA5MUPW.js";import{a as v}from"./chunk-UJNGGFGX.js";import{c as b}from"./chunk-ADUAJIAU.js";import{c as I}from"./chunk-DZGPUGUG.js";import{d as T,e as z}from"./chunk-IA55PFLG.js";import{a as d,b as L,e as P}from"./chunk-W4II6SIH.js";import{e as Ee}from"./chunk-WDEXOLK2.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Re={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as me from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=me.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var pe=Ee(Ce(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&Object.hasOwn(r,i))r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=_e({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=ve("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return he(this.getConnectionString())}};function Ae(l){return new $(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}A();P();v();import{createRequire as ke}from"module";var N=b.create("postgres-writer"),$e=ke(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
3
3
|
INSERT INTO ${u} (${p.join(", ")})
|
|
4
4
|
VALUES ${s.join(", ")}
|
|
5
5
|
${h}
|
|
@@ -26,4 +26,4 @@ import{b as w,c as E,d as A,r as de,v as ue}from"./chunk-LD5CFK53.js";import{a a
|
|
|
26
26
|
INSERT OR REPLACE INTO embeddings
|
|
27
27
|
(key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
|
|
28
28
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
29
|
-
`).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-ZWMQO3L2.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();A();P();ee();v();import{resolve as ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){be.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){be.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function Se(l){return new q(l)}export{k as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,Ae as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se as A};
|
|
29
|
+
`).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-U2ML3OHE.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();A();P();ee();v();import{resolve as ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){be.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){be.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function Se(l){return new q(l)}export{k as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,Ae as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se as A};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{c as p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{c as p}from"./chunk-XCNSGSKV.js";import*as u from"fs";import*as m from"path";var y=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function F(r){for(let o of y){let s=m.join(r,o);if(u.existsSync(s))try{let t=u.readFileSync(s,"utf-8"),c=JSON.parse(t);if(c.total&&c.total.lines)return x(c,r);let n=new Map;for(let e of p(t).files)n.set(e.path,e);return n.size>0?n:null}catch{continue}}return null}function x(r,o){let s=new Map;for(let[t,c]of Object.entries(r)){if(t==="total")continue;let n=c;s.set(t,{path:t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return s.size>0?s:null}function S(r,o){let t=o.split(`
|
|
3
3
|
`).length,n=[r.replace(".ts",".test.ts").replace("/src/","/tests/"),r.replace(".ts",".spec.ts").replace("/src/","/tests/"),r.replace(".ts",".test.ts"),r.replace("/src/","/test/").replace(".ts",".test.ts")].some(f=>u.existsSync(f)),e=(o.match(/\bexport\b/g)||[]).length,a=(o.match(/\b(function|=>)\b/g)||[]).length,i=(o.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,l;if(n){let f=Math.min(i*.005,.15),b=Math.min(t*1e-4,.1);l=.85-f-b}else l=.2+(e>5?.1:0);l=Math.max(.05,Math.min(.95,l));let v=Math.floor(t*l),g=Math.max(a,1),d=Math.max(i,1),C=Math.floor(v*.7),M=Math.floor(g*l*.9),h=Array.from({length:t-v},(f,b)=>b+v+1);return{path:r,lines:{covered:v,total:t},branches:{covered:Math.min(C,d),total:d},functions:{covered:Math.min(M,g),total:g},statements:{covered:v,total:t},uncoveredLines:h,uncoveredBranches:h.slice(0,Math.floor(h.length/2))}}function L(r){let o=e=>r.reduce((a,i)=>a+e(i),0),s=(e,a)=>a>0?Math.round(e/a*100):0,t=o(e=>e.lines.total),c=o(e=>e.lines.covered),n=o(e=>e.statements.total);return{line:s(c,t),branch:s(o(e=>e.branches.covered),o(e=>e.branches.total)),function:s(o(e=>e.functions.covered),o(e=>e.functions.total)),statement:n>0?s(o(e=>e.statements.covered),n):s(c,t),files:r.length}}function B(r,o){let s=o||process.cwd(),t=F(s),c=[],n=[],e=!1;if(t&&t.size>0){e=!0;for(let a of r){let i=m.resolve(a),l=t.get(i)||t.get(a)||t.get(m.relative(s,i));l?c.push({...l,path:a}):n.push(a)}}else for(let a of r){let i=u.existsSync(a)?u.readFileSync(a,"utf-8"):"";c.push(S(a,i))}return{files:c,summary:L(c),instrumented:e,...n.length>0?{unmeasuredFiles:n}:{}}}export{L as a,B as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as s,d as t}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{b as s,d as t}from"./chunk-WDEXOLK2.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>u,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>P,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>F,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>M,isDeterministicDitherEnabled:()=>T,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>m,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>C,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>i,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function u(){return{...e}}function o(n){e={...e,...n}}function i(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function T(){return e.useDeterministicDither}function C(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function F(){return e.useCusumDriftDetection}function M(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function P(){return e.useColdTierGNN}function m(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_RVF_PATTERN_STORE!==void 0&&(n.useRVFPatternStore=process.env.RUVECTOR_USE_RVF_PATTERN_STORE==="true"),process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,u as b,o as c,i as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,T as l,C as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,F as C,M as D,L as E,x as F,h as G,P as H,m as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as l,d as y}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{b as l,d as y}from"./chunk-WTAUF6O4.js";y();import{copyFileSync as k,existsSync as c,readFileSync as u,writeFileSync as s}from"fs";function J(n,r){let e=typeof r=="string"?Buffer.from(r,"utf-8"):r;try{if(c(n)&&u(n).equals(e))return!1}catch{}return typeof r=="string"?s(n,r,"utf-8"):s(n,r),!0}function S(n,r){try{if(c(r)&&u(r).equals(u(n)))return!1}catch{}return k(n,r),!0}function E(n,r,e){try{if(c(n)){let t=o=>o.split(`
|
|
3
3
|
`).filter(i=>!e.test(i)).join(`
|
|
4
4
|
`);if(t(u(n,"utf-8"))===t(r))return!1}}catch{}return s(n,r,"utf-8"),!0}var I=/^\*Generated by AQE v3 init on [^*]+\*$/;function a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n){return JSON.stringify(n,(r,e)=>{if(!a(e))return e;let t={};for(let o of Object.keys(e).sort())t[o]=e[o];return t})}function w(n,r){return d(n)===d(r)}function f(n,r){let e=n;for(let t of r){if(!a(e))return;e=e[t]}return e}function g(n,r,e){let t=n;for(let i of r.slice(0,-1)){if(!a(t[i]))return;t=t[i]}let o=r[r.length-1];o in t&&(t[o]=e)}function p(n,r,e){if(!a(n))return!0;let t=JSON.parse(JSON.stringify(r));for(let o of e){let i=f(n,o);i!==void 0&&f(t,o)!==void 0&&g(t,o,i)}if(!w(n,t))return!0;for(let o of e){let i=f(n,o);i!==void 0&&f(r,o)!==void 0&&g(r,o,i)}return!1}function R(n){if(c(n))try{return l(u(n,"utf-8"))}catch{return}}function N(n,r,e=[]){let t=R(n);return t!==void 0&&!p(t,r,e)?!1:(s(n,JSON.stringify(r,null,2),"utf-8"),!0)}export{J as a,S as b,E as c,I as d,p as e,N as f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as C,d as G}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{b as C,d as G}from"./chunk-WTAUF6O4.js";import{a as R}from"./chunk-VZBC6DP7.js";import{a as x,e as K}from"./chunk-W4II6SIH.js";import{randomUUID as ne}from"crypto";import*as l from"fs";import*as g from"path";import*as k from"os";import*as P from"fs";var H={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},T=1e4,I=20,O=1e4,X=["__proto__","constructor","prototype"];function _(t){return!X.includes(t)}function B(t){let e=t.split(`
|
|
3
3
|
`);if(e.length>T)throw new Error(`YAML content exceeds maximum allowed lines (${T}). File has ${e.length} lines.`);for(let s=0;s<e.length;s++)if(e[s].length>O)throw new Error(`YAML line ${s+1} exceeds maximum allowed length (${O} characters).`);let i={};for(let s=0;s<e.length;s++){let r=e[s];if(r.trim()===""||r.trim().startsWith("#")||r.search(/\S/)!==0)continue;let c=r.match(/^([\w_-]+):\s*(.+)$/);if(c){let[,a,d]=c;_(a)&&(i[a]=w(d))}}let n=["tags","stages","triggers"];for(let s of n){let r=new RegExp(`^${s}:\\s*$`),o=-1;for(let h=0;h<e.length;h++){let u=e[h];if(!(u.trim()===""||u.trim().startsWith("#"))&&r.test(u.trim())){o=h;break}}if(o===-1)continue;let c=[];i[s]=c;let a=e[o].search(/\S/),d=o+1;for(;d<e.length;){let h=e[d];if(h.trim()===""||h.trim().startsWith("#")){d++;continue}let u=h.search(/\S/),m=h.trim();if(u<=a&&!m.startsWith("-"))break;if(m.startsWith("- ")){let f=m.slice(2).trim();if(!f.includes(":")){c.push(w(f)),d++;continue}let p={},y=f.match(/^([\w_-]+):\s*(.*)$/);if(y){let[,S,v]=y;p[S]=w(v)}let V=u;for(d++;d<e.length;){let S=e[d];if(S.trim()===""||S.trim().startsWith("#")){d++;continue}let v=S.search(/\S/),U=S.trim();if(v<=V)break;let L=U.match(/^([\w_-]+):\s*(.*)$/);if(L){let[,E,F]=L;if(F===""){let M=J(e,d+1,v,1);p[E]=M.value,d=M.nextLine;continue}else p[E]=w(F)}d++}c.push(p)}else d++}}return i}function J(t,e,i,n=0){if(n>I)throw new Error(`YAML nesting exceeds maximum allowed depth (${I}).`);let s={},r=null,o=null,c=e;for(;c<t.length;){let d=t[c];if(d.trim()===""||d.trim().startsWith("#")){c++;continue}let h=d.search(/\S/),u=d.trim();if(h<=i)break;if(u.startsWith("- ")){let f=u.slice(2).trim();o&&!Array.isArray(s[o])&&(s[o]=[]),o?s[o].push(w(f)):(r||(r=[]),r.push(w(f))),c++;continue}let m=u.match(/^([\w_-]+):\s*(.*)$/);if(m){let[,f,p]=m;if(!_(f)){c++;continue}p===""?(o=f,s[f]=[]):(s[f]=w(p),o=null)}c++}if(r&&Object.keys(s).length===0)return{value:r,nextLine:c};let a=Object.keys(s);return a.length===1&&Array.isArray(s[a[0]])?{value:s[a[0]],nextLine:c}:{value:s,nextLine:c}}function w(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let e=Number(t);return!isNaN(e)&&t!==""?e:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(n=>w(n.trim())):t}function he(t){let e=[];if(!P.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let i;try{i=P.readFileSync(t,"utf-8")}catch(n){return{success:!1,errors:[`Failed to read file: ${n}`]}}return Q(i,t)}function Q(t,e){let i=[],n;try{n=B(t)}catch(o){return{success:!1,errors:[`Invalid YAML syntax: ${o}`]}}if((!n.name||typeof n.name!="string")&&i.push('Pipeline must have a "name" field'),(!n.stages||!Array.isArray(n.stages))&&i.push('Pipeline must have a "stages" array'),i.length>0)return{success:!1,errors:i};let s={name:n.name,description:n.description,version:n.version||"1.0.0",schedule:n.schedule,stages:n.stages.map((o,c)=>{let a=o;return{name:a.name||`stage-${c}`,command:a.command,params:a.params,depends_on:a.depends_on,condition:a.condition,timeout:a.timeout,retry:a.retry,continue_on_failure:a.continue_on_failure}}),triggers:n.triggers,tags:n.tags,timeout:n.timeout};for(let o=0;o<s.stages.length;o++){let c=s.stages[o];c.command||i.push(`Stage ${o+1} (${c.name}) must have a "command" field`)}if(i.length>0)return{success:!1,pipeline:s,errors:i};let r=Z(s,e);return{success:!0,pipeline:s,workflow:r,errors:[]}}function Z(t,e){let i=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,n=t.stages.map((r,o)=>{let c=W(r.command),a={};if(r.params)for(let[h,u]of Object.entries(r.params))_(h)&&(a[h]=`input.${h}`);let d={id:`stage-${r.name.replace(/\s+/g,"-").toLowerCase()}`,name:r.name,domain:c.domain,action:c.action,inputMapping:Object.keys(a).length>0?a:void 0,dependsOn:r.depends_on?.map(h=>`stage-${h.replace(/\s+/g,"-").toLowerCase()}`),timeout:r.timeout?r.timeout*1e3:void 0,continueOnFailure:r.continue_on_failure};return r.condition&&(d.condition={path:r.condition.path,operator:r.condition.operator,value:r.condition.value}),r.retry&&(d.retry={maxAttempts:r.retry.max_attempts||3,backoffMs:(r.retry.backoff_seconds||1)*1e3}),d}),s=t.triggers?.map(r=>{let o={eventType:ee(r),sourceDomain:r.source_domain};return r.condition&&(o.condition={path:r.condition.path,operator:r.condition.operator,value:r.condition.value}),o});return{id:i,name:t.name,description:t.description||`Pipeline from ${e||"inline YAML"}`,version:t.version||"1.0.0",steps:n,triggers:s,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function W(t){let e=t.trim().replace(/\s+/g," ").toLowerCase();for(let[i,n]of Object.entries(H))if(e.startsWith(i.toLowerCase()))return n;return e.includes("test")&&e.includes("generate")?{domain:"test-generation",action:"generateTests"}:e.includes("test")&&(e.includes("execute")||e.includes("run"))?{domain:"test-execution",action:"execute"}:e.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:e.includes("quality")||e.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:e.includes("security")||e.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:e.includes("defect")||e.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function ee(t){let e=t.event.toLowerCase();return e==="push"?"code-intelligence.CodePushed":e==="pull_request"||e==="pr"?"code-intelligence.PullRequestOpened":e==="schedule"?"workflow.ScheduleTrigger":e==="quality_gate"?"quality-assessment.QualityGateEvaluated":e==="test_complete"?"test-execution.TestRunCompleted":e}function fe(t){let e=[],i=[];if(t.name||e.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)e.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let n=new Set;for(let r=0;r<t.stages.length;r++){let o=t.stages[r],c=`stages[${r}]`;if(n.has(o.name)&&e.push({path:`${c}.name`,message:`Duplicate stage name: ${o.name}`,severity:"error"}),n.add(o.name),o.command?W(o.command).domain==="learning-optimization"&&!o.command.toLowerCase().includes("learn")&&i.push({path:`${c}.command`,message:`Command "${o.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):e.push({path:`${c}.command`,message:"Stage must have a command",severity:"error"}),o.depends_on)for(let a of o.depends_on)t.stages.some(d=>d.name===a)||e.push({path:`${c}.depends_on`,message:`Unknown dependency: ${a}`,severity:"error"});o.timeout!==void 0&&o.timeout<=0&&e.push({path:`${c}.timeout`,message:"Timeout must be a positive number",severity:"error"}),o.retry&&o.retry.max_attempts!==void 0&&o.retry.max_attempts<1&&e.push({path:`${c}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let s=te(t.stages);s&&e.push({path:"stages",message:`Circular dependency detected: ${s}`,severity:"error"})}if(t.schedule&&(A(t.schedule)||e.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let n=0;n<t.triggers.length;n++){let s=t.triggers[n],r=`triggers[${n}]`;s.event||e.push({path:`${r}.event`,message:"Trigger must have an event type",severity:"error"}),s.source_domain&&!R.includes(s.source_domain)&&i.push({path:`${r}.source_domain`,message:`Unknown domain: ${s.source_domain}`,severity:"warning"})}return{valid:e.length===0,errors:e,warnings:i}}function te(t){let e=new Set,i=new Set,n=(s,r)=>{if(i.has(s))return[...r,s].join(" -> ");if(e.has(s))return null;e.add(s),i.add(s);let o=t.find(c=>c.name===s);if(o?.depends_on)for(let c of o.depends_on){let a=n(c,[...r,s]);if(a)return a}return i.delete(s),null};for(let s of t){let r=n(s.name,[]);if(r)return r}return null}function A(t){return q(t)!==void 0}function q(t){let i=(Object.hasOwn(D,t)?D[t]:t).trim().split(/\s+/);if(i.length!==5)return;let n=[[0,59],[0,23],[1,31],[1,12],[0,7]],s=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/],r=[];for(let o=0;o<i.length;o++){let[c,a]=n[o],d=new Set;for(let h of i[o].split(",")){if(!s[o].test(h))return;let u=/^(\*|\d+)(?:-(\d+))?(?:\/(\d+))?$/.exec(h);if(!u||u[1]==="*"&&u[2]!==void 0)return;let m=u[1]==="*"?c:Number(u[1]),f=u[2]!==void 0?Number(u[2]):u[1]==="*"||u[3]!==void 0?a:m,p=u[3]===void 0?1:Number(u[3]);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(f)||!Number.isSafeInteger(p)||p<=0||m<c||f>a||m>f)return;for(let y=m;y<=f;y+=p)d.add(o===4&&y===7?0:y)}r.push(d)}return{fields:r,wildcardDay:i[2].startsWith("*")||i[4].startsWith("*")}}function me(t){let e={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(e[t])return e[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let i=t.trim().split(/\s+/);if(i.length!==5)return t;let[n,s,r,o,c]=i;return n==="0"&&s==="0"&&r==="*"&&o==="*"&&c==="*"?"Daily at midnight":n==="0"&&r==="*"&&o==="*"&&c==="*"?`Daily at ${s}:00`:n!=="*"&&s!=="*"&&r==="*"&&o==="*"?`Daily at ${s}:${n.padStart(2,"0")}`:s==="*"&&n==="0"?"Every hour":n!=="*"&&s==="*"?`Every hour at minute ${n}`:t}function b(t,e=new Date){let i=q(t);if(!i)throw new Error(`Invalid cron expression: ${t}`);if(!Number.isFinite(e.getTime()))throw new Error("Invalid schedule start date");let[n,s,r,o,c]=i.fields,a=new Date(Math.floor(e.getTime()/6e4)*6e4+6e4),d=new Date(e);d.setFullYear(e.getFullYear()+400);let h=Number.isFinite(d.getTime())?d.getTime():864e13;for(;Number.isFinite(a.getTime())&&a.getTime()<=h;){let u=r.has(a.getDate()),m=c.has(a.getDay());if(!(o.has(a.getMonth()+1)&&(i.wildcardDay?u&&m:u||m))){a.setHours(24,0,0,0);continue}if(s.has(a.getHours())&&n.has(a.getMinutes()))return a;a=new Date(a.getTime()+6e4)}throw new Error(`No matching cron date within a 400-year Gregorian cycle and the supported Date range: ${t}`)}G();K();var ie=".aqe",se="schedules.json",re="1.0.0",N=5e3,oe=50,Y=10*1024*1024,$=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let i=k.homedir(),n=g.resolve(e),s=g.resolve(i);if(n.startsWith(s+g.sep)||n===s)return;let r=process.cwd(),o=g.resolve(r);if(n.startsWith(o+g.sep)||n===o)return;let c=k.tmpdir(),a=g.resolve(c);if(!(n.startsWith(a+g.sep)||n===a))throw new Error(`Security: Custom schedulesPath must be within home directory (${i}), current working directory (${r}), or temp directory (${c}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=k.homedir();return g.join(e,ie,se)}async initialize(){if(this.initialized)return;let e=g.dirname(this.schedulesPath);l.existsSync(e)||(l.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!l.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=l.readFileSync(this.schedulesPath,"utf-8"),{file:i,skipped:n}=this.parseSchedulesFile(e);return n.length>0&&console.warn(`[PersistentScheduler] Skipped ${n.length} malformed schedule entries in ${this.schedulesPath} (not an object, no id, or duplicate id)`),this.log(`Loaded ${i.schedules.length} schedules`),i.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let{schedules:i,skipped:n}=this.loadForWrite(),s=i.findIndex(r=>r.id===e.id);s>=0?(i[s]=e,this.log(`Updated schedule: ${e.id}`)):(i.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(i,n)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let{schedules:i,skipped:n}=this.loadForWrite(),s=i.filter(r=>r.id!==e);if(s.length===i.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(s,n),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(n=>n.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),i=new Date;return e.filter(n=>n.enabled?new Date(n.nextRun)<=i:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let{schedules:i,skipped:n}=this.loadForWrite(),s=i.find(o=>o.id===e);if(!s)throw new Error(`Schedule not found: ${e}`);let r=new Date;s.lastRun=r.toISOString(),s.disabledReason||(s.nextRun=b(s.schedule,r).toISOString()),await this.writeSchedules(i,n),this.log(`Marked executed: ${e}, next run: ${s.nextRun}`)})}async setEnabled(e,i){await this.initialize(),await this.withFileLock(async()=>{let{schedules:n,skipped:s}=this.loadForWrite(),r=n.find(o=>o.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);if(i&&r.disabledReason)throw new Error(`Cannot enable schedule ${e}: ${r.disabledReason}`);r.enabled=i,i&&(r.nextRun=b(r.schedule,new Date).toISOString()),await this.writeSchedules(n,s),this.log(`Set enabled=${i}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(i=>i.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(n=>n.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{let{skipped:e}=this.loadForWrite();await this.writeSchedules([],e),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),i=new Date;return{total:e.length,enabled:e.filter(n=>n.enabled).length,disabled:e.filter(n=>!n.enabled).length,due:e.filter(n=>n.enabled&&new Date(n.nextRun)<=i).length}}loadForWrite(){if(!l.existsSync(this.schedulesPath))return{schedules:[],skipped:[]};try{let e=l.readFileSync(this.schedulesPath,"utf-8"),{file:i,skipped:n}=this.parseSchedulesFile(e);return{schedules:i.schedules,skipped:n}}catch(e){return this.backupCorruptFile(e),{schedules:[],skipped:[]}}}parseSchedulesFile(e){let i=Buffer.byteLength(e,"utf-8");if(i>Y)throw new Error(`Schedules file exceeds maximum allowed size (${Y/(1024*1024)}MB). File is ${(i/(1024*1024)).toFixed(2)}MB.`);let n=C(e);if(!z(n)||!Array.isArray(n.schedules))throw new Error("Invalid schedules file: missing schedules array");let s=[],r=[],o=new Set;for(let c of n.schedules){if(!z(c)||typeof c.id!="string"||c.id.length===0||o.has(c.id)){r.push(c);continue}let a=c;o.add(a.id);let d=ae(c);d?(a.disabledReason=d,a.enabled&&console.warn(`[PersistentScheduler] Disabled schedule ${a.id}: ${d}`),a.enabled=!1):delete a.disabledReason,s.push(a)}return{file:{...n,schedules:s},skipped:r}}async writeSchedules(e,i=[]){if(i.length>0){let r=`${this.schedulesPath}.quarantine.${Date.now()}.json`;l.writeFileSync(r,JSON.stringify({quarantinedAt:new Date().toISOString(),reason:"Malformed schedule entries (not an object, no id, or duplicate id)",entries:i},null,2),{encoding:"utf-8",flag:"wx"}),console.warn(`[PersistentScheduler] Moved ${i.length} malformed schedule entries to ${r}`)}let n={version:re,updatedAt:new Date().toISOString(),schedules:e},s=JSON.stringify(n,null,2);l.writeFileSync(this.schedulesPath,s,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let i=x(e);this.log(`Corrupt schedules file detected: ${i}`),this.backupCorruptFile(e);try{l.existsSync(this.schedulesPath)&&(l.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(n){this.log(`Failed to remove corrupt file: ${n}`)}}backupCorruptFile(e){this.log(`Corrupt schedules file detected: ${x(e)}`);let i=`${this.schedulesPath}.corrupt.${Date.now()}`;try{l.existsSync(this.schedulesPath)&&(l.copyFileSync(this.schedulesPath,i,l.constants.COPYFILE_EXCL),this.log(`Backed up corrupt file to: ${i}`))}catch(n){this.log(`Failed to backup corrupt file: ${n}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;l.existsSync(this.lockFile);){try{let i=l.statSync(this.lockFile);if(Date.now()-i.mtimeMs>N){l.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>N)throw new Error("Timeout waiting for scheduler lock");await this.sleep(oe)}try{l.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(i){if(i.code==="EEXIST")return this.acquireLock();throw i}}releaseLock(){try{l.existsSync(this.lockFile)&&l.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(i=>setTimeout(i,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function z(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ae(t){if(!Object.prototype.hasOwnProperty.call(t,"schedule"))return"Missing cron expression (no schedule field)";if(typeof t.schedule!="string"||!A(t.schedule))return`Invalid cron expression: ${String(t.schedule)}`;if(typeof t.workflowId!="string"||t.workflowId.length===0)return"Missing workflowId"}function ce(t={}){return new $(t)}function j(){let t=Date.now().toString(36),e=ne().slice(0,8);return`sched-${t}-${e}`}function de(t){let e=new Date;return{id:j(),workflowId:t.workflowId,pipelinePath:t.pipelinePath,schedule:t.schedule,scheduleDescription:t.scheduleDescription,nextRun:b(t.schedule,e).toISOString(),enabled:t.enabled??!0,createdAt:e.toISOString()}}export{he as a,fe as b,me as c,$ as d,ce as e,j as f,de as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as ae,b as oe}from"./chunk-OYJC3YON.js";import{S as ie,i as D,p as $}from"./chunk-76SNL7GU.js";import{b as g,d as ne,f as W}from"./chunk-CFWGGRE7.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
|
|
2
|
+
import{a as ae,b as oe}from"./chunk-YVJEUX3I.js";import{S as ie,i as D,p as $}from"./chunk-35MIUSXQ.js";import{b as g,d as ne,f as W}from"./chunk-WDEXOLK2.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
|