agentic-qe 3.15.5 → 3.15.6
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/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
- package/.claude/skills/qe-court/evals/qe-court.yaml +3 -2
- package/.claude/skills/qe-quality-assessment/schemas/output.json +12 -2
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +121 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +9 -2
- package/assets/skills/qe-court/evals/qe-court.yaml +3 -2
- package/assets/skills/qe-quality-assessment/schemas/output.json +12 -2
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-PP3XIXDV.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-CCTTGCQS.js → agent-booster-wasm-SY7UCLBL.js} +2 -2
- package/dist/cli/chunks/{agent-handler-DHYUF3NX.js → agent-handler-KAMYBU3S.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-642W7CYX.js → agent-memory-branch-2CAW3KUM.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-VDUQJKKY.js +2 -0
- package/dist/cli/chunks/{arena-NW2JVAFY.js → arena-4OFLJ3R2.js} +2 -2
- package/dist/cli/chunks/{arena-MUCC7UUN.js → arena-QCCVIOAH.js} +4 -4
- package/dist/cli/chunks/{audit-VKQTZJAA.js → audit-RBDQJQJB.js} +3 -3
- package/dist/cli/chunks/base-QSYWWPCE.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-7ZUFVWLQ.js → better-sqlite3-5JRACCDQ.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7LKAWSBI.js → brain-handler-W4QIIRT4.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HUNXJKM4.js → branch-enumerator-IBNGI572.js} +2 -2
- package/dist/cli/chunks/{browser-ZSZEYUDP.js → browser-GMSCVAOI.js} +2 -2
- package/dist/cli/chunks/browser-workflow-WXXPBSCM.js +2 -0
- package/dist/cli/chunks/{chunk-RUSLEOMC.js → chunk-22OZIJAD.js} +2 -2
- package/dist/cli/chunks/{chunk-WR64BKUE.js → chunk-24ZSGYC6.js} +1 -1
- package/dist/cli/chunks/{chunk-CR2JUANW.js → chunk-2CIDFR2H.js} +3 -3
- package/dist/cli/chunks/{chunk-SDWMLT7B.js → chunk-2IWPJUVV.js} +5 -5
- package/dist/cli/chunks/{chunk-VYDNLQJN.js → chunk-2ZTWPMTK.js} +2 -2
- package/dist/cli/chunks/{chunk-WN55MNZ2.js → chunk-34MDMFET.js} +2 -2
- package/dist/cli/chunks/{chunk-D3G2NN7F.js → chunk-3DJNKNBR.js} +66 -65
- package/dist/cli/chunks/{chunk-XQRE2HWM.js → chunk-3NJ7O3OH.js} +2 -2
- package/dist/cli/chunks/chunk-45MVRQG4.js +2 -0
- package/dist/cli/chunks/chunk-46HBVDMU.js +2 -0
- package/dist/cli/chunks/{chunk-MNQ36MAF.js → chunk-47Q7JL3V.js} +2 -2
- package/dist/cli/chunks/chunk-4CLDYT36.js +2 -0
- package/dist/cli/chunks/{chunk-ORTBRO7F.js → chunk-4KOVHQXK.js} +2 -2
- package/dist/cli/chunks/{chunk-B2UHTA4Q.js → chunk-4POOJYXA.js} +1 -1
- package/dist/cli/chunks/{chunk-QXY3IRBW.js → chunk-5DH5QI7G.js} +26 -26
- package/dist/cli/chunks/{chunk-7BIYJRQJ.js → chunk-5GIJU2ZY.js} +2 -2
- package/dist/cli/chunks/{chunk-6LG5UEQE.js → chunk-5HAPS6VD.js} +2 -2
- package/dist/cli/chunks/{chunk-OU4ZAWCC.js → chunk-5LST62QR.js} +2 -2
- package/dist/cli/chunks/{chunk-Y2E3IJ53.js → chunk-5MT7DMD7.js} +2 -2
- package/dist/cli/chunks/{chunk-6UYN5PHA.js → chunk-5NC7QEJ6.js} +4 -4
- package/dist/cli/chunks/{chunk-3DTEQHFB.js → chunk-5UPIL62W.js} +3 -3
- package/dist/cli/chunks/{chunk-YINFES3E.js → chunk-5VUIXDY2.js} +2 -2
- package/dist/cli/chunks/chunk-5VZVMO7B.js +3 -0
- package/dist/cli/chunks/{chunk-JCC7QEKZ.js → chunk-624QRKQX.js} +1 -1
- package/dist/cli/chunks/{chunk-HIUNCO2W.js → chunk-66NW3ZB4.js} +2 -2
- package/dist/cli/chunks/{chunk-4AZP7ZCW.js → chunk-6HWARQWV.js} +2 -2
- package/dist/cli/chunks/{chunk-LNO5IWGH.js → chunk-6MXAJBEA.js} +1 -1
- package/dist/cli/chunks/{chunk-XNEEYXR2.js → chunk-6R3FBFCJ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZT3GUYM5.js → chunk-6RDVY26I.js} +2 -2
- package/dist/cli/chunks/{chunk-W3ZGNNDV.js → chunk-6T6AHVLF.js} +1 -1
- package/dist/cli/chunks/{chunk-JANLATHN.js → chunk-6WOZUSSN.js} +2 -2
- package/dist/cli/chunks/chunk-72MQCZSM.js +2 -0
- package/dist/cli/chunks/chunk-7QVPMH25.js +3 -0
- package/dist/cli/chunks/{chunk-HLFDC4SF.js → chunk-7SAMMQVS.js} +1 -1
- package/dist/cli/chunks/{chunk-644DFAGS.js → chunk-7TJZDRDU.js} +1 -1
- package/dist/cli/chunks/{chunk-BYXNHGQC.js → chunk-7TVIX4WL.js} +2 -2
- package/dist/cli/chunks/{chunk-FBEXG4HD.js → chunk-7VTKR44N.js} +2 -2
- package/dist/cli/chunks/{chunk-UE22ODHN.js → chunk-7XTANLTN.js} +1 -1
- package/dist/cli/chunks/chunk-7XUB7U6Z.js +4 -0
- package/dist/cli/chunks/{chunk-HPLMX62I.js → chunk-A74J23QB.js} +2 -2
- package/dist/cli/chunks/{chunk-VRJPH3LG.js → chunk-A7ANPS4E.js} +2 -2
- package/dist/cli/chunks/{chunk-IHFUEPZH.js → chunk-AJT3XDRD.js} +2 -2
- package/dist/cli/chunks/{chunk-EUEHBERE.js → chunk-ALCIUWFC.js} +1 -1
- package/dist/cli/chunks/{chunk-NMJVG22Z.js → chunk-AUN4FG7V.js} +1 -1
- package/dist/cli/chunks/{chunk-DWZI3IVB.js → chunk-AUOSHM63.js} +2 -2
- package/dist/cli/chunks/{chunk-7EZLOC4K.js → chunk-AX26QJ6T.js} +2 -2
- package/dist/cli/chunks/{chunk-PDPEMBFV.js → chunk-B7RHBKHL.js} +2 -2
- package/dist/cli/chunks/{chunk-DEGWCUMY.js → chunk-BAYGQRNP.js} +2 -2
- package/dist/cli/chunks/{chunk-ONCH5AXU.js → chunk-BIXRTOH3.js} +18 -18
- package/dist/cli/chunks/{chunk-U4TV75AC.js → chunk-BO7UFNYV.js} +2 -2
- package/dist/cli/chunks/{chunk-FNAYDITO.js → chunk-BUTGIVKW.js} +1 -1
- package/dist/cli/chunks/{chunk-HBYQYGXP.js → chunk-BXATKI5S.js} +2 -2
- package/dist/cli/chunks/{chunk-BO4PKNYP.js → chunk-CCL436IU.js} +32 -27
- package/dist/cli/chunks/{chunk-XIE7OHML.js → chunk-CEXNW5TR.js} +1 -1
- package/dist/cli/chunks/{chunk-663ZFPUL.js → chunk-CLAMMGY3.js} +2 -2
- package/dist/cli/chunks/{chunk-PVAE65B4.js → chunk-CR66HNAE.js} +1 -1
- package/dist/cli/chunks/{chunk-LRASYSGV.js → chunk-CZBIREL5.js} +2 -2
- package/dist/cli/chunks/{chunk-WLIYWBQR.js → chunk-D5N2O5EH.js} +2 -2
- package/dist/cli/chunks/{chunk-A337MD3C.js → chunk-DA7DGDTI.js} +2 -2
- package/dist/cli/chunks/{chunk-WC47GICZ.js → chunk-DLSFT6PO.js} +2 -2
- package/dist/cli/chunks/{chunk-KHCALIFP.js → chunk-DQNUPEY5.js} +2 -2
- package/dist/cli/chunks/{chunk-GTSOFCMQ.js → chunk-EECF4CMA.js} +1 -1
- package/dist/cli/chunks/{chunk-5BOZCMXZ.js → chunk-EF5UHDCG.js} +1 -1
- package/dist/cli/chunks/{chunk-L6SVCNXK.js → chunk-EJ4KZFZN.js} +1 -1
- package/dist/cli/chunks/{chunk-CFPR24YK.js → chunk-ELI4GDQO.js} +2 -2
- package/dist/cli/chunks/{chunk-KJ3KBP24.js → chunk-F3KS3TAB.js} +2 -2
- package/dist/cli/chunks/{chunk-RMJ7PJOS.js → chunk-F7A2UBZO.js} +2 -2
- package/dist/cli/chunks/{chunk-U6OVPMQX.js → chunk-FOJRPEIP.js} +2 -2
- package/dist/cli/chunks/{chunk-JYY7AYGA.js → chunk-FQ5N666N.js} +1 -1
- package/dist/cli/chunks/{chunk-4XSCZVON.js → chunk-FU7LNUD7.js} +2 -2
- package/dist/cli/chunks/{chunk-OW42F2TX.js → chunk-GFB6BZWU.js} +2 -2
- package/dist/cli/chunks/{chunk-JI77KJP7.js → chunk-GI5HWS4H.js} +1 -1
- package/dist/cli/chunks/{chunk-4UXPDV7E.js → chunk-GNYOHZVV.js} +1 -1
- package/dist/cli/chunks/{chunk-VCKDVOPD.js → chunk-GVRFSXY6.js} +2 -2
- package/dist/cli/chunks/{chunk-PURHGLEC.js → chunk-GWM4M5NF.js} +1 -1
- package/dist/cli/chunks/{chunk-BY646JOM.js → chunk-HAN4MS5T.js} +2 -2
- package/dist/cli/chunks/{chunk-OGYWWZU7.js → chunk-HEGGV2PT.js} +2 -2
- package/dist/cli/chunks/{chunk-FHUJCVT3.js → chunk-HOEWMEF2.js} +2 -2
- package/dist/cli/chunks/{chunk-CXOXUBYU.js → chunk-HZFK2Z2Z.js} +1 -1
- package/dist/cli/chunks/chunk-I7WAW7TM.js +2 -0
- package/dist/cli/chunks/{chunk-E4VIVMDL.js → chunk-IEPWO4XP.js} +2 -2
- package/dist/cli/chunks/{chunk-DTJODGCE.js → chunk-ITIJ23K2.js} +2 -2
- package/dist/cli/chunks/{chunk-AQN5EDBM.js → chunk-IVJIHZSM.js} +1 -1
- package/dist/cli/chunks/{chunk-PHP4UJYP.js → chunk-JAPBSSFY.js} +1 -1
- package/dist/cli/chunks/{chunk-A2WOQO2N.js → chunk-JCE76MPP.js} +2 -2
- package/dist/cli/chunks/{chunk-A5J4XJS6.js → chunk-JPJEAK4G.js} +1 -1
- package/dist/cli/chunks/{chunk-3OAQPN2N.js → chunk-JYKQVYX2.js} +2 -2
- package/dist/cli/chunks/{chunk-MQGEZA2A.js → chunk-K55EAWZ5.js} +2 -2
- package/dist/cli/chunks/chunk-KCB6P463.js +3 -0
- package/dist/cli/chunks/{chunk-L375O3CZ.js → chunk-KIDOBLUO.js} +2 -2
- package/dist/cli/chunks/{chunk-NLDFNAOS.js → chunk-KYVIOC3C.js} +2 -2
- package/dist/cli/chunks/{chunk-CQMHDAJS.js → chunk-L2TDHJR3.js} +2 -2
- package/dist/cli/chunks/{chunk-FE3AIZI6.js → chunk-L4D3TPFP.js} +1 -1
- package/dist/cli/chunks/{chunk-VLOIEVER.js → chunk-LAY7NCQK.js} +3 -3
- package/dist/cli/chunks/{chunk-WT3JC4A6.js → chunk-LCCTJ2PC.js} +2 -2
- package/dist/cli/chunks/{chunk-VML4SG3X.js → chunk-LJCEDTUM.js} +3 -3
- package/dist/cli/chunks/{chunk-NF6AFIAX.js → chunk-LMAEMVPA.js} +1 -1
- package/dist/cli/chunks/{chunk-2XYTS2WY.js → chunk-LZWJ5BMP.js} +2 -2
- package/dist/cli/chunks/{chunk-PHAQWAEV.js → chunk-MP3FSUNB.js} +2 -2
- package/dist/cli/chunks/{chunk-IJ2EXSMO.js → chunk-MQCTLTGE.js} +2 -2
- package/dist/cli/chunks/{chunk-GRIPCYW5.js → chunk-MQTA6KIO.js} +1 -1
- package/dist/cli/chunks/{chunk-GGDKOJVF.js → chunk-NBUXM5X6.js} +10 -6
- package/dist/cli/chunks/{chunk-DPYDUKVZ.js → chunk-NHRF3V4B.js} +2 -2
- package/dist/cli/chunks/chunk-NMY4KTWA.js +16 -0
- package/dist/cli/chunks/chunk-NYS2GUNO.js +2 -0
- package/dist/cli/chunks/{chunk-AUZXRFOX.js → chunk-ONPPBLRB.js} +2 -2
- package/dist/cli/chunks/{chunk-HGBJ2QQ4.js → chunk-OPDZBRIL.js} +2 -2
- package/dist/cli/chunks/{chunk-DXVZBJE4.js → chunk-OQ4S6B7P.js} +1 -1
- package/dist/cli/chunks/{chunk-Y2WMPEUP.js → chunk-ORBODZSO.js} +2 -2
- package/dist/cli/chunks/{chunk-IJOFZBXD.js → chunk-ORFL3YXB.js} +2 -2
- package/dist/cli/chunks/{chunk-BMWAWZAN.js → chunk-P7DXVL2S.js} +2 -2
- package/dist/cli/chunks/chunk-PEMSXSP2.js +4 -0
- package/dist/cli/chunks/chunk-PS6WFCA4.js +6 -0
- package/dist/cli/chunks/{chunk-DPV33C77.js → chunk-Q2RBOC7V.js} +2 -2
- package/dist/cli/chunks/{chunk-3AYYGR6W.js → chunk-QLKUCMZC.js} +1 -1
- package/dist/cli/chunks/{chunk-EVCFUYYK.js → chunk-QLYO3H7E.js} +9 -9
- package/dist/cli/chunks/{chunk-3SH23PS3.js → chunk-QS5KZYUZ.js} +2 -2
- package/dist/cli/chunks/{chunk-3YNP33GB.js → chunk-R363XXGH.js} +2 -2
- package/dist/cli/chunks/chunk-RD5BYLN7.js +2 -0
- package/dist/cli/chunks/{chunk-MS3Z2CP5.js → chunk-RFDFET3O.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLBBX24Q.js → chunk-RHIQ6QO5.js} +357 -351
- package/dist/cli/chunks/chunk-RLB7K7QP.js +2 -0
- package/dist/cli/chunks/{chunk-3YASZPLO.js → chunk-RUTO67PT.js} +2 -2
- package/dist/cli/chunks/{chunk-V7GNUVYI.js → chunk-RV6HSMKJ.js} +1 -1
- package/dist/cli/chunks/{chunk-4PT5KNXL.js → chunk-SOSJWM3E.js} +4 -4
- package/dist/cli/chunks/{chunk-6ZIDZ4TJ.js → chunk-SV5BUYHH.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTC5FBL6.js → chunk-TL5GV3PR.js} +8 -8
- package/dist/cli/chunks/{chunk-GKPRECLL.js → chunk-TLUIO37P.js} +2 -2
- package/dist/cli/chunks/{chunk-FWYJ6UDX.js → chunk-TUDENMAE.js} +2 -2
- package/dist/cli/chunks/chunk-TVLOED6O.js +2 -0
- package/dist/cli/chunks/{chunk-3QD7U3FY.js → chunk-UB6DQGWM.js} +2 -2
- package/dist/cli/chunks/{chunk-SAPIRK2G.js → chunk-UHHMAKPE.js} +1 -1
- package/dist/cli/chunks/{chunk-35MDATQE.js → chunk-ULCHPPW2.js} +1 -1
- package/dist/cli/chunks/chunk-V3OLS2NG.js +2 -0
- package/dist/cli/chunks/{chunk-UXZEVIFX.js → chunk-VAYZ5QIE.js} +1 -1
- package/dist/cli/chunks/{chunk-VH3EB6ZG.js → chunk-VCONCVSY.js} +3 -3
- package/dist/cli/chunks/{chunk-QPV3OKX2.js → chunk-VVF337SV.js} +2 -2
- package/dist/cli/chunks/{chunk-XNHB6TLC.js → chunk-WKDWRRDT.js} +2 -2
- package/dist/cli/chunks/{chunk-RUJLVJDE.js → chunk-X2DR27AY.js} +2 -2
- package/dist/cli/chunks/{chunk-47GEI2LT.js → chunk-X33F7NXH.js} +3 -3
- package/dist/cli/chunks/{chunk-MB4VFAJC.js → chunk-XBEI2JBA.js} +2 -2
- package/dist/cli/chunks/{chunk-OQDC7GCM.js → chunk-XBFQJZWX.js} +2 -2
- package/dist/cli/chunks/{chunk-EAYQCBXL.js → chunk-XFPQIWEH.js} +3 -3
- package/dist/cli/chunks/{chunk-2KWI3MT3.js → chunk-XPB5BVU6.js} +2 -2
- package/dist/cli/chunks/{chunk-DL5JENWD.js → chunk-XQ53PZEF.js} +3 -3
- package/dist/cli/chunks/{chunk-BZFT4QDQ.js → chunk-XZ46CI35.js} +2 -2
- package/dist/cli/chunks/chunk-YLNYPQDR.js +2 -0
- package/dist/cli/chunks/{chunk-EOR3RECZ.js → chunk-YNG7E26C.js} +2 -2
- package/dist/cli/chunks/{chunk-6JFGB2JB.js → chunk-YXU35GGD.js} +1 -1
- package/dist/cli/chunks/{chunk-JNMUVBAJ.js → chunk-ZCP4P6O2.js} +2 -2
- package/dist/cli/chunks/{chunk-Y7GPLOXB.js → chunk-ZL5LJT7D.js} +2 -2
- package/dist/cli/chunks/{chunk-PCCIZFD7.js → chunk-ZOUEQ6DL.js} +1 -1
- package/dist/cli/chunks/{chunk-FQKEZVN6.js → chunk-ZSBD4FUX.js} +2 -2
- package/dist/cli/chunks/chunk-ZTB32K5N.js +5 -0
- package/dist/cli/chunks/{chunk-X52TMBHU.js → chunk-ZUTFHGEO.js} +1 -1
- package/dist/cli/chunks/ci-GEJCXMBK.js +81 -0
- package/dist/cli/chunks/{ci-config-XDDZOOEI.js → ci-config-2ZVV4OXL.js} +2 -2
- package/dist/cli/chunks/{ci-output-7ZUQI4U6.js → ci-output-E45OGVPR.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ALXKCFAL.js → circuit-breaker-X73ITYZC.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-RL7K2NI2.js → claude-flow-setup-W4PPH46C.js} +2 -2
- package/dist/cli/chunks/client-6XKSQ4JT.js +2 -0
- package/dist/cli/chunks/{cline-installer-2Z2QQKC3.js → cline-installer-NUEPMWDE.js} +2 -2
- package/dist/cli/chunks/{code-QSZTDINQ.js → code-6WQHBS7G.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-5CGR5D3Y.js → code-index-extractor-BXQIFIFT.js} +2 -2
- package/dist/cli/chunks/{codex-installer-7JLSEDE5.js → codex-installer-Z337R2KH.js} +2 -2
- package/dist/cli/chunks/{completions-U4NBSXEB.js → completions-F5DMYFHV.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-WYZD2YSY.js → complexity-analyzer-W2SYPZDI.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-UPXINJFT.js → continuedev-installer-ZCHUIFTN.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-WIVYQRIF.js → copilot-installer-M5JNODXF.js} +2 -2
- package/dist/cli/chunks/core-handlers-OJYW4Y6M.js +2 -0
- package/dist/cli/chunks/{cost-tracker-RIN4JDDM.js → cost-tracker-LSYTHBHV.js} +2 -2
- package/dist/cli/chunks/coverage-PGMRS5SS.js +49 -0
- package/dist/cli/chunks/cross-domain-router-QVUPQ2SC.js +2 -0
- package/dist/cli/chunks/{cursor-installer-POM7NGCC.js → cursor-installer-XPUA73UW.js} +2 -2
- package/dist/cli/chunks/{daemon-HFGKQ6LB.js → daemon-ITKDIYMW.js} +5 -5
- package/dist/cli/chunks/daemon-QBYTCIMH.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-HJXM7Q5P.js → dag-attention-scheduler-T55AXLD6.js} +2 -2
- package/dist/cli/chunks/{detect-XKQGLZYN.js → detect-DR7J6K4O.js} +2 -2
- package/dist/cli/chunks/{dist-node-SSKB53QL.js → dist-node-LAJJBOUT.js} +2 -2
- package/dist/cli/chunks/{domain-handler-6BNDHATU.js → domain-handler-OMSHCRMK.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-DOX54YE3.js → domain-plugins-EQXSKC5K.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-FW4ZX3Z7.js → domain-transfer-FKRAGVSW.js} +2 -2
- package/dist/cli/chunks/dream-3UABDRZJ.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-JZFPCNL3.js +3 -0
- package/dist/cli/chunks/{eval-K7E4XXBS.js → eval-JSNNASBW.js} +2 -2
- package/dist/cli/chunks/experience-capture-middleware-UPD3IZBK.js +40 -0
- package/dist/cli/chunks/{fast-paths-5JXXTYAG.js → fast-paths-YNMIBS2E.js} +2 -2
- package/dist/cli/chunks/{feature-flags-2CR3CO23.js → feature-flags-SRLXDKBI.js} +2 -2
- package/dist/cli/chunks/{feature-flags-RB72LHOJ.js → feature-flags-VIR7O4L7.js} +2 -2
- package/dist/cli/chunks/file-discovery-ZFGZTKZ4.js +2 -0
- package/dist/cli/chunks/{fleet-SDU7QEOA.js → fleet-K2ED46EL.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-AWCFODUV.js → gnn-wrapper-QCU4ZRYW.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-A4PJ3NFP.js → heartbeat-handler-YYQI4WZM.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-MJ6MTPDF.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-FQWJCFVW.js +2 -0
- package/dist/cli/chunks/hnsw-index-NJYKJUHC.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-KRS7SSFM.js → hnsw-legacy-bridge-C5TJSWTZ.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-OGGCPKPO.js → hnswlib-node-SE3MJJYS.js} +2 -2
- package/dist/cli/chunks/{hooks-XNRNMUBW.js → hooks-C572SRDH.js} +43 -43
- package/dist/cli/chunks/hybrid-backend-SL7RFID7.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-X35LTXYT.js → hypergraph-engine-35A6G3M5.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-M6THKAG6.js → hypergraph-handler-U2756CWI.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-5ZJTXPVC.js +2 -0
- package/dist/cli/chunks/init-handler-PCLYQUSB.js +88 -0
- package/dist/cli/chunks/init-wizard-MQMDSIOF.js +2 -0
- package/dist/cli/chunks/kernel-MEJ5GMRH.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-TEPR2ZJD.js → kilocode-installer-32PX5YH7.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-RUKHGDEE.js → kiro-installer-C4ROMMUS.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-XUBZSEZE.js +2 -0
- package/dist/cli/chunks/learning-GEPVZGJQ.js +122 -0
- package/dist/cli/chunks/{llm-router-7GECMDCP.js → llm-router-XRKTTJTX.js} +4 -4
- package/dist/cli/chunks/llm-router-service-QZAPAEPX.js +2 -0
- package/dist/cli/chunks/{load-NTJ4Y4ZR.js → load-XVH6HW7E.js} +2 -2
- package/dist/cli/chunks/load-test-OVXIQ3AF.js +2 -0
- package/dist/cli/chunks/{mcp-4335GTTG.js → mcp-IULSTM4Z.js} +2 -2
- package/dist/cli/chunks/{memory-HYC4M4XS.js → memory-6K7IAU4T.js} +5 -5
- package/dist/cli/chunks/memory-backend-TRPOMPK4.js +2 -0
- package/dist/cli/chunks/memory-handlers-CG6DRLAW.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-T7FYKM6T.js → multi-model-executor-VZDUYPLX.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-3USXVT5M.js → opencode-installer-QUTXKNH4.js} +2 -2
- package/dist/cli/chunks/orchestrator-PCKKUWOP.js +452 -0
- package/dist/cli/chunks/pattern-null-store-JWYBRBZG.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-CMZLPX2K.js → pattern-usage-recorder-PX5HQVRL.js} +2 -2
- package/dist/cli/chunks/{pipeline-BTRZOVSL.js → pipeline-O562GTOG.js} +2 -2
- package/dist/cli/chunks/{platform-2MCRKC25.js → platform-PM7Q2AZS.js} +2 -2
- package/dist/cli/chunks/plugin-OTYTFGPY.js +27 -0
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-TXFEMBP6.js → prime-radiant-advanced-wasm-6CFXTHC2.js} +2 -2
- package/dist/cli/chunks/project-root-VVSTHIP4.js +2 -0
- package/dist/cli/chunks/protocol-executor-PXZCLZD3.js +2 -0
- package/dist/cli/chunks/{protocol-handler-DZ26OYVZ.js → protocol-handler-PPGNSAOS.js} +2 -2
- package/dist/cli/chunks/{prove-QWONEJWX.js → prove-WQ3BKRZG.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-42FRS5V3.js +2 -0
- package/dist/cli/chunks/{quality-WFH54FY7.js → quality-C5WUU3AA.js} +2 -2
- package/dist/cli/chunks/{quality-gate-ONJB7XU7.js → quality-gate-WSSRKD5U.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-UI3B7DI6.js +2 -0
- package/dist/cli/chunks/real-embeddings-CFQE7IRQ.js +2 -0
- package/dist/cli/chunks/{ref-validation-HW5Y55ZC.js → ref-validation-DHKHXVZT.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-5OABDNZT.js → roocode-installer-3PPODABV.js} +2 -2
- package/dist/cli/chunks/router-HYRPWLAY.js +2 -0
- package/dist/cli/chunks/routing-feedback-BPZ5R6F3.js +2 -0
- package/dist/cli/chunks/{routing-handler-CVHVOQTC.js → routing-handler-JNXTGT6T.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-KKDKFGIQ.js → ruvector-commands-6YLROPVP.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-DEKDQ6KO.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-L53VBS7I.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-4DWB4WRK.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-I6RUGD2D.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-UGUXKIFX.js → rvf-store-integrity-YKR2ZNBF.js} +2 -2
- package/dist/cli/chunks/safe-db-KS65XDCP.js +2 -0
- package/dist/cli/chunks/schedule-KD2VN6GB.js +2 -0
- package/dist/cli/chunks/scheduler-ZH3RMUHY.js +2 -0
- package/dist/cli/chunks/{security-7723AZZ4.js → security-PWQTGDRU.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-LNRLFP5I.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-ZSHYG5IA.js → shared-rvf-dual-writer-GWU6YQNS.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-6DTVME5D.js +2 -0
- package/dist/cli/chunks/{standalone-memory-MHZEEYMK.js → standalone-memory-46KKBSSV.js} +2 -2
- package/dist/cli/chunks/{status-handler-JKXPJ22K.js → status-handler-35T5FTDQ.js} +2 -2
- package/dist/cli/chunks/{structural-health-J4RKCYWF.js → structural-health-P7QPQWLO.js} +2 -2
- package/dist/cli/chunks/{sync-PDPORHVN.js → sync-W6Z4R4PL.js} +2 -2
- package/dist/cli/chunks/sync-Y43EWBSY.js +2 -0
- package/dist/cli/chunks/{task-handler-VERADM44.js → task-handler-5CX3ZYT7.js} +2 -2
- package/dist/cli/chunks/{task-handlers-4RUCWUR2.js → task-handlers-DQZGOJNE.js} +3 -3
- package/dist/cli/chunks/{test-DMBJFQNL.js → test-TPP53VVV.js} +12 -12
- package/dist/cli/chunks/{test-scheduling-LUPTVGCD.js → test-scheduling-WBV4UMQH.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-GIIDXHLC.js +2 -0
- package/dist/cli/chunks/{token-usage-VOA34IKM.js → token-usage-AKK37RB7.js} +2 -2
- package/dist/cli/chunks/{transformers-GU4TYAN5.js → transformers-7MASPELS.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-MZPXAH7C.js → tree-sitter-wasm-parser-YZKD6UGB.js} +2 -2
- package/dist/cli/chunks/{types-K4FLXR2K.js → types-AZ3BTXDP.js} +2 -2
- package/dist/cli/chunks/unified-memory-FCX7NLFZ.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-VU5QJK37.js +2 -0
- package/dist/cli/chunks/unified-persistence-FM376LGE.js +2 -0
- package/dist/cli/chunks/{upgrade-M3ATDRMK.js → upgrade-L7OTDKEK.js} +2 -2
- package/dist/cli/chunks/{validate-AAP773B3.js → validate-O3QVFIGP.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-7RGAZX5F.js → validate-swarm-2UGBGLTX.js} +2 -2
- package/dist/cli/chunks/visual-security-EU7Y3X46.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-GQMRHGGI.js → web-tree-sitter-J75IYPRO.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-HG6HF2GF.js → windsurf-installer-FQ5DBFCG.js} +2 -2
- package/dist/cli/chunks/witness-chain-CSEBT52D.js +2 -0
- package/dist/cli/chunks/{witness-chain-WKU3ZIBQ.js → witness-chain-I7TN4MXZ.js} +2 -2
- package/dist/cli/chunks/witness-chain-repair-D3NE3NQK.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-Q2KW3QEQ.js → witness-chain-verifier-RU2WOP5M.js} +2 -2
- package/dist/cli/chunks/witness-key-manager-IHQB2FR5.js +2 -0
- package/dist/cli/chunks/{workflow-CX6SHFBW.js → workflow-6BWTNVV6.js} +28 -28
- package/dist/cli/chunks/workflow-orchestrator-ALNKOM3N.js +2 -0
- package/dist/cli/chunks/wrappers-URVP25VU.js +2 -0
- package/dist/cli/commands/ci.js +47 -25
- package/dist/cli/commands/coverage.d.ts +1 -28
- package/dist/cli/commands/coverage.js +63 -134
- package/dist/cli/commands/daemon.js +7 -1
- package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +15 -0
- package/dist/cli/commands/hooks-handlers/stats-hooks.js +54 -2
- package/dist/cli/commands/learning.js +47 -7
- package/dist/cli/commands/test.js +6 -7
- package/dist/cli/commands/workflow.js +9 -5
- package/dist/cli/handlers/init-guard.d.ts +13 -0
- package/dist/cli/handlers/init-guard.js +23 -0
- package/dist/cli/handlers/init-handler.d.ts +3 -0
- package/dist/cli/handlers/init-handler.js +9 -0
- package/dist/cli/handlers/interfaces.js +5 -1
- package/dist/cli/scheduler/persistent-scheduler.d.ts +6 -2
- package/dist/cli/scheduler/persistent-scheduler.js +107 -41
- package/dist/cli/utils/ci-output.d.ts +8 -1
- package/dist/cli/utils/ci-output.js +13 -2
- package/dist/cli/utils/coverage-data.d.ts +3 -0
- package/dist/cli/utils/coverage-data.js +14 -39
- package/dist/cli/utils/coverage-verdict.d.ts +130 -0
- package/dist/cli/utils/coverage-verdict.js +193 -0
- package/dist/cli/utils/file-discovery.js +5 -0
- package/dist/coordination/deterministic-actions.js +24 -13
- package/dist/coordination/handlers/code-intelligence-handlers.d.ts +8 -0
- package/dist/coordination/handlers/code-intelligence-handlers.js +39 -0
- package/dist/coordination/handlers/coverage-handlers.js +34 -6
- package/dist/coordination/handlers/coverage-runner.d.ts +22 -0
- package/dist/coordination/handlers/coverage-runner.js +105 -10
- package/dist/coordination/handlers/coverage-target.d.ts +1 -0
- package/dist/coordination/handlers/coverage-target.js +4 -1
- package/dist/coordination/handlers/handler-types.d.ts +9 -0
- package/dist/coordination/handlers/handler-utils.d.ts +14 -1
- package/dist/coordination/handlers/handler-utils.js +46 -22
- package/dist/coordination/handlers/quality-handlers.js +108 -18
- package/dist/coordination/handlers/test-execution-handlers.js +4 -1
- package/dist/coordination/protocols/defect-investigation.d.ts +2 -1
- package/dist/coordination/protocols/defect-investigation.js +6 -3
- package/dist/coordination/protocols/quality-gate.js +10 -6
- package/dist/coordination/result-saver.d.ts +22 -0
- package/dist/coordination/result-saver.js +113 -43
- package/dist/coordination/task-executor.d.ts +7 -0
- package/dist/coordination/task-executor.js +32 -3
- package/dist/domains/code-intelligence/plugin.js +4 -0
- package/dist/domains/code-intelligence/services/metric-collector/index.js +9 -2
- package/dist/domains/code-intelligence/services/metric-collector/interfaces.d.ts +21 -0
- package/dist/domains/code-intelligence/services/metric-collector/interfaces.js +25 -0
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.d.ts +12 -0
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +69 -3
- package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +4 -1
- package/dist/domains/coverage-analysis/collected-metrics.d.ts +33 -0
- package/dist/domains/coverage-analysis/collected-metrics.js +36 -0
- package/dist/domains/coverage-analysis/coordinator.js +18 -6
- package/dist/domains/coverage-analysis/interfaces.d.ts +44 -0
- package/dist/domains/coverage-analysis/interfaces.js +6 -1
- package/dist/domains/coverage-analysis/services/coverage-analyzer.js +61 -34
- package/dist/domains/coverage-analysis/services/gap-detector.js +7 -2
- package/dist/domains/defect-intelligence/plugin.js +4 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +6 -4
- package/dist/domains/learning-optimization/coordinator.js +4 -0
- package/dist/domains/learning-optimization/plugin.js +4 -0
- package/dist/domains/quality-assessment/coordinator-rl-integration.d.ts +14 -0
- package/dist/domains/quality-assessment/coordinator-rl-integration.js +54 -16
- package/dist/domains/quality-assessment/coordinator.js +10 -6
- package/dist/domains/quality-assessment/coverage-report-event.d.ts +32 -8
- package/dist/domains/quality-assessment/coverage-report-event.js +28 -6
- package/dist/domains/quality-assessment/index.d.ts +1 -1
- package/dist/domains/quality-assessment/interfaces.d.ts +46 -0
- package/dist/domains/quality-assessment/quality-evidence.d.ts +48 -2
- package/dist/domains/quality-assessment/quality-evidence.js +62 -0
- package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +23 -2
- package/dist/domains/quality-assessment/services/quality-analyzer.js +192 -109
- package/dist/domains/security-compliance/services/scanners/dast-scanner.js +22 -16
- package/dist/domains/test-execution/interfaces.d.ts +10 -6
- package/dist/domains/test-execution/plugin.js +4 -0
- package/dist/domains/test-execution/services/test-executor.js +152 -102
- package/dist/domains/test-generation/coordinator.js +4 -0
- package/dist/domains/test-generation/plugin.js +4 -0
- package/dist/feedback/coverage-learner.js +4 -1
- package/dist/feedback/coverage-session-provenance.d.ts +29 -0
- package/dist/feedback/coverage-session-provenance.js +39 -0
- package/dist/init/orchestrator.js +2 -0
- package/dist/init/phases/09-assets.d.ts +4 -0
- package/dist/init/phases/09-assets.js +35 -0
- package/dist/init/retired-assets.d.ts +86 -0
- package/dist/init/retired-assets.js +230 -0
- package/dist/init/skills-installer.d.ts +2 -0
- package/dist/init/skills-installer.js +4 -0
- package/dist/init/types.d.ts +3 -0
- package/dist/integrations/ruvector/rvf-native-adapter.d.ts +2 -0
- package/dist/integrations/ruvector/rvf-native-adapter.js +5 -0
- package/dist/integrations/ruvector/server-client.js +4 -12
- package/dist/kernel/project-root.d.ts +17 -0
- package/dist/kernel/project-root.js +54 -2
- package/dist/kernel/shared-dirs.d.ts +66 -0
- package/dist/kernel/shared-dirs.js +168 -0
- package/dist/learning/daily-log.js +2 -1
- package/dist/learning/experience-capture-middleware.d.ts +22 -0
- package/dist/learning/experience-capture-middleware.js +35 -0
- package/dist/learning/learnable-result.d.ts +16 -0
- package/dist/learning/learnable-result.js +24 -0
- package/dist/learning/pattern-mutation-error.d.ts +8 -0
- package/dist/learning/pattern-mutation-error.js +12 -0
- package/dist/learning/qe-reasoning-bank.d.ts +10 -0
- package/dist/learning/qe-reasoning-bank.js +50 -1
- package/dist/learning/rvf-reconcile.d.ts +39 -0
- package/dist/learning/rvf-reconcile.js +40 -0
- package/dist/learning/sqlite-persistence.d.ts +14 -0
- package/dist/learning/sqlite-persistence.js +36 -0
- package/dist/mcp/bundle.js +516 -504
- package/dist/mcp/handlers/domain-handler-configs.d.ts +31 -1
- package/dist/mcp/handlers/domain-handler-configs.js +37 -3
- package/dist/mcp/handlers/handler-factory.js +40 -14
- package/dist/mcp/protocol-server.js +27 -2
- package/dist/mcp/tool-cache-scope.d.ts +31 -0
- package/dist/mcp/tool-cache-scope.js +71 -0
- package/dist/mcp/tools/code-intelligence/analyze.js +5 -3
- package/dist/mcp/types.d.ts +4 -0
- package/dist/optimization/session-cache.d.ts +19 -1
- package/dist/optimization/session-cache.js +36 -2
- package/dist/plugins/cache.js +2 -1
- package/dist/plugins/sources/github.js +2 -1
- package/dist/plugins/sources/npm.js +2 -1
- package/dist/shared/aqe-managed-dirs.d.ts +24 -0
- package/dist/shared/aqe-managed-dirs.js +56 -0
- package/dist/shared/events/domain-events.d.ts +18 -3
- package/dist/shared/events/domain-events.js +4 -0
- package/dist/shared/http/http-client.d.ts +6 -0
- package/dist/shared/http/http-client.js +13 -15
- package/dist/shared/io/file-reader.d.ts +26 -0
- package/dist/shared/io/file-reader.js +111 -17
- package/dist/shared/llm/providers/response-deadline.d.ts +7 -2
- package/dist/shared/llm/providers/response-deadline.js +17 -5
- package/dist/shared/metrics/code-metrics.d.ts +24 -0
- package/dist/shared/metrics/code-metrics.js +93 -6
- package/dist/shared/metrics/index.d.ts +1 -1
- package/dist/workers/interfaces.d.ts +9 -1
- package/dist/workers/quality-daemon/coverage-delta.d.ts +4 -3
- package/dist/workers/quality-daemon/coverage-delta.js +13 -6
- package/dist/workers/quality-daemon/index.js +6 -5
- package/dist/workers/quality-daemon/notification-service.js +3 -3
- package/dist/workers/quality-daemon/persistent-memory.d.ts +2 -2
- package/dist/workers/quality-daemon/persistent-memory.js +2 -2
- package/dist/workers/worker-manager.js +5 -1
- package/dist/workers/workers/coverage-tracker.js +69 -33
- package/dist/workers/workers/regression-monitor.d.ts +18 -1
- package/dist/workers/workers/regression-monitor.js +276 -117
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-EGIPTX5H.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-WP4GCBDT.js +0 -2
- package/dist/cli/chunks/base-6ORFD62I.js +0 -2
- package/dist/cli/chunks/browser-workflow-PIXGERWP.js +0 -2
- package/dist/cli/chunks/chunk-2WFTZSRT.js +0 -2
- package/dist/cli/chunks/chunk-7YB2KELI.js +0 -5
- package/dist/cli/chunks/chunk-BBL6YXD3.js +0 -2
- package/dist/cli/chunks/chunk-BJ5P4IV2.js +0 -2
- package/dist/cli/chunks/chunk-DFPL5N3Q.js +0 -16
- package/dist/cli/chunks/chunk-DLY4YEN3.js +0 -2
- package/dist/cli/chunks/chunk-ERGWWI4Y.js +0 -3
- package/dist/cli/chunks/chunk-KZVJW2SD.js +0 -2
- package/dist/cli/chunks/chunk-L336HFFE.js +0 -2
- package/dist/cli/chunks/chunk-N2TJNIHA.js +0 -2
- package/dist/cli/chunks/chunk-RCXMUEZN.js +0 -3
- package/dist/cli/chunks/chunk-SEZLYRCS.js +0 -2
- package/dist/cli/chunks/chunk-TDLKXLJC.js +0 -4
- package/dist/cli/chunks/chunk-WOZIXXY5.js +0 -7
- package/dist/cli/chunks/ci-KP4GZKJ7.js +0 -81
- package/dist/cli/chunks/client-C3KHVRM6.js +0 -2
- package/dist/cli/chunks/core-handlers-KSQM6Q6S.js +0 -2
- package/dist/cli/chunks/coverage-SPFVHRRU.js +0 -43
- package/dist/cli/chunks/coverage-target-GSRBNHXE.js +0 -2
- package/dist/cli/chunks/cross-domain-router-CTGNOVCF.js +0 -2
- package/dist/cli/chunks/daemon-M5TD5Y6T.js +0 -10
- package/dist/cli/chunks/dream-MIK2E4UL.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-QST77T2B.js +0 -3
- package/dist/cli/chunks/experience-capture-middleware-X66IYSRV.js +0 -40
- package/dist/cli/chunks/file-discovery-3NHRUQQB.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-OCKRACUW.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-X67XG73C.js +0 -2
- package/dist/cli/chunks/hnsw-index-I7KCQBQR.js +0 -2
- package/dist/cli/chunks/hybrid-backend-FOUHTKAK.js +0 -2
- package/dist/cli/chunks/impact-analyzer-GXYVX46O.js +0 -2
- package/dist/cli/chunks/init-handler-2AXMXHYF.js +0 -86
- package/dist/cli/chunks/init-wizard-C2MRX2QG.js +0 -2
- package/dist/cli/chunks/kernel-Q2IUDIDC.js +0 -2
- package/dist/cli/chunks/knowledge-graph-E2Z6K5EE.js +0 -2
- package/dist/cli/chunks/learning-BEA26RNA.js +0 -122
- package/dist/cli/chunks/llm-router-service-YATYFEDD.js +0 -2
- package/dist/cli/chunks/load-test-LV77JXWA.js +0 -2
- package/dist/cli/chunks/memory-backend-XME3X3QX.js +0 -2
- package/dist/cli/chunks/memory-handlers-VG47X5DX.js +0 -2
- package/dist/cli/chunks/orchestrator-VHUXUYIM.js +0 -452
- package/dist/cli/chunks/pattern-null-store-TAXMLENP.js +0 -2
- package/dist/cli/chunks/plugin-2VAYWAO3.js +0 -27
- package/dist/cli/chunks/project-root-CFFPBGPX.js +0 -2
- package/dist/cli/chunks/protocol-executor-ML76QAVQ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-LUZH6RYV.js +0 -2
- package/dist/cli/chunks/queen-coordinator-EWXNIXB6.js +0 -2
- package/dist/cli/chunks/real-embeddings-GZV4VKK4.js +0 -2
- package/dist/cli/chunks/router-MXOBVEBF.js +0 -2
- package/dist/cli/chunks/routing-feedback-T6CCRUEK.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-WHXVT3V3.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-JFPWIRCG.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-D4KUBNRZ.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-KOXR7TJL.js +0 -2
- package/dist/cli/chunks/safe-db-CI6IPSIN.js +0 -2
- package/dist/cli/chunks/schedule-X4HW6TVJ.js +0 -2
- package/dist/cli/chunks/scheduler-KCNJ2ON3.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-KEQ5CLNI.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-PGHU6VUR.js +0 -2
- package/dist/cli/chunks/sync-EFWXMA2H.js +0 -2
- package/dist/cli/chunks/token-bootstrap-S346YBVO.js +0 -2
- package/dist/cli/chunks/unified-memory-6CK3TUNQ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-A7BWBGYN.js +0 -2
- package/dist/cli/chunks/unified-persistence-GEPMDBQZ.js +0 -2
- package/dist/cli/chunks/visual-security-L4J7LQWT.js +0 -2
- package/dist/cli/chunks/witness-chain-CDUMX623.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-WNYH6O4L.js +0 -2
- package/dist/cli/chunks/witness-key-manager-NQ5DAAC4.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-USJDWVDR.js +0 -2
- package/dist/cli/chunks/wrappers-CZDI6Z3X.js +0 -2
- /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
- /package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
- /package/.claude/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
- /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.test.ts → budget-tests.ts.fixture} +0 -0
- /package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/{budget.ts → budget.ts.fixture} +0 -0
- /package/assets/skills/testability-scoring/resources/templates/{testability-scoring.spec.template.js → testability-scoring-spec.template.js} +0 -0
|
@@ -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-RMJ7PJOS.js";import{S as ie,i as D,p as $}from"./chunk-VRJPH3LG.js";import{b as g,d as ne,f as W}from"./chunk-HLFDC4SF.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.6");process.exit(0)}
|
|
2
|
+
import{a as ae,b as oe}from"./chunk-F7A2UBZO.js";import{S as ie,i as D,p as $}from"./chunk-A7ANPS4E.js";import{b as g,d as ne,f as W}from"./chunk-7SAMMQVS.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,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 j,d as z}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.6");process.exit(0)}
|
|
2
|
+
import{b as j,d as z}from"./chunk-5MT7DMD7.js";import{a as F,e as ce}from"./chunk-KYVIOC3C.js";import{c as k,d as pe}from"./chunk-TVLOED6O.js";z();ce();z();import*as N from"node:http";import*as M from"node:https";import{createHash as me}from"node:crypto";import{URL as Q}from"node:url";var x={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ue="AQE embedder endpoint identity canary v1",fe="/v1/embeddings";function X(t){if(t.startsWith("unix:"))return t;try{let e=new Q(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function ge(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new Q(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},_=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??x.model,expectedDim:e.expectedDim??x.expectedDim,connectTimeoutMs:e.connectTimeoutMs??x.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??x.requestTimeoutMs,failureThreshold:e.failureThreshold??x.failureThreshold,failureWindowMs:e.failureWindowMs??x.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ge(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new M.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new N.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([ue]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=me("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return j(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(fe,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=N.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?M.request:N.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,R=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);R(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as J,resolve as he}from"node:path";import{existsSync as Ee,mkdirSync as be}from"node:fs";import{createRequire as ye}from"node:module";var we=ye(import.meta.url);function Ie(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:he(k(),t):J(k(),".agentic-qe","memory.db")}var K="_system",Y="embedder_identity:",T=null,U=!1;function Z(){if(T)return T;if(U)return null;try{let t=we("better-sqlite3"),e=Ie(),n=J(e,"..");Ee(n)||be(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS kv_store (
|
|
4
4
|
key TEXT NOT NULL,
|
|
5
5
|
namespace TEXT NOT NULL,
|
|
@@ -10,4 +10,4 @@ import{b as j,d as z}from"./chunk-Y2E3IJ53.js";import{a as F,e as ce}from"./chun
|
|
|
10
10
|
);
|
|
11
11
|
CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
|
|
12
12
|
`),T=r,r}catch{return U=!0,null}}function ee(t){let e=Z();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(K,Y+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function te(t){let e=Z();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Y+t.endpoint,K,JSON.stringify(n))}function ne(){if(T)try{T.close()}catch{}T=null,U=!1}z();import{createHash as ie}from"node:crypto";import{existsSync as Ae,readFileSync as xe,renameSync as Te,writeFileSync as Se}from"node:fs";var oe="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ne(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function se(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return ie("sha256").update(e).digest("hex").slice(0,16)}function V(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=ie("sha256").update("aqe:embedding-space:v1\0").update(Ne(t)).digest("hex");return{...t,spaceId:e}}function Le(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}var Ce="[VectorSearch] WARN: semantic vector search is not active: no embedding runtime was available when the ANN indexes were opened (set AQE_EMBEDDER_ENDPOINT, or install @huggingface/transformers). Any existing vectors in patterns.rvf and brain.rvf are kept and will be used once an embedder is available; until then pattern search uses SQLite text matching.",He="VECTOR_SPACE_UNVERIFIED: no embedding runtime was available when the RVF index was opened; index left unbound (existing vectors are kept)",re=!1;function We(){re||(re=!0,console.warn(Ce))}function Re(t){return`${t}.space.json`}function Ge(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=Re(t);if(Ae(r)){let s;try{s=JSON.parse(xe(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;Se(i,`${JSON.stringify(a)}
|
|
13
|
-
`,{encoding:"utf8",mode:384}),Te(i,r)}var B=null,f=null,C=null,P=!1,D="",v=null,c=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,ae=36e5;function L(t){return c?`endpoint:${c.fingerprint}:${t}`:`inproc:${t}`}function de(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${D}`);if(C)return C;let e={...H,...t};return C=(async()=>{try{if(e.endpoint){let l=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new _({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:O()}),c=await v.probe(),A=V({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:c.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:c.endpoint,runtimeFingerprint:c.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let m=ee(c.endpoint);m&&m.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),te(c)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=_e(v);return}let n;try{n=await import("./transformers-
|
|
13
|
+
`,{encoding:"utf8",mode:384}),Te(i,r)}var B=null,f=null,C=null,P=!1,D="",v=null,c=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,ae=36e5;function L(t){return c?`endpoint:${c.fingerprint}:${t}`:`inproc:${t}`}function de(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${D}`);if(C)return C;let e={...H,...t};return C=(async()=>{try{if(e.endpoint){let l=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new _({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:O()}),c=await v.probe(),A=V({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:c.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:c.endpoint,runtimeFingerprint:c.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let m=ee(c.endpoint);m&&m.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),te(c)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=_e(v);return}let n;try{n=await import("./transformers-7MASPELS.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. 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.')}B=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await B("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(oe,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=V({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:se(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw P=!0,D=F(n),new Error(`Failed to initialize transformer model: ${D}`)}})(),C}function _e(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??O(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Ye(t,e={}){let n={...H,...e};if(de(t))return new Array(O()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=p.get(r);if(l&&Date.now()-l.timestamp<ae)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(p.size>=n.maxCacheSize){let l=p.keys().next().value;l&&p.delete(l)}p.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Ze(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)de(t[o])?i[o]=new Array(O()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=p.get(L(t[o]));l&&Date.now()-l.timestamp<ae?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),R=await f(y,{pooling:"mean",normalize:!0}),h=R.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(R.data.slice(u,u+d)),S=b+g,le=a[S];if(i[le]=E,n.enableCache){if(p.size>=n.maxCacheSize){let G=p.keys().next().value;G&&p.delete(G)}p.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function et(){p.clear(),console.log("[RealEmbeddings] Cache cleared")}function tt(){return{size:p.size,hitRate:0}}function nt(){return!P&&f!==null}function O(){return 384}function rt(){B=null,f=null,C=null,P=!1,D="",p.clear(),v&&v.close(),v=null,c=null,A=null,ne()}function it(){return v!==null}function ot(){return c}function st(){return A}async function at(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{oe as a,Le as b,He as c,We as d,Ge as e,H as f,Ye as g,Ze as h,et as i,tt as j,nt as k,O as l,rt as m,it as n,ot as o,st as p,at as q};
|
|
@@ -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{o as C,s 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.6");process.exit(0)}
|
|
2
|
+
import{o as C,s as M}from"./chunk-YNG7E26C.js";import{i as b}from"./chunk-IVJIHZSM.js";M();import{createRequire as H}from"node:module";var w=H(import.meta.url),_=null;function T(){if(_)return _;let E=w("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function U(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=U(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=w("../../../kernel/hnsw-adapter.js"),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=T(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=T(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var O={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...O,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=C();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
|
|
3
3
|
SELECT id, task, domain, quality, success, application_count,
|
|
4
4
|
consolidation_count, reuse_success_count, reuse_failure_count,
|
|
5
5
|
embedding, embedding_dimension, started_at
|
|
@@ -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{c as G,d 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.6");process.exit(0)}
|
|
2
|
+
import{c as G,d as H}from"./chunk-ORBODZSO.js";import{h as U}from"./chunk-TL5GV3PR.js";import{e as N}from"./chunk-GNYOHZVV.js";import{e as W}from"./chunk-SOSJWM3E.js";import{e as T}from"./chunk-BUTGIVKW.js";import{b as v,c as x}from"./chunk-HOEWMEF2.js";import{b,d as q}from"./chunk-22OZIJAD.js";import{i as _}from"./chunk-IVJIHZSM.js";import{c as k,d as E}from"./chunk-QLKUCMZC.js";import{a as se}from"./chunk-45MVRQG4.js";import{e as z}from"./chunk-IEPWO4XP.js";import{a as y,e as $}from"./chunk-KYVIOC3C.js";import{S as ae,b as O}from"./chunk-A7ANPS4E.js";import{randomUUID as ee}from"crypto";$();q();import{randomUUID as oe}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${oe()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let s=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),n!==void 0&&s.push("--quality",String(n)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-FCX7NLFZ.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
|
|
3
3
|
INSERT OR REPLACE INTO qe_trajectories
|
|
4
4
|
(id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -9,4 +9,4 @@ Steps:
|
|
|
9
9
|
${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
|
|
10
10
|
`)}
|
|
11
11
|
|
|
12
|
-
Duration: ${e.durationMs}ms`;return{patternType:t,qeDomain:e.domain,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:[...this.extractTags(e),this.experienceIdentity(e)],experienceOrigin:{task:e.task,domain:e.domain??null,patternType:t},testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}experienceIdentity(e){return ce("sha256").update(JSON.stringify([e.task,e.domain??null,this.detectPatternType(e.task)])).digest("hex")}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t} ${this.experienceIdentity(e)}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){F.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(u,e,t,i){return new Q(u,e,t,i)}var pe={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...pe,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await G(H),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=U(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-ZSHYG5IA.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-WKU3ZIBQ.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-WKU3ZIBQ.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-GEPMDBQZ.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-GEPMDBQZ.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-TAXMLENP.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-2CR3CO23.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-FW4ZX3Z7.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=r.byDomain?.[a]??0,o=r.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:r.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=X({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=N(i.value,t.value);return k(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return k([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),k([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${ee().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${ee().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(c){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(c))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let c=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});c.success&&c.value.length>0&&(s=c.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:s}));let d={id:o||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(d.id,d),d.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let m of d.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&c.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&c.add("javascript"),m.endsWith(".py")&&c.add("python"),m.endsWith(".go")&&c.add("go"),m.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let m=b(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},ge={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},te=class{config;constructor(e){this.config={...ge,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),s=h(i.map(l=>l.tokenMetrics.costUsd)),o=h(n.map(l=>l.tokenMetrics.costUsd)),d=h(i.map(l=>l.tokenMetrics.savingsUsd)),c=h(n.map(l=>l.tokenMetrics.savingsUsd));if(o>s*1.1&&c<=d*1.05){let l=Math.min(1,(o-s)/(s||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(l),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(l=>l.qualityMetrics.gatePassRate)),w=h(n.map(l=>l.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(l=>l.learningMetrics.patternCount)),f=h(n.map(l=>l.learningMetrics.patternCount)),ie=h(i.map(l=>l.learningMetrics.averageConfidence)),I=h(n.map(l=>l.learningMetrics.averageConfidence)),ne=Math.abs(f-p),re=Math.abs(I-ie);ne<1&&re<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${I.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(l=>l.performanceMetrics.p95LatencyMs)),j=h(n.map(l=>l.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let l=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(l),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(u){return u.length===0?0:u.reduce((e,t)=>e+t,0)/u.length}function A(u){return Math.max(0,Math.min(1,u))}function me(u,e,t){return new L(u,e,t)}function rt(u,e,t){return me(u,{projectRoot:e},t)}export{pe as a,L as b,ge as c,te as d,me as e,rt as f};
|
|
12
|
+
Duration: ${e.durationMs}ms`;return{patternType:t,qeDomain:e.domain,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:[...this.extractTags(e),this.experienceIdentity(e)],experienceOrigin:{task:e.task,domain:e.domain??null,patternType:t},testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}experienceIdentity(e){return ce("sha256").update(JSON.stringify([e.task,e.domain??null,this.detectPatternType(e.task)])).digest("hex")}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t} ${this.experienceIdentity(e)}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){F.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(u,e,t,i){return new Q(u,e,t,i)}var pe={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...pe,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await G(H),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=U(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-GWU6YQNS.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-I7TN4MXZ.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-I7TN4MXZ.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-FM376LGE.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-FM376LGE.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-JWYBRBZG.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-SRLXDKBI.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-FKRAGVSW.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=r.byDomain?.[a]??0,o=r.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:r.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=X({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=N(i.value,t.value);return k(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return k([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),k([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${ee().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${ee().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(c){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(c))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let c=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});c.success&&c.value.length>0&&(s=c.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:s}));let d={id:o||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(d.id,d),d.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let m of d.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&c.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&c.add("javascript"),m.endsWith(".py")&&c.add("python"),m.endsWith(".go")&&c.add("go"),m.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let m=b(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},ge={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},te=class{config;constructor(e){this.config={...ge,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),s=h(i.map(l=>l.tokenMetrics.costUsd)),o=h(n.map(l=>l.tokenMetrics.costUsd)),d=h(i.map(l=>l.tokenMetrics.savingsUsd)),c=h(n.map(l=>l.tokenMetrics.savingsUsd));if(o>s*1.1&&c<=d*1.05){let l=Math.min(1,(o-s)/(s||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(l),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(l=>l.qualityMetrics.gatePassRate)),w=h(n.map(l=>l.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(l=>l.learningMetrics.patternCount)),f=h(n.map(l=>l.learningMetrics.patternCount)),ie=h(i.map(l=>l.learningMetrics.averageConfidence)),I=h(n.map(l=>l.learningMetrics.averageConfidence)),ne=Math.abs(f-p),re=Math.abs(I-ie);ne<1&&re<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${I.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(l=>l.performanceMetrics.p95LatencyMs)),j=h(n.map(l=>l.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let l=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(l),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(u){return u.length===0?0:u.reduce((e,t)=>e+t,0)/u.length}function A(u){return Math.max(0,Math.min(1,u))}function me(u,e,t){return new L(u,e,t)}function rt(u,e,t){return me(u,{projectRoot:e},t)}export{pe as a,L as b,ge as c,te as d,me as e,rt as f};
|
|
@@ -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.6");process.exit(0)}
|
|
2
|
+
import{a as h}from"./chunk-45MVRQG4.js";import{e as m}from"./chunk-IEPWO4XP.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};
|
|
@@ -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.6");process.exit(0)}
|
|
2
|
+
var r=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=100,t=n=>n===null||r(n);function s(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!r(e.line)||!t(e.statement)||!t(e.branch)||!t(e.function))return null;let u=typeof e.files=="number"&&Number.isInteger(e.files)&&e.files>=0?e.files:null;return u===null?null:{line:e.line,branch:e.branch,function:e.function,statement:e.statement,files:u,measured:!0,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{}}}function i(n){if(!n||typeof n!="object")return null;let e=n;if(e.measured!==!0||!r(e.line))return null;let u=l=>r(l)?l:null;return{line:e.line,branch:u(e.branch),function:u(e.function),statement:u(e.statement),measured:!0}}export{s as a,i as b};
|
|
@@ -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{d as W,f as Tt}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.6");process.exit(0)}
|
|
2
|
+
import{d as W,f as Tt}from"./chunk-X2DR27AY.js";import{b as I,d as ge}from"./chunk-22OZIJAD.js";import{a as K,b as $,c as V,d as Ne,e as dt}from"./chunk-DQNUPEY5.js";import{a as Y,c as Et}from"./chunk-LZWJ5BMP.js";import{a as _e,d as F,e as me,f as fe}from"./chunk-RUTO67PT.js";import{a as X,b as pe,e as ct}from"./chunk-5LST62QR.js";import{a as Se,c as he,d as ut}from"./chunk-HEGGV2PT.js";import{a as it}from"./chunk-45MVRQG4.js";import{e as ue}from"./chunk-IEPWO4XP.js";import{a as O,e as de}from"./chunk-KYVIOC3C.js";import{a as H,c as y,d as ot}from"./chunk-TVLOED6O.js";import{a as le,b as at}from"./chunk-AJT3XDRD.js";import{b as R,d as st}from"./chunk-7SAMMQVS.js";import{createHash as Ie}from"node:crypto";function gt(n){let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(n)),t}function pt(n){return typeof n=="string"?Buffer.from(n,"utf8"):n instanceof Uint8Array?Buffer.from(n):Buffer.from(Q(n),"utf8")}function Q(n){return n===null||typeof n!="object"?JSON.stringify(n)??"null":Array.isArray(n)?`[${n.map(Q).join(",")}]`:`{${Object.keys(n).sort().map(e=>`${JSON.stringify(e)}:${Q(n[e])}`).join(",")}}`}function Ce(...n){let t=Ie("sha256");for(let e of n)t.update(e);return t.digest()}function Le(n,t,e){return Ce(lt,n,t,gt(e))}var lt,Re,A,Oe=R(()=>{"use strict";lt=Buffer.from("ruvector:chain:"),Re=Ie("sha256").update("ruvector-proof-gate-v1").digest();A=class n{seq=0;prev=Re;chain=[];payloadHashes=[];admit(t){let e=Ce(pt(t)),r=Le(this.prev,e,this.seq);this.prev=r,this.chain.push(r),this.payloadHashes.push(e);let o={sequence:this.seq,payloadHash:e.toString("hex"),chainCommitment:r.toString("hex")};return this.seq+=1,o}verifyReceipt(t){return t.sequence>=0&&t.sequence<this.chain.length&&this.chain[t.sequence].toString("hex")===t.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let t=Re;for(let e=0;e<this.chain.length;e++){if(!Le(t,this.payloadHashes[e],e).equals(this.chain[e]))return!1;t=this.chain[e]}return t.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(t=>t.toString("hex")),payloadHashes:this.payloadHashes.map(t=>t.toString("hex"))}}static fromJSON(t){let e=new n;e.seq=t.seq,e.prev=Buffer.from(t.head,"hex");for(let r of t.chain)e.chain.push(Buffer.from(r,"hex"));for(let r of t.payloadHashes)e.payloadHashes.push(Buffer.from(r,"hex"));return e}}});function v(n){if(!J.has(n))throw new Error(`Invalid table name: "${n}" is not in the allowlist`);return n}function bt(n){let t=n.split(".");if(t.length>2)throw new Error(`Invalid SQL identifier: "${n}" has too many parts (max: schema.table)`);for(let e of t)if(!Ae.test(e))throw new Error(`Invalid SQL identifier: "${n}" \u2014 part "${e}" does not match pattern ${Ae}`);return n}var J,Ae,Z=R(()=>{"use strict";J=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);Ae=/^[a-z_][a-z0-9_]{0,62}$/});function be(n){n.exec(ve),n.exec(`
|
|
3
3
|
INSERT OR IGNORE INTO learning_evidence_manifests (
|
|
4
4
|
id, trajectory_id, trajectory_hash, manifest_hash, task_family,
|
|
5
5
|
outcome, oracle_refs_json, source_kind, process_signals_json
|
|
@@ -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.6");process.exit(0)}
|
|
2
2
|
var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n 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{d 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.6");process.exit(0)}
|
|
2
|
+
import{d as m}from"./chunk-K55EAWZ5.js";import{d as T}from"./chunk-5MT7DMD7.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s 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 E,d as S}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.6");process.exit(0)}
|
|
2
|
+
import{b as E,d as S}from"./chunk-22OZIJAD.js";import{a as D,b as Q}from"./chunk-F7A2UBZO.js";import{S as M,l as A}from"./chunk-A7ANPS4E.js";import{f as C}from"./chunk-7SAMMQVS.js";S();M();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(Q(),C(D));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=E(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(A()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
|
|
@@ -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.6");process.exit(0)}
|
|
2
2
|
var a=class extends Error{constructor(r){super(r),this.name="TestRunnerExecutionError"}};function N(e,r,t,n,s,i){let c=(i?.testResults??[]).filter(u=>u.status==="failed"&&(e==="vitest"&&u.message||!u.assertionResults?.some(f=>f.status==="failed"))),o;if(t===null?o="terminated without an exit code":n.passed+n.failed+n.skipped===0?o="reported zero tests":c.length>0||(i?.numRuntimeErrorTestSuites??0)>0||(i?.numFailedTestSuites??0)>0&&n.failed===0?o="reported a suite execution error":(t!==0||i?.success===!1)&&n.failed===0&&(o="failed without a failed assertion"),!o)return;let l=[...c.map(u=>u.message).filter(Boolean),s.trim()].filter(Boolean).join(`
|
|
3
3
|
`).slice(0,4e3);return new a(`${e} ${o} for ${r} (exit code ${t??"unknown"}).`+(l?`
|
|
4
4
|
${l}`:""))}import{mkdtempSync as g,readFileSync as R,rmSync as y}from"node:fs";import{tmpdir as h}from"node:os";import{join as d}from"node:path";function x(e,r){if(!r)return;let t;try{t=R(r,"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(t);if(!n||!Array.isArray(n.testResults))throw new Error("Invalid report")}catch{throw new Error("The current Vitest JSON report is malformed.")}return t}function k(){let e=g(d(h(),"aqe-vitest-report-")),r=d(e,"report.json"),t=!1;return{path:r,args:[`--outputFile=${r}`],read:n=>x(n,r),cleanup:()=>{if(!t){t=!0;try{y(e,{recursive:!0,force:!0})}catch{}}}}}function z(e){let r=e.some(s=>/(^|[\\/])vitest(\.cmd|\.js|\.mjs)?$/i.test(s)),t=e.some((s,i)=>s==="--reporter=json"||s==="--reporter"&&e[i+1]==="json"),n=e.some(s=>s.startsWith("--outputFile"));return r&&t&&!n}import{realpathSync as E,statSync as $}from"node:fs";import{basename as j,dirname as S,extname as b,resolve as p,sep as w}from"node:path";function m(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function F(e,r=process.cwd()){let t=p(r,e);try{return p(E(S(t)),j(t))}catch{return t}}function J(e){try{return $(e).isDirectory()}catch{return b(e)===""}}function P(e,r=process.cwd()){let t=F(e,r),n=t.split(w).join("/"),s=J(t)?"(?:/|$)":"$";return`^${m(n)}${s}`}function q(e,r){let t=m(r);return e==="mocha"?`--grep=${t}`:`--testNamePattern=${t}`}function I(e){return e.some(r=>/(^|[\\/])jest(\.cmd|\.js|\.mjs)?$/i.test(r))}export{a,N as b,k as c,z as d,F as e,P as f,q as g,I as h};
|
|
@@ -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{d as g,e as S,p as E,q as _}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.6");process.exit(0)}
|
|
2
|
+
import{d as g,e as S,p as E,q as _}from"./chunk-XFPQIWEH.js";function R(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??E()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-I6RUGD2D.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}if(this.activeSpaceId()||await _(),!this.activeSpaceId()){this.rvfAvailable=!1,g();return}let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-YKR2ZNBF.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=R(n,this.config.dimensions),S(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
|
|
3
3
|
SELECT COUNT(*) AS incompatible
|
|
4
4
|
FROM qe_pattern_embeddings
|
|
5
5
|
WHERE space_id IS NULL OR space_id <> ?
|
|
@@ -0,0 +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.6");process.exit(0)}
|
|
2
|
+
import{a as W}from"./chunk-YLNYPQDR.js";import{a as A}from"./chunk-HZFK2Z2Z.js";import{b as q,d as H}from"./chunk-TVLOED6O.js";var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as oe,freemem as re,totalmem as ne,loadavg as se}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as z}from"fs";import{execFile as E}from"child_process";import{promisify as L}from"util";import{resolve as N,join as U}from"path";import{existsSync as j,readFileSync as B}from"fs";var _=L(E),J={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...J,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=N(this.options.repoRoot,".git","refs","heads");if(!j(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=z(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
|
|
3
|
+
`)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=N(this.options.repoRoot,".git","refs","heads"),o=U(i,e),r;try{r=B(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){if(A(t,"commit hash"))return;let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
|
|
4
|
+
`).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
|
|
5
|
+
`)){if(!t)continue;let[i,o]=t.split(" ");this.lastKnownHeads.set(i,o)}}catch{}}};function M(u,e){return u===null||e===null?0:u-e}var K={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...K,...t}}queue;options;async analyze(e,t,i){let o=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!o)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let r=o,n={line:e.overall.line-r.overall.line,branch:M(e.overall.branch,r.overall.branch??null),function:M(e.overall.function,r.overall.function??null),statement:M(e.overall.statement,r.overall.statement??null)},s=n.line<-this.options.regressionThreshold||(n.branch??0)<-this.options.regressionThreshold,a=i??Object.keys(e.files),c=[],d=[];for(let h of a){let l=e.files[h],m=r.files[h];if(!l)continue;let I=m?l.line-m.line:0,R=m?l.branch-m.branch:0,D=m?l.uncoveredLines.filter(T=>!m.uncoveredLines.includes(T)):l.uncoveredLines;if((I!==0||R!==0||D.length>0)&&c.push({file:h,lineDelta:I,branchDelta:R,newUncoveredLines:D}),l.line<this.options.gapThreshold){let T=this.computeRiskScore(l,D.length);d.push({file:h,uncoveredLines:l.uncoveredLines,currentCoverage:l.line,riskScore:T})}}return(s||d.length>0)&&this.enqueueTestSuggestion(e,r,d),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:c.length,gapCount:d.length}),{regressionDetected:s,overallDelta:n,affectedFiles:c,newGaps:d}}async buildSnapshot(e){let t=await e.get("coverage:latest"),i=W(t);if(i)return{timestamp:Date.now(),overall:{line:i.line,branch:i.branch,function:i.function,statement:i.statement},files:t&&typeof t.files=="object"?t.files:{}}}computeRiskScore(e,t){let o=1-Math.min(100,Math.max(0,e.line))/100,r=Math.min(t/50,1);return Math.min(1,o*.6+r*.4)}enqueueTestSuggestion(e,t,i){let o={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},r={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:o,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(r)}};import{execFile as V}from"child_process";import{promisify as Y}from"util";var X=Y(V),Z={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...Z,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],o=[],r=0;for(let[s,a]of Object.entries(t)){let c=a.filter(m=>m.conclusion==="failure").length,d=a.length>0?(a.length-c)/a.length*100:100,h=this.countConsecutiveFailures(a),l=a[0]?.conclusion??"unknown";l==="failure"&&r++,h>=this.options.flakyThreshold&&(o.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:c,successRate:Math.round(d*10)/10,lastConclusion:l,consecutiveFailures:h})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:r,flakyWorkflows:o,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await X("gh",e,{timeout:15e3});return JSON.parse(t).map(o=>({name:o.name,status:o.status,conclusion:o.conclusion??"pending",headBranch:o.headBranch,runNumber:o.number,databaseId:o.databaseId,createdAt:o.createdAt}))}catch{return[]}}groupByWorkflow(e){let t={};for(let i of e)t[i.name]||(t[i.name]=[]),t[i.name].push(i);for(let i of Object.keys(t))t[i]=t[i].slice(0,this.options.runsPerWorkflow);return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,o)=>i+o.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},o={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(o)}};var ee={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...ee,...e}}async suggest(e,t,i){let o=[],r=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of r){let a=t.includes(s.file),c=this.determinePriority(s,a),d=this.determineTestType(s.file),h=this.estimateEffort(s);o.push({id:`suggestion-${Date.now()}-${o.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:d,description:this.generateDescription(s,d),priority:c,estimatedEffort:h,createdAt:Date.now(),status:"pending"})}o.sort((s,a)=>{let c={high:0,medium:1,low:2};return c[s.priority]-c[a.priority]});let n=o.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let o=await i.get(`${this.options.memoryPrefix}:list`);if(!o)return!1;let r=o.findIndex(s=>s.id===e);if(r===-1)return!1;let n=o.map((s,a)=>a===r?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,o=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${o}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let r=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,r),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:r.length,lastUpdated:Date.now()})}};var te={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),o=new Date().toISOString().split("T")[0],r=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(o,t);await e.set(`${this.options.memoryPrefix}:report:${o}`,s),this.lastRunDate=o;let a={timestamp:Date.now(),patternsConsolidated:r,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,o=Date.now();for(let r of t){if(r.endsWith(":snapshot")||r.endsWith(":list"))continue;let n=await e.get(r);n&&typeof n.timestamp=="number"&&o-n.timestamp>this.options.maxEntryAge&&(await e.set(r,{pruned:!0,prunedAt:o}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};H();import{writeFileSync as F,mkdirSync as O,readdirSync as S,readFileSync as G,unlinkSync as Q}from"fs";import{join as b}from"path";var ie={maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??q("notifications"),this.maxNotifications=e?.maxNotifications??ie.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){O(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=S(this.notificationsDir).filter(r=>r.endsWith(".json")).sort().reverse(),o=[];for(let r of i){if(o.length>=t)break;try{let n=G(b(this.notificationsDir,r),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;o.push(s)}catch{}}return o}catch{return[]}}markRead(e){try{let t=S(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),r={...JSON.parse(G(i,"utf-8")),read:!0};return F(i,JSON.stringify(r,null,2)),!0}catch{return!1}}clear(){try{let e=S(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)Q(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{O(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);F(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=S(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)Q(b(this.notificationsDir,i))}catch{}}};var C={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},$=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??C.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??C.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??C.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??C.cpuThreshold,memoryThreshold:e?.memoryThreshold??C.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let o=this.queue.dequeue();if(!o)break;await this.handleQueueItem(o,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let o=await this.coverageDelta.buildSnapshot(t);if(o){let r=await this.coverageDelta.analyze(o,t,i.changedFiles);if(r.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${r.overallDelta.line.toFixed(1)}% (${r.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:r.overallDelta,commit:i.commitHash}}),r.newGaps.length>0){let n=await this.testSuggester.suggest(r.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let o=await this.testSuggester.getPending(t);o.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${o.length} test suggestions awaiting review`,severity:"info",metadata:{count:o.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let o={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,o);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);if(i){let o=[i.overall.line,i.overall.branch,i.overall.function,i.overall.statement].filter(r=>typeof r=="number");this._coverageHealth=Math.round(o.reduce((r,n)=>r+n,0)/o.length),this._lastCoverageCheck=t}}catch{}}isResourceConstrained(){if(1-re()/ne()>this.config.memoryThreshold)return!0;let t=oe().length;return(t>0?se()[0]/t:0)>this.config.cpuThreshold}};export{x as a,$ as b};
|