agentic-qe 3.15.7 → 3.15.9
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/skills-manifest.json +1 -1
- package/CHANGELOG.md +305 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/agents/claim-verifier/claim-verifier-service.js +13 -8
- package/dist/bridge/captured-experience-bridge.js +12 -13
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-R2Q4QGXQ.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-OS5G7KMQ.js → agent-booster-wasm-427FRKWG.js} +2 -2
- package/dist/cli/chunks/{agent-handler-PI4I7PME.js → agent-handler-RIYHTHVZ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-J7TXHX4U.js → agent-memory-branch-WSUCUHOO.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-3RENLQWP.js +2 -0
- package/dist/cli/chunks/{arena-OWUGXKNT.js → arena-KRIBMIXX.js} +2 -2
- package/dist/cli/chunks/{arena-FXESDCFR.js → arena-YAJZX6MC.js} +4 -4
- package/dist/cli/chunks/{audit-EPAWLYIZ.js → audit-7ZNOXWP3.js} +3 -3
- package/dist/cli/chunks/base-67DXSAYM.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-IYVR5EQY.js → better-sqlite3-ZQAT4I6H.js} +2 -2
- package/dist/cli/chunks/{brain-handler-3W2E6TC6.js → brain-handler-452WCPZC.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HU7VACJ4.js → branch-enumerator-IJFXJRPN.js} +2 -2
- package/dist/cli/chunks/{browser-72XOR6E2.js → browser-CT3MTV6G.js} +2 -2
- package/dist/cli/chunks/browser-workflow-NDXRROWZ.js +2 -0
- package/dist/cli/chunks/{chunk-WXI2STKQ.js → chunk-2BA45H64.js} +2 -2
- package/dist/cli/chunks/{chunk-DGK6GQMO.js → chunk-2HL3UM5P.js} +2 -2
- package/dist/cli/chunks/{chunk-LGBN7TKC.js → chunk-2I2UPJS7.js} +2 -2
- package/dist/cli/chunks/{chunk-ZRLNACPY.js → chunk-2TDIS6YK.js} +2 -2
- package/dist/cli/chunks/{chunk-34JLY3U6.js → chunk-2URBI52G.js} +2 -2
- package/dist/cli/chunks/{chunk-K7W55B7Q.js → chunk-2XITOPYV.js} +2 -2
- package/dist/cli/chunks/{chunk-I7H4IP7T.js → chunk-2YH62JCN.js} +2 -2
- package/dist/cli/chunks/{chunk-HPG7354V.js → chunk-32UTLDNY.js} +2 -2
- package/dist/cli/chunks/{chunk-C2CUPJGR.js → chunk-37BIGMJI.js} +1 -1
- package/dist/cli/chunks/{chunk-2RJYA6WK.js → chunk-3CJCROMW.js} +2 -2
- package/dist/cli/chunks/{chunk-CWPRU7ZI.js → chunk-3LYU7BLY.js} +2 -2
- package/dist/cli/chunks/{chunk-24CENUT4.js → chunk-47TYABPD.js} +3 -3
- package/dist/cli/chunks/{chunk-WUV5RZUI.js → chunk-47V7FQGX.js} +2 -2
- package/dist/cli/chunks/{chunk-IWQQIXHO.js → chunk-4JCY45KV.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTMZFF25.js → chunk-4SUOVLJ6.js} +2 -2
- package/dist/cli/chunks/{chunk-CIFWOMNX.js → chunk-4URT6JO2.js} +1 -1
- package/dist/cli/chunks/{chunk-5Q22XPTH.js → chunk-4V27J6YN.js} +2 -2
- package/dist/cli/chunks/{chunk-SX2YSHE7.js → chunk-4W4DYVSH.js} +1 -1
- package/dist/cli/chunks/chunk-55HRSNGN.js +2 -0
- package/dist/cli/chunks/{chunk-F62EKVVC.js → chunk-5D2I7JUP.js} +2 -2
- package/dist/cli/chunks/{chunk-XXAVQACL.js → chunk-5JWGCIQW.js} +1 -1
- package/dist/cli/chunks/chunk-5LAAZLUC.js +4 -0
- package/dist/cli/chunks/{chunk-EDU72RTW.js → chunk-5NS3USRW.js} +1 -1
- package/dist/cli/chunks/{chunk-BTYKGVJ5.js → chunk-6EPHNJTL.js} +1 -1
- package/dist/cli/chunks/{chunk-JVYPXW6Y.js → chunk-6OOYIO3W.js} +2 -2
- package/dist/cli/chunks/{chunk-PG64YV6C.js → chunk-6PXA2BQJ.js} +58 -58
- package/dist/cli/chunks/{chunk-IARSGAG7.js → chunk-6YL6JOQB.js} +2 -2
- package/dist/cli/chunks/{chunk-LDXQRNTT.js → chunk-72AMFDC7.js} +1 -1
- package/dist/cli/chunks/{chunk-Z3VJLWRR.js → chunk-763SUL4B.js} +2 -2
- package/dist/cli/chunks/{chunk-EL75G2A3.js → chunk-7DMA5NYL.js} +1 -1
- package/dist/cli/chunks/{chunk-J43DV3ME.js → chunk-7JKB3Q7O.js} +1 -1
- package/dist/cli/chunks/{chunk-ONVALAZN.js → chunk-7KII4CQG.js} +2 -2
- package/dist/cli/chunks/{chunk-AAA4SHEG.js → chunk-7QGYJ5OY.js} +1 -1
- package/dist/cli/chunks/{chunk-MMXG3LL6.js → chunk-7QTB5VJZ.js} +2 -2
- package/dist/cli/chunks/{chunk-BB7OLQKO.js → chunk-7X2Y727E.js} +1 -1
- package/dist/cli/chunks/{chunk-VNW5Q2CX.js → chunk-A4RU67VX.js} +2 -2
- package/dist/cli/chunks/{chunk-YFOBQSOW.js → chunk-A6YIH4C4.js} +2 -2
- package/dist/cli/chunks/{chunk-MJJC6HUK.js → chunk-ABFDB4X3.js} +1 -1
- package/dist/cli/chunks/{chunk-MHZPC4HJ.js → chunk-AJ4YDSOI.js} +2 -2
- package/dist/cli/chunks/{chunk-OA4GR3EZ.js → chunk-AOFO4N32.js} +2 -2
- package/dist/cli/chunks/{chunk-EB2PP6X2.js → chunk-AQTVVLNP.js} +1 -1
- package/dist/cli/chunks/chunk-AR2E4B7K.js +6 -0
- package/dist/cli/chunks/{chunk-N4PMPSJJ.js → chunk-AVB5QY2Q.js} +2 -2
- package/dist/cli/chunks/{chunk-HLZATDD2.js → chunk-BHKXMIWX.js} +2 -2
- package/dist/cli/chunks/{chunk-C2MDBBFF.js → chunk-BXO536GT.js} +3 -3
- package/dist/cli/chunks/{chunk-WTLIEBDH.js → chunk-C6RTMTEH.js} +1 -1
- package/dist/cli/chunks/{chunk-MNZFEIE5.js → chunk-CTZJUV5I.js} +1 -1
- package/dist/cli/chunks/{chunk-XEWXYGJI.js → chunk-D6XVGFTI.js} +2 -2
- package/dist/cli/chunks/{chunk-Y4SAWE45.js → chunk-DDPPSSHW.js} +1 -1
- package/dist/cli/chunks/{chunk-KPOPBUUJ.js → chunk-DGTLJNJH.js} +2 -2
- package/dist/cli/chunks/{chunk-6JT73S5B.js → chunk-DINZR5CF.js} +1 -1
- package/dist/cli/chunks/{chunk-HTWIGQL4.js → chunk-EFBLP43U.js} +2 -2
- package/dist/cli/chunks/chunk-ETG7O5E5.js +5 -0
- package/dist/cli/chunks/{chunk-2AYBYXOA.js → chunk-F2SQPP6U.js} +2 -2
- package/dist/cli/chunks/{chunk-V2SAEMZY.js → chunk-F3PQZX44.js} +1 -1
- package/dist/cli/chunks/{chunk-JPHDMHFG.js → chunk-F4JYIRW2.js} +2 -2
- package/dist/cli/chunks/{chunk-REEIFA6A.js → chunk-FJ4VTLLK.js} +2 -2
- package/dist/cli/chunks/{chunk-PTK66HEY.js → chunk-FL3OYGCS.js} +2 -2
- package/dist/cli/chunks/{chunk-PEKDSJBC.js → chunk-FLASM2XB.js} +2 -2
- package/dist/cli/chunks/{chunk-G762PEFO.js → chunk-FV3NHVC7.js} +22 -22
- package/dist/cli/chunks/{chunk-FTTFJ7SJ.js → chunk-FV7VAG74.js} +1 -1
- package/dist/cli/chunks/{chunk-2YVJ5OUL.js → chunk-G3BKZNFL.js} +8 -8
- package/dist/cli/chunks/{chunk-MDC4G323.js → chunk-GBUIG3FS.js} +1 -1
- package/dist/cli/chunks/{chunk-DCJW2DPL.js → chunk-GCWSX2NY.js} +4 -4
- package/dist/cli/chunks/{chunk-VCA6YYII.js → chunk-GII5WVAK.js} +1 -1
- package/dist/cli/chunks/{chunk-HXBAQKMH.js → chunk-GKPQ2GRR.js} +2 -2
- package/dist/cli/chunks/chunk-GR3JYE5A.js +2 -0
- package/dist/cli/chunks/{chunk-ZUMDDMDE.js → chunk-H3KBIWTO.js} +2 -2
- package/dist/cli/chunks/{chunk-ECSLJJOQ.js → chunk-HAROIAJE.js} +1 -1
- package/dist/cli/chunks/{chunk-ICPALF4Q.js → chunk-HCYQHWI2.js} +2 -2
- package/dist/cli/chunks/{chunk-V5NGBQAQ.js → chunk-HGTWAZWU.js} +2 -2
- package/dist/cli/chunks/{chunk-YK3NOC2R.js → chunk-HTZJSQ3C.js} +2 -2
- package/dist/cli/chunks/{chunk-IYQ7XNE5.js → chunk-HWK5L7IJ.js} +2 -2
- package/dist/cli/chunks/{chunk-HSDOOFV7.js → chunk-HZ5NC6U5.js} +1 -1
- package/dist/cli/chunks/{chunk-M63QB466.js → chunk-I6S35FRO.js} +2 -2
- package/dist/cli/chunks/{chunk-LMEU64TR.js → chunk-ICP2ORGI.js} +2 -2
- package/dist/cli/chunks/{chunk-PXZKPUW6.js → chunk-IFEIY3NQ.js} +2 -2
- package/dist/cli/chunks/{chunk-OJEZNLB6.js → chunk-J3DTDJDT.js} +2 -2
- package/dist/cli/chunks/chunk-J3WGK22W.js +2 -0
- package/dist/cli/chunks/{chunk-SQHLC6I5.js → chunk-J5KNRVXR.js} +1 -1
- package/dist/cli/chunks/{chunk-RORZ5O5Z.js → chunk-JAV5WPSY.js} +2 -2
- package/dist/cli/chunks/{chunk-SSP2B2WR.js → chunk-JEP4ULR6.js} +2 -2
- package/dist/cli/chunks/{chunk-6FEQ73BF.js → chunk-JK2ME6IT.js} +2 -2
- package/dist/cli/chunks/chunk-JNNZK7KH.js +2 -0
- package/dist/cli/chunks/{chunk-RXAFLK34.js → chunk-JP4P3P3D.js} +2 -2
- package/dist/cli/chunks/{chunk-JY4AIEZ7.js → chunk-JUVHZG7I.js} +1 -1
- package/dist/cli/chunks/{chunk-UBYCR3O4.js → chunk-JWGRWMZP.js} +2 -2
- package/dist/cli/chunks/{chunk-6BO3WCK7.js → chunk-K5DJXMAA.js} +2 -2
- package/dist/cli/chunks/{chunk-MKFQNCXI.js → chunk-KFUUIAR4.js} +2 -2
- package/dist/cli/chunks/chunk-KHSRIPBP.js +180 -0
- package/dist/cli/chunks/{chunk-UY3REQOK.js → chunk-KIKWJM6J.js} +2 -2
- package/dist/cli/chunks/{chunk-YUC7RJGR.js → chunk-KIXYKUCI.js} +1 -1
- package/dist/cli/chunks/{chunk-IC2WSSD5.js → chunk-KLGYIEJK.js} +3 -3
- package/dist/cli/chunks/{chunk-DVPGBDBP.js → chunk-KR3M44CF.js} +3 -3
- package/dist/cli/chunks/chunk-KTSLTZSG.js +2 -0
- package/dist/cli/chunks/{chunk-Y6A46M3B.js → chunk-KVBEGOJE.js} +2 -2
- package/dist/cli/chunks/{chunk-PZG3542B.js → chunk-L42JPFCC.js} +2 -2
- package/dist/cli/chunks/{chunk-J26GADQE.js → chunk-LCJTEUDC.js} +181 -181
- package/dist/cli/chunks/{chunk-3JD2USUH.js → chunk-LEAKYZ37.js} +2 -2
- package/dist/cli/chunks/{chunk-UCLN6AME.js → chunk-LMU5DUDK.js} +1 -1
- package/dist/cli/chunks/{chunk-EV2BYY6T.js → chunk-MZS32SYS.js} +1 -1
- package/dist/cli/chunks/{chunk-LVEX4GID.js → chunk-N3KEY4XJ.js} +2 -2
- package/dist/cli/chunks/{chunk-XNSQZ3O7.js → chunk-N3NP6PTT.js} +2 -2
- package/dist/cli/chunks/{chunk-QVG4ZDXX.js → chunk-N5PDFGCQ.js} +2 -2
- package/dist/cli/chunks/{chunk-6PKCQXEW.js → chunk-NDKLQW6N.js} +2 -2
- package/dist/cli/chunks/{chunk-6AYRAOCA.js → chunk-NHZIWIQZ.js} +2 -2
- package/dist/cli/chunks/{chunk-H4WHDFB5.js → chunk-NTAD5UX4.js} +2 -2
- package/dist/cli/chunks/{chunk-JYXOFN3E.js → chunk-O3JLOVZX.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLVQSEZK.js → chunk-OCESWNAZ.js} +3 -3
- package/dist/cli/chunks/{chunk-7EX4DEQR.js → chunk-OG2UI6A3.js} +2 -2
- package/dist/cli/chunks/{chunk-3RM46XFP.js → chunk-OXTFSIGN.js} +1 -1
- package/dist/cli/chunks/{chunk-44DPYNPE.js → chunk-OXZLKP6C.js} +1 -1
- package/dist/cli/chunks/{chunk-TU4LIIOP.js → chunk-P2CXVNKK.js} +2 -2
- package/dist/cli/chunks/{chunk-LDZWIV2O.js → chunk-P73W2K7T.js} +1 -1
- package/dist/cli/chunks/{chunk-56ZKQYZY.js → chunk-PBZI2ZPV.js} +3 -3
- package/dist/cli/chunks/{chunk-MNCF643K.js → chunk-PMCRCEW5.js} +2 -2
- package/dist/cli/chunks/{chunk-4G2VNW4C.js → chunk-PVIA2FPD.js} +2 -2
- package/dist/cli/chunks/{chunk-MRHM4COP.js → chunk-PX2B5TS2.js} +2 -2
- package/dist/cli/chunks/{chunk-HZFT3P5B.js → chunk-Q3JVJRVJ.js} +1 -1
- package/dist/cli/chunks/{chunk-GY2SAIXP.js → chunk-QQ5SZH4D.js} +2 -2
- package/dist/cli/chunks/{chunk-LP4AS2E4.js → chunk-QTVWUQTB.js} +1 -1
- package/dist/cli/chunks/{chunk-W4X2VTIY.js → chunk-REUFWGMA.js} +2 -2
- package/dist/cli/chunks/{chunk-FVBFASOD.js → chunk-SNBYYO6F.js} +2 -2
- package/dist/cli/chunks/{chunk-RNYX4CPI.js → chunk-SVHUYVUR.js} +2 -2
- package/dist/cli/chunks/{chunk-AXO7OOOA.js → chunk-THAY7WHO.js} +2 -2
- package/dist/cli/chunks/{chunk-QWLTHFZW.js → chunk-TNMQVG4A.js} +2 -2
- package/dist/cli/chunks/{chunk-JFPXCQNP.js → chunk-TSYQDRNK.js} +1 -1
- package/dist/cli/chunks/{chunk-JK6B3ULP.js → chunk-TUYJ53V4.js} +2 -2
- package/dist/cli/chunks/{chunk-PUECC4WI.js → chunk-UNUTC6TX.js} +2 -2
- package/dist/cli/chunks/{chunk-ED32XJ5R.js → chunk-UOJBR4J3.js} +2 -2
- package/dist/cli/chunks/{chunk-CXTJ47QS.js → chunk-UOWHE77F.js} +2 -2
- package/dist/cli/chunks/{chunk-5KCBX225.js → chunk-UYLYMWV5.js} +2 -2
- package/dist/cli/chunks/{chunk-QNQSM2OG.js → chunk-V5PXQSFS.js} +2 -2
- package/dist/cli/chunks/{chunk-VKPKYMCT.js → chunk-VCMINU7K.js} +2 -2
- package/dist/cli/chunks/{chunk-QQT6QENQ.js → chunk-VQHVHVSF.js} +2 -2
- package/dist/cli/chunks/{chunk-634D2ENF.js → chunk-VRGCKBF7.js} +2 -2
- package/dist/cli/chunks/{chunk-T6W5APYP.js → chunk-VU2EL424.js} +1 -1
- package/dist/cli/chunks/{chunk-JY4WLN3K.js → chunk-VXZJOKOX.js} +2 -2
- package/dist/cli/chunks/{chunk-NZQPP533.js → chunk-VYLM2YV5.js} +3 -3
- package/dist/cli/chunks/{chunk-PQV7E7XH.js → chunk-W32YU3VI.js} +2 -2
- package/dist/cli/chunks/{chunk-RRPYWBFX.js → chunk-W5VJRDDG.js} +2 -2
- package/dist/cli/chunks/{chunk-7UCVYYWL.js → chunk-WGDR2KIR.js} +2 -2
- package/dist/cli/chunks/{chunk-2423JAA5.js → chunk-WRRCQ2UE.js} +1 -1
- package/dist/cli/chunks/{chunk-RCYLCA7E.js → chunk-XDBD4GXO.js} +2 -2
- package/dist/cli/chunks/{chunk-PYHYOKYT.js → chunk-XOLDMK23.js} +2 -2
- package/dist/cli/chunks/{chunk-5KS7HA37.js → chunk-XOVNZT7F.js} +1 -1
- package/dist/cli/chunks/{chunk-5PBRBS7D.js → chunk-XQ3DDY7X.js} +2 -2
- package/dist/cli/chunks/{chunk-4DIZ5BT6.js → chunk-XUIA5KMS.js} +2 -2
- package/dist/cli/chunks/{chunk-G7YTZTGU.js → chunk-XWIUFYM3.js} +1 -1
- package/dist/cli/chunks/{chunk-B7M323VL.js → chunk-XYCKHYBM.js} +2 -2
- package/dist/cli/chunks/{chunk-6OS7HREG.js → chunk-XZJ2O3VC.js} +1 -1
- package/dist/cli/chunks/{chunk-BTIBXGVQ.js → chunk-YRBBBUJX.js} +5 -5
- package/dist/cli/chunks/{chunk-MQ6OF6DU.js → chunk-YZGSJG34.js} +1 -1
- package/dist/cli/chunks/{chunk-XTJMY3KS.js → chunk-YZYDTABJ.js} +1 -1
- package/dist/cli/chunks/{chunk-LQOVA4YX.js → chunk-ZANDSVCK.js} +2 -2
- package/dist/cli/chunks/{chunk-2E3XWKEU.js → chunk-ZBDRLF43.js} +2 -2
- package/dist/cli/chunks/{chunk-UUHIEM2M.js → chunk-ZVSLCEVC.js} +3 -3
- package/dist/cli/chunks/{chunk-Q2T5FXEA.js → chunk-ZXBCCO2H.js} +2 -2
- package/dist/cli/chunks/{ci-5HEXJZ2C.js → ci-7SGRCFPS.js} +2 -2
- package/dist/cli/chunks/{ci-config-WU4NPDAM.js → ci-config-MX3URPZA.js} +2 -2
- package/dist/cli/chunks/{ci-output-BJQVXX5E.js → ci-output-M47NJY6D.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-3BMGTQCB.js → circuit-breaker-5GAK45SW.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-GVDGJWMU.js → claude-flow-setup-YXYSRH4Y.js} +2 -2
- package/dist/cli/chunks/client-ZP3CTVRF.js +2 -0
- package/dist/cli/chunks/{cline-installer-V4MRGWVA.js → cline-installer-DLJ5QD5N.js} +2 -2
- package/dist/cli/chunks/{code-A3TGQPEO.js → code-ONKLMVQ2.js} +25 -24
- package/dist/cli/chunks/{code-index-extractor-YJQSYWD3.js → code-index-extractor-2232LGZN.js} +2 -2
- package/dist/cli/chunks/{codex-installer-7N7UQPAH.js → codex-installer-UOWLYCMH.js} +2 -2
- package/dist/cli/chunks/{completions-PPGVYLZS.js → completions-MHX7GCC7.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-XZTFLYV5.js → complexity-analyzer-43ZUJKZU.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-Z5I57RAH.js → continuedev-installer-6Q5JR4FF.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-F5YZ6BHB.js → copilot-installer-CZUMVHSI.js} +2 -2
- package/dist/cli/chunks/core-handlers-JSRXQWPE.js +2 -0
- package/dist/cli/chunks/{cost-tracker-GO33ZQAP.js → cost-tracker-VS5ZW3XN.js} +2 -2
- package/dist/cli/chunks/{coverage-GSHKLY74.js → coverage-VWKTWZ6D.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-7UKODQWG.js +2 -0
- package/dist/cli/chunks/{cursor-installer-JJ7IVJZB.js → cursor-installer-YIFEMORH.js} +2 -2
- package/dist/cli/chunks/{daemon-IRL7QRNE.js → daemon-SHWJSJW5.js} +7 -7
- package/dist/cli/chunks/daemon-YIFT46FH.js +34 -0
- package/dist/cli/chunks/{dag-attention-scheduler-ORXSUHPA.js → dag-attention-scheduler-TCC2WM46.js} +2 -2
- package/dist/cli/chunks/{detect-RHU62KRI.js → detect-IGTWSQMA.js} +2 -2
- package/dist/cli/chunks/{dist-node-3VKV4Z6C.js → dist-node-TCOTJVQX.js} +2 -2
- package/dist/cli/chunks/{domain-handler-SFIML4FK.js → domain-handler-55ZVYODR.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-CJ4FA3OC.js → domain-plugins-GJRWOHQP.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-BCRKPCAA.js → domain-transfer-6EF75EKU.js} +2 -2
- package/dist/cli/chunks/dream-UDLM6M55.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-VL3HFLPV.js → embed-and-insert-pattern-XAMNIKQL.js} +2 -2
- package/dist/cli/chunks/{eval-GGKRI4P5.js → eval-GO22R4OZ.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-F72TIRQY.js → experience-capture-middleware-F2BRMJ3Y.js} +3 -3
- package/dist/cli/chunks/{fast-paths-7KOOF3MA.js → fast-paths-6RGPYALD.js} +2 -2
- package/dist/cli/chunks/{feature-flags-FNHBTHBH.js → feature-flags-MIWQIOHU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-IOZEWWFU.js → feature-flags-ZGS3KLPH.js} +2 -2
- package/dist/cli/chunks/file-discovery-THWOUQ7Z.js +2 -0
- package/dist/cli/chunks/fleet-ADL57COA.js +44 -0
- package/dist/cli/chunks/{gnn-wrapper-OH2DOQP7.js → gnn-wrapper-ALBJVW6T.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-W67NXTNE.js → heartbeat-handler-ZMM53NDY.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-HGOC5KH3.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-EPSA6AP7.js +2 -0
- package/dist/cli/chunks/hnsw-index-RMFOPYGY.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-6MLLOGOE.js → hnsw-legacy-bridge-RYUJPA7B.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-4UDISJ3G.js → hnswlib-node-XM6XF3YV.js} +2 -2
- package/dist/cli/chunks/{hooks-NOQJWQ4P.js → hooks-X62O7TJO.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-NZ3G4WBX.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-2OD3APVP.js → hypergraph-engine-ZBWUPTVD.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-5AZGMBUM.js → hypergraph-handler-DUMF6SJV.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-WZC6NHFP.js +2 -0
- package/dist/cli/chunks/{init-guard-SMGJ45PW.js → init-guard-S4I2R46S.js} +2 -2
- package/dist/cli/chunks/{init-handler-5T4MP2NM.js → init-handler-L4KJHVWS.js} +6 -6
- package/dist/cli/chunks/init-wizard-422UZYQ5.js +2 -0
- package/dist/cli/chunks/kernel-N7PJ6FCE.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-RLZYLVQJ.js → kilocode-installer-GNNB5FCZ.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-LFZOC7VD.js → kiro-installer-HR6ZAH7T.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-SZCVQF37.js +2 -0
- package/dist/cli/chunks/{learning-XRPGLUWR.js → learning-4IEEOHJS.js} +3 -3
- package/dist/cli/chunks/{llm-router-OMK5HYPH.js → llm-router-ZFMORP36.js} +4 -4
- package/dist/cli/chunks/llm-router-service-4DE5WDUZ.js +2 -0
- package/dist/cli/chunks/{load-XADC7KCU.js → load-ZM43WGDO.js} +2 -2
- package/dist/cli/chunks/load-test-POMIF4Q4.js +2 -0
- package/dist/cli/chunks/{mcp-PIBKSSVU.js → mcp-CRZKZE37.js} +2 -2
- package/dist/cli/chunks/{memory-AP7EZERS.js → memory-W5FZGVAD.js} +5 -5
- package/dist/cli/chunks/memory-backend-4P6AHSOY.js +2 -0
- package/dist/cli/chunks/memory-handlers-NK6NV3GE.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-7JJ2FZ33.js → multi-model-executor-SXXGAQ2G.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-ZZZ6EBYJ.js → opencode-installer-PIRBUAB5.js} +2 -2
- package/dist/cli/chunks/{orchestrator-2H2YKSGJ.js → orchestrator-H5SQCQTB.js} +11 -10
- package/dist/cli/chunks/pattern-null-store-CCHQHGQG.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-7MJJWC2Z.js → pattern-usage-recorder-XZTWDI2T.js} +2 -2
- package/dist/cli/chunks/{pipeline-LIE5BWQY.js → pipeline-5LMLBIJ7.js} +2 -2
- package/dist/cli/chunks/{platform-SMYUNLGX.js → platform-KJDABL5C.js} +2 -2
- package/dist/cli/chunks/{plugin-LJDIXQNT.js → plugin-V4KSBVVM.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-RIDNE5D2.js → prime-radiant-advanced-wasm-JDHTKQAT.js} +2 -2
- package/dist/cli/chunks/project-root-X72FSM2F.js +2 -0
- package/dist/cli/chunks/protocol-executor-QW6XN6QN.js +2 -0
- package/dist/cli/chunks/{protocol-handler-YVM66DLI.js → protocol-handler-BNRONTQV.js} +2 -2
- package/dist/cli/chunks/{prove-ZBDT52GD.js → prove-ELLL6XMX.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-ZD3WF647.js +2 -0
- package/dist/cli/chunks/{quality-DUKXGDDO.js → quality-NH2QA4D4.js} +2 -2
- package/dist/cli/chunks/{quality-gate-SM3RXF4V.js → quality-gate-JTKLF7GW.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-S4U4MKK2.js +2 -0
- package/dist/cli/chunks/{real-embeddings-4QLQZDB5.js → real-embeddings-J3KCKLPB.js} +2 -2
- package/dist/cli/chunks/{ref-validation-M3EO32YQ.js → ref-validation-HNXQRP4F.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-S6Q5OLV5.js → roocode-installer-COJ6CX6S.js} +2 -2
- package/dist/cli/chunks/router-CXZKOOTR.js +2 -0
- package/dist/cli/chunks/routing-feedback-IYFANYY5.js +2 -0
- package/dist/cli/chunks/{routing-handler-55FMUACP.js → routing-handler-WM33ZILE.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-QATKAAPK.js → ruvector-commands-BBLXEA7A.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-HCLQ5WUQ.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-XCLUWOO3.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-RFXFU6JD.js → rvf-migration-coordinator-P7H6HCAG.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-MRT5H3IP.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-PKDVXQAW.js → rvf-store-integrity-R5SPVRFP.js} +2 -2
- package/dist/cli/chunks/safe-db-WFODRGVZ.js +2 -0
- package/dist/cli/chunks/schedule-RO55OQXG.js +2 -0
- package/dist/cli/chunks/scheduler-XXMJCH24.js +2 -0
- package/dist/cli/chunks/{security-CMRB6WA3.js → security-AUDTRX3I.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-YHLLNFHF.js → shared-rvf-adapter-PVDGBGI2.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-4BGDVPQ7.js → shared-rvf-dual-writer-LZ2GMSS2.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-AWRIS4MK.js +2 -0
- package/dist/cli/chunks/{standalone-memory-LUHKQAGM.js → standalone-memory-XNOAI4G4.js} +2 -2
- package/dist/cli/chunks/{status-handler-S6S5PNR7.js → status-handler-K72XZE4T.js} +2 -2
- package/dist/cli/chunks/{structural-health-PQ7NZAJ4.js → structural-health-NF3YY7U5.js} +2 -2
- package/dist/cli/chunks/{sync-S744AEJC.js → sync-UVXA6CT2.js} +2 -2
- package/dist/cli/chunks/{sync-Q6KRQXU6.js → sync-VBD5Y3E2.js} +2 -2
- package/dist/cli/chunks/{task-handler-GAMGEHUW.js → task-handler-24S3WFVJ.js} +13 -7
- package/dist/cli/chunks/task-handlers-GUYW2EPJ.js +9 -0
- package/dist/cli/chunks/{test-FNH67DBK.js → test-XFSGQELD.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-NZA5SHK6.js → test-scheduling-VYUQ4CDE.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-CXKG55JD.js → token-bootstrap-EDK6FNQ3.js} +2 -2
- package/dist/cli/chunks/{token-usage-M7WWEDJX.js → token-usage-VLQ6WO2L.js} +2 -2
- package/dist/cli/chunks/{transformers-2IFMCK6A.js → transformers-TOFMWWNM.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-NMNA6RJC.js → tree-sitter-wasm-parser-MI3NZKUD.js} +2 -2
- package/dist/cli/chunks/{types-N7FWTOLD.js → types-JTWLBAZJ.js} +2 -2
- package/dist/cli/chunks/unified-memory-6JWHV6EF.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-4UANU6NU.js +2 -0
- package/dist/cli/chunks/unified-persistence-KGGNA46H.js +2 -0
- package/dist/cli/chunks/{upgrade-KDB5RGL7.js → upgrade-4ABM72T4.js} +2 -2
- package/dist/cli/chunks/{validate-KMUV5FUA.js → validate-UDJCWKXI.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-ANZWRCJU.js → validate-swarm-TODOUWNN.js} +2 -2
- package/dist/cli/chunks/visual-security-6VZNQLH7.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-SXXC4NMS.js → web-tree-sitter-WBMAJPM5.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-2LWSKMBU.js → windsurf-installer-BTT53TUL.js} +2 -2
- package/dist/cli/chunks/witness-chain-AKKHWEWU.js +2 -0
- package/dist/cli/chunks/{witness-chain-JJMSJFZP.js → witness-chain-TATPXQRK.js} +2 -2
- package/dist/cli/chunks/{witness-chain-repair-OX7VFW6T.js → witness-chain-repair-2HGJGE7O.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-QLSMXHAZ.js → witness-chain-verifier-FRY3LMGH.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-3DS4L7LE.js → witness-key-manager-X7QHQQWL.js} +2 -2
- package/dist/cli/chunks/{workflow-ARWAMHD3.js → workflow-QMZPAWQW.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-4GAW7HNZ.js +2 -0
- package/dist/cli/chunks/{wrappers-J6KGTUSJ.js → wrappers-ZD5NBHYI.js} +2 -2
- package/dist/cli/commands/code.js +8 -0
- package/dist/cli/commands/daemon.js +8 -0
- package/dist/cli/commands/fleet.js +14 -9
- package/dist/cli/handlers/task-handler.js +21 -1
- package/dist/coordination/handlers/code-intelligence-handlers.js +14 -2
- package/dist/coordination/handlers/coverage-collection.js +9 -10
- package/dist/coordination/handlers/coverage-handlers.js +21 -3
- package/dist/coordination/handlers/coverage-runner.d.ts +2 -1
- package/dist/coordination/handlers/coverage-runner.js +9 -2
- package/dist/coordination/handlers/coverage-target.d.ts +13 -3
- package/dist/coordination/handlers/coverage-target.js +224 -7
- package/dist/coordination/handlers/handler-types.d.ts +2 -0
- package/dist/coordination/handlers/test-execution-handlers.js +32 -5
- package/dist/coordination/index.d.ts +2 -2
- package/dist/coordination/index.js +1 -1
- package/dist/coordination/protocols/learning-consolidation-archive.d.ts +39 -0
- package/dist/coordination/protocols/learning-consolidation-archive.js +57 -0
- package/dist/coordination/protocols/learning-consolidation.d.ts +38 -3
- package/dist/coordination/protocols/learning-consolidation.js +130 -58
- package/dist/coordination/queen-coordinator.d.ts +12 -1
- package/dist/coordination/queen-coordinator.js +24 -1
- package/dist/coordination/queen-event-handlers.js +2 -1
- package/dist/coordination/queen-lifecycle.js +9 -0
- package/dist/coordination/queen-task-management.js +113 -40
- package/dist/coordination/queen-types.d.ts +10 -0
- package/dist/coordination/queen-types.js +8 -0
- package/dist/coordination/task-dag/dag-algorithms.d.ts +33 -0
- package/dist/coordination/task-dag/dag-algorithms.js +162 -0
- package/dist/coordination/task-dag/dag-obligations.d.ts +21 -0
- package/dist/coordination/task-dag/dag-obligations.js +83 -0
- package/dist/coordination/task-dag/dag.d.ts +69 -19
- package/dist/coordination/task-dag/dag.js +215 -269
- package/dist/coordination/task-dag/index.d.ts +12 -4
- package/dist/coordination/task-dag/index.js +11 -3
- package/dist/coordination/task-dag/prerequisite-ledger.d.ts +84 -0
- package/dist/coordination/task-dag/prerequisite-ledger.js +252 -0
- package/dist/coordination/task-dag/scheduler.d.ts +19 -9
- package/dist/coordination/task-dag/scheduler.js +36 -12
- package/dist/coordination/task-dag/types.d.ts +160 -1
- package/dist/coordination/task-dag/types.js +2 -1
- package/dist/coordination/task-executability.d.ts +18 -0
- package/dist/coordination/task-executability.js +31 -0
- package/dist/coordination/task-executor.d.ts +1 -0
- package/dist/coordination/task-executor.js +5 -0
- package/dist/domains/code-intelligence/coordinator.js +35 -9
- package/dist/domains/code-intelligence/index-path-guard.d.ts +49 -0
- package/dist/domains/code-intelligence/index-path-guard.js +125 -0
- package/dist/domains/code-intelligence/interfaces.d.ts +12 -0
- package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +6 -0
- package/dist/domains/code-intelligence/services/knowledge-graph.js +42 -5
- package/dist/domains/contract-testing/coordinator.js +3 -1
- package/dist/domains/coverage-analysis/collected-metrics.js +2 -1
- package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -2
- package/dist/domains/learning-optimization/active-patterns.d.ts +55 -0
- package/dist/domains/learning-optimization/active-patterns.js +80 -0
- package/dist/domains/learning-optimization/coordinator-helpers.js +2 -3
- package/dist/domains/learning-optimization/coordinator.d.ts +0 -3
- package/dist/domains/learning-optimization/coordinator.js +50 -106
- package/dist/domains/learning-optimization/index.d.ts +1 -1
- package/dist/domains/learning-optimization/interfaces.d.ts +56 -4
- package/dist/domains/learning-optimization/plugin.js +11 -1
- package/dist/domains/learning-optimization/reward-source.d.ts +37 -0
- package/dist/domains/learning-optimization/reward-source.js +58 -0
- package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +4 -4
- package/dist/domains/learning-optimization/services/learning-coordinator.js +68 -34
- package/dist/domains/learning-optimization/services/metrics-optimizer.d.ts +14 -4
- package/dist/domains/learning-optimization/services/metrics-optimizer.js +129 -63
- package/dist/domains/learning-optimization/services/transfer-specialist.js +25 -15
- package/dist/domains/test-execution/interfaces.d.ts +16 -0
- package/dist/domains/test-execution/services/retry-handler.js +18 -2
- package/dist/domains/test-execution/services/runner-test-cases.d.ts +21 -0
- package/dist/domains/test-execution/services/runner-test-cases.js +69 -0
- package/dist/domains/test-execution/services/test-executor.d.ts +5 -0
- package/dist/domains/test-execution/services/test-executor.js +24 -2
- package/dist/init/fleet-integration.js +2 -0
- package/dist/init/init-wizard-steps.js +2 -0
- package/dist/init/phases/06-code-intelligence.js +2 -0
- package/dist/init/phases/10-workers.js +2 -1
- package/dist/kernel/anti-drift-middleware.d.ts +44 -5
- package/dist/kernel/anti-drift-middleware.js +147 -11
- package/dist/kernel/interfaces.d.ts +5 -0
- package/dist/learning/dream/dream-engine.d.ts +27 -1
- package/dist/learning/dream/dream-engine.js +56 -2
- package/dist/learning/dream/dream-insights-pruner.d.ts +18 -4
- package/dist/learning/dream/dream-insights-pruner.js +99 -11
- package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -0
- package/dist/learning/dream/rvcow-branch-manager.js +8 -0
- package/dist/learning/dream/speculative-dreamer.d.ts +8 -0
- package/dist/learning/dream/speculative-dreamer.js +8 -0
- package/dist/learning/skill-validation-learner.d.ts +2 -0
- package/dist/learning/skill-validation-learner.js +29 -21
- package/dist/mcp/background-workers.d.ts +15 -0
- package/dist/mcp/background-workers.js +77 -0
- package/dist/mcp/bundle.js +511 -484
- package/dist/mcp/entry.js +4 -49
- package/dist/mcp/handlers/domain-handler-configs.d.ts +14 -0
- package/dist/mcp/handlers/domain-handler-configs.js +68 -30
- package/dist/mcp/handlers/handler-factory.js +1 -0
- package/dist/mcp/handlers/task-handlers.js +37 -1
- package/dist/mcp/metrics/metrics-collector.d.ts +11 -9
- package/dist/mcp/metrics/metrics-collector.js +13 -26
- package/dist/mcp/protocol-server.js +8 -3
- package/dist/mcp/tools/learning-optimization/optimize.d.ts +34 -3
- package/dist/mcp/tools/learning-optimization/optimize.js +106 -70
- package/dist/memory/crdt/lww-register.js +11 -1
- package/dist/routing/calibration/ema-calibrator.js +3 -1
- package/dist/shared/base-domain-plugin.d.ts +4 -0
- package/dist/shared/base-domain-plugin.js +6 -0
- package/dist/shared/llm/cache.js +4 -1
- package/dist/shared/security/compliance-patterns.js +3 -1
- package/dist/shared/test-runner-process.d.ts +26 -0
- package/dist/shared/test-runner-process.js +91 -0
- package/dist/shared/types/index.d.ts +9 -0
- package/dist/shared/types/index.js +13 -0
- package/dist/shared/utils/namespaced-search.d.ts +42 -0
- package/dist/shared/utils/namespaced-search.js +53 -0
- package/dist/strange-loop/infra-healing/infra-action-executor.js +7 -3
- package/dist/strange-loop/infra-healing/infra-healing-orchestrator.js +10 -9
- package/dist/workers/daemon.d.ts +7 -0
- package/dist/workers/daemon.js +21 -2
- package/dist/workers/namespaced-keys.d.ts +4 -7
- package/dist/workers/namespaced-keys.js +4 -15
- package/dist/workers/quality-daemon/ci-monitor.js +9 -5
- package/dist/workers/worker-env.d.ts +53 -0
- package/dist/workers/worker-env.js +89 -0
- package/dist/workers/worker-manager.js +4 -0
- package/dist/workers/workers/learning-consolidation.d.ts +20 -0
- package/dist/workers/workers/learning-consolidation.js +57 -23
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-PEOUNYXJ.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-DHKZI5RX.js +0 -2
- package/dist/cli/chunks/base-QZWK3D5P.js +0 -2
- package/dist/cli/chunks/browser-workflow-ITPX72RX.js +0 -2
- package/dist/cli/chunks/chunk-CG5DZCOZ.js +0 -2
- package/dist/cli/chunks/chunk-QJE6ZW2X.js +0 -6
- package/dist/cli/chunks/chunk-T3ZDVU6F.js +0 -5
- package/dist/cli/chunks/chunk-UIYKR2SA.js +0 -2
- package/dist/cli/chunks/chunk-VJRZFWR5.js +0 -2
- package/dist/cli/chunks/chunk-VUFRTGML.js +0 -3
- package/dist/cli/chunks/chunk-YDZJWDR6.js +0 -180
- package/dist/cli/chunks/client-S7GNYTZ5.js +0 -2
- package/dist/cli/chunks/core-handlers-CUEPOQIO.js +0 -2
- package/dist/cli/chunks/cross-domain-router-CXN5QFEV.js +0 -2
- package/dist/cli/chunks/daemon-3DQCKRYO.js +0 -10
- package/dist/cli/chunks/dream-5AUNJW24.js +0 -2
- package/dist/cli/chunks/file-discovery-AYWF357I.js +0 -2
- package/dist/cli/chunks/fleet-QX5KXTRC.js +0 -43
- package/dist/cli/chunks/heartbeat-scheduler-7ZIDVXIP.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-P77OC7FM.js +0 -2
- package/dist/cli/chunks/hnsw-index-3LBOTQAW.js +0 -2
- package/dist/cli/chunks/hybrid-backend-LOM54PDD.js +0 -2
- package/dist/cli/chunks/impact-analyzer-QSDJVBPS.js +0 -2
- package/dist/cli/chunks/init-wizard-MK2325JJ.js +0 -2
- package/dist/cli/chunks/kernel-2NJQQ2KT.js +0 -2
- package/dist/cli/chunks/knowledge-graph-SDISHO62.js +0 -2
- package/dist/cli/chunks/llm-router-service-YTCMRBAN.js +0 -2
- package/dist/cli/chunks/load-test-RPKHLBCC.js +0 -2
- package/dist/cli/chunks/memory-backend-BZXFO4JZ.js +0 -2
- package/dist/cli/chunks/memory-handlers-MOFDNB6E.js +0 -2
- package/dist/cli/chunks/pattern-null-store-4PRPIOR6.js +0 -2
- package/dist/cli/chunks/project-root-NBIQF63D.js +0 -2
- package/dist/cli/chunks/protocol-executor-BRPGIYWQ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-GDZACWKW.js +0 -2
- package/dist/cli/chunks/queen-coordinator-LDKLBPD5.js +0 -2
- package/dist/cli/chunks/router-H5YSIRH2.js +0 -2
- package/dist/cli/chunks/routing-feedback-5R36TJDH.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-TT2DBQQQ.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-BCLFJKSK.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-UXI66OQJ.js +0 -2
- package/dist/cli/chunks/safe-db-MSTD2GDH.js +0 -2
- package/dist/cli/chunks/schedule-KST6KIFD.js +0 -2
- package/dist/cli/chunks/scheduler-FTQS6YK3.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-ZX5QFDMR.js +0 -2
- package/dist/cli/chunks/task-handlers-6CRDEELN.js +0 -9
- package/dist/cli/chunks/unified-memory-2Z2F446J.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-A4EWYPJQ.js +0 -2
- package/dist/cli/chunks/unified-persistence-Z6N6JZFA.js +0 -2
- package/dist/cli/chunks/visual-security-GXYZV7KR.js +0 -2
- package/dist/cli/chunks/witness-chain-52PEIEGK.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-DORMQMG7.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
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 V,e as X,g as ae,h as G}from"./chunk-
|
|
3
|
-
`)}var It=(function(n){Et(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,Xe(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,l.prototype),d.message=Xe(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);R.PatchError=It});var ye=B(v=>{Object.defineProperty(v,"__esModule",{value:!0});var C=Z();v.JsonPatchError=C.PatchError;v.deepClone=C._deepClone;var U={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=ee(t,this.path);r&&(r=C._deepClone(r));var i=N(t,{op:"remove",path:this.from}).removed;return N(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=ee(t,this.from);return N(t,{op:"add",path:this.path,value:C._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Dt={add:function(n,e,t){return C.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function ee(n,e){if(e=="")return n;var t={op:"_get",path:e};return N(n,t),t.value}v.getValueByPointer=ee;function N(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):te(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=ee(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=C._deepClone(n));var l=e.path||"",d=l.split("/"),o=n,c=1,h=d.length,m=void 0,u=void 0,f=void 0;for(typeof t=="function"?f=t:f=te;;){if(u=d[c],u&&u.indexOf("~")!=-1&&(u=C.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&c>0&&d[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&m===void 0&&(o[u]===void 0?m=d.slice(0,c).join("/"):c==h-1&&(m=e.path),m!==void 0&&f(e,0,n,m)),c++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!C.isInteger(u))throw new v.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);C.isInteger(u)&&(u=~~u)}if(c>=h){if(t&&e.op==="add"&&u>o.length)throw new v.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Dt[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(c>=h){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&c<h&&(!o||typeof o!="object"))throw new v.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}v.applyOperation=N;function Ye(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=C._deepClone(n));for(var s=new Array(e.length),a=0,l=e.length;a<l;a++)s[a]=N(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}v.applyPatch=Ye;function Ft(n,e,t){var r=N(n,e);if(r.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}v.applyReducer=Ft;function te(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new v.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new v.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new v.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new v.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&C.hasUndefined(n.value))throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new v.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new v.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},l=Ke([a],t);if(l&&l.name==="OPERATION_PATH_UNRESOLVABLE")throw new v.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}v.validator=te;function Ke(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ye(C._deepClone(e),C._deepClone(n),t||!0);else{t=t||te;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof v.JsonPatchError)return i;throw i}}v.validate=Ke;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var l=Object.keys(n);if(s=l.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=s;i--!==0;)if(a=l[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}v._areEquals=J});var Ze=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var A=Z(),Ot=ye(),Se=new WeakMap,_t=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Nt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Mt(n){return Se.get(n)}function Ht(n,e){return n.observers.get(e)}function Lt(n,e){n.observers.delete(e.callback)}function kt(n,e){e.unobserve()}q.unobserve=kt;function Ut(n,e){var t=[],r,i=Mt(n);if(!i)i=new _t(n),Se.set(n,i);else{var s=Ht(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=A._deepClone(n),e){r.callback=e,r.next=null;var a=function(){ve(r)},l=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",l),window.addEventListener("keyup",l),window.addEventListener("mousedown",l),window.addEventListener("keydown",l),window.addEventListener("change",l))}return r.patches=t,r.object=n,r.unobserve=function(){ve(r),clearTimeout(r.next),Lt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",l),window.removeEventListener("keyup",l),window.removeEventListener("mousedown",l),window.removeEventListener("keydown",l),window.removeEventListener("change",l))},i.observers.set(e,new Nt(e,r)),r}q.observe=Ut;function ve(n,e){e===void 0&&(e=!1);var t=Se.get(n.object);we(t.value,n.object,n.patches,"",e),n.patches.length&&Ot.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ve;function we(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=A._objectKeys(e),a=A._objectKeys(n),l=!1,d=!1,o=a.length-1;o>=0;o--){var c=a[o],h=n[c];if(A.hasOwnProperty(e,c)&&!(e[c]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var m=e[c];typeof h=="object"&&h!=null&&typeof m=="object"&&m!=null&&Array.isArray(h)===Array.isArray(m)?we(h,m,t,r+"/"+A.escapePathComponent(c),i):h!==m&&(l=!0,i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"replace",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(m)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"remove",path:r+"/"+A.escapePathComponent(c)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),l=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var c=s[o];!A.hasOwnProperty(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(e[c])})}}}function qt(n,e,t){t===void 0&&(t=!1);var r=[];return we(n,e,r,"",t),r}q.compare=qt});var et=B(M=>{var Qt=ye();Object.assign(M,Qt);var $t=Ze();Object.assign(M,$t);var re=Z();M.JsonPatchError=re.PatchError;M.deepClone=re._deepClone;M.escapePathComponent=re.escapePathComponent;M.unescapePathComponent=re.unescapePathComponent});var T=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};function rr(n){return n instanceof T&&n.disposition==="COMMITTED_PENDING_INDEX"?n.patternId:null}ft();import{existsSync as Zt}from"node:fs";import{join as ct}from"node:path";Oe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??Y,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{!this.embeddingSpaceId&&!x()&&await W();let e=x()?.spaceId??this.embeddingSpaceId??null;e?(this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),Qe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)):(this.rvfInitError=Ue,this.adapter=null,this.initialized=!0,qe())}catch(e){this.rvfInitError=b(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-ZX5QFDMR.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),l=new Set((a.entries??[]).map(c=>Array.isArray(c)?c[0]:void 0).filter(c=>typeof c=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(c=>c.id)),o=[...l].filter(c=>!d.has(c));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${b(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return S(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=x()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return S(new T(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return S(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return S(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:V({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let d=x()?.spaceId??this.embeddingSpaceId;if(!d||t.embeddingSpaceId!==d)return S(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let d=e instanceof Float32Array?e:new Float32Array(e),o=this.adapter.search(d,i*2);for(let c of o){let h=await this.get(c.id);if(h&&this.matchesFilters(h,t)){let m=this.calculateReuseInfo(h,c.score);s.push({pattern:h,score:c.score,matchType:"vector",similarity:c.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}catch(d){console.warn("[RvfPatternStore] RVF search failed:",b(d))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let d=x()?.spaceId??this.embeddingSpaceId,o=this.sqliteStore.getAllEmbeddings(),c=e,h=Math.sqrt(c.reduce((m,u)=>m+u*u,0));if(h>0)for(let m of o){if(!d||m.spaceId!==d)continue;let u=this.sqliteStore.getPattern(m.patternId);if(!u||!this.matchesFilters(u,t))continue;let f=m.embedding;if(!f||f.length!==c.length)continue;let g=0,y=0;for(let E=0;E<c.length;E++)g+=c[E]*f[E],y+=f[E]*f[E];if(y=Math.sqrt(y),y===0)continue;let p=g/(h*y),w=this.calculateReuseInfo(u,p);s.push({pattern:u,score:p,matchType:"vector",similarity:p,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.getPatterns({limit:i*2}),o=new Set(s.map(c=>c.pattern.id));for(let c of d)o.has(c.id)||this.matchesFilters(c,t)&&s.push({pattern:c,score:c.confidence,matchType:"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}catch{}let a=typeof e=="string"?e:t.textQuery;if(a?.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(a,i*2),o=new Set(s.map(h=>h.pattern.id)),c=new Map(d.map(h=>[h.id,h.ftsScore*h.coverage]));for(let h of s){let m=c.get(h.pattern.id);m!==void 0&&(h.score=le(h.score,m))}for(let h of d){if(o.has(h.id))continue;let m=await this.get(h.id);if(m&&this.matchesFilters(m,t)){let u=.5*h.ftsScore*h.coverage;s.push({pattern:m,score:u,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}catch{}s.sort((d,o)=>o.score-d.score);let l=performance.now()-r;return this.searchOps++,this.totalSearchMs+=l,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return S(new Error(`recordUsage failed: ${b(s)}`))}}async promote(e){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return S(new Error(`promote failed: ${b(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,b(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return S(new Error(`SQLite delete failed: ${b(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=X&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",b(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};mt();Oe();_();function gt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let l of s){if(a==null)break;if(typeof a=="object")a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function yt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),l=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=l}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function K(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>K(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>K(n,r))}case"NOT":return e.child?!K(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=gt(n,e.field);return yt(t,e.operator,e.value)}default:return!0}}function $e(n,e){return e?n.filter(t=>K(t,e)):n}_();_();var Je=1e4,Be=2166136261;function je(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var he=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;he[n]=e}var ze="0123456789abcdef";function vt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=ze[i>>4]+ze[i&15]}return t}function St(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function wt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let l=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&l++;l>=r&&(s|=d)}t[i]=s}return t}function bt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=he[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function Pt(n,e,t){return 1-bt(n,e,t)}var de=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Je,this.baseSeed=e?.seed??Be,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=je(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=St(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return wt([r,i])}similarity(e,t){return Pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new oe(e),i=0;for(;i<this.byteLen;){let a=r.next(),l=Math.min(4,this.byteLen-i);for(let d=0;d<l;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ue=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Je,this.baseSeed=e?.seed??Be,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=je(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:vt(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=he[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new oe(e),s=0;for(;s<t;){let l=i.next(),d=t-s,o=d<4?d:4;for(let c=0;c<o;c++)r[s++]=l>>>c*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function We(n){return new ue(n)}function Ve(n){return $()?new de(n):null}var Pe=ht(et(),1),be=Pe.default??Pe,zt=`
|
|
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.9");process.exit(0)}
|
|
2
|
+
import{d as V,e as X,g as ae,h as G}from"./chunk-F3PQZX44.js";import{a as oe}from"./chunk-DDPPSSHW.js";import{a as ce}from"./chunk-AVB5QY2Q.js";import{c as Ue,d as qe,e as Qe,p as x,q as W}from"./chunk-BXO536GT.js";import{i as O}from"./chunk-FV7VAG74.js";import{c as P,d as S}from"./chunk-JNNZK7KH.js";import{a as b,b as Fe,e as Oe}from"./chunk-N3KEY4XJ.js";import{B as $,D as L,G as ie,P as k,S as _,b as F}from"./chunk-2I2UPJS7.js";import{c as ke}from"./chunk-PX2B5TS2.js";import{c as _e,d as ft}from"./chunk-4V27J6YN.js";import{c as j,e as Ne,f as Me}from"./chunk-OXZLKP6C.js";import{a as se,b as He,d as Le,f as mt}from"./chunk-SNBYYO6F.js";import{c as B,e as ht}from"./chunk-HZ5NC6U5.js";var Z=B(R=>{var Et=R&&R.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(R,"__esModule",{value:!0});var At=Object.prototype.hasOwnProperty;function pe(n,e){return At.call(n,e)}R.hasOwnProperty=pe;function Ge(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)pe(n,i)&&r.push(i);return r}R._objectKeys=Ge;function Tt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}R._deepClone=Tt;function Rt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}R.isInteger=Rt;function fe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}R.escapePathComponent=fe;function xt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}R.unescapePathComponent=xt;function ge(n,e){var t;for(var r in n)if(pe(n,r)){if(n[r]===e)return fe(r)+"/";if(typeof n[r]=="object"&&(t=ge(n[r],e),t!=""))return fe(r)+"/"+t}return""}R._getPathRecursive=ge;function Ct(n,e){if(n===e)return"/";var t=ge(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}R.getPath=Ct;function me(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(me(n[e]))return!0}else if(typeof n=="object"){for(var r=Ge(n),i=r.length,s=0;s<i;s++)if(me(n[r[s]]))return!0}}return!1}R.hasUndefined=me;function Xe(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
|
|
3
|
+
`)}var It=(function(n){Et(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,Xe(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,l.prototype),d.message=Xe(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);R.PatchError=It});var ye=B(v=>{Object.defineProperty(v,"__esModule",{value:!0});var C=Z();v.JsonPatchError=C.PatchError;v.deepClone=C._deepClone;var U={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=ee(t,this.path);r&&(r=C._deepClone(r));var i=N(t,{op:"remove",path:this.from}).removed;return N(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=ee(t,this.from);return N(t,{op:"add",path:this.path,value:C._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Dt={add:function(n,e,t){return C.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function ee(n,e){if(e=="")return n;var t={op:"_get",path:e};return N(n,t),t.value}v.getValueByPointer=ee;function N(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):te(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=ee(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=C._deepClone(n));var l=e.path||"",d=l.split("/"),o=n,c=1,h=d.length,m=void 0,u=void 0,f=void 0;for(typeof t=="function"?f=t:f=te;;){if(u=d[c],u&&u.indexOf("~")!=-1&&(u=C.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&c>0&&d[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&m===void 0&&(o[u]===void 0?m=d.slice(0,c).join("/"):c==h-1&&(m=e.path),m!==void 0&&f(e,0,n,m)),c++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!C.isInteger(u))throw new v.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);C.isInteger(u)&&(u=~~u)}if(c>=h){if(t&&e.op==="add"&&u>o.length)throw new v.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Dt[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(c>=h){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&c<h&&(!o||typeof o!="object"))throw new v.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}v.applyOperation=N;function Ye(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=C._deepClone(n));for(var s=new Array(e.length),a=0,l=e.length;a<l;a++)s[a]=N(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}v.applyPatch=Ye;function Ft(n,e,t){var r=N(n,e);if(r.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}v.applyReducer=Ft;function te(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new v.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new v.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new v.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new v.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&C.hasUndefined(n.value))throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new v.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new v.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},l=Ke([a],t);if(l&&l.name==="OPERATION_PATH_UNRESOLVABLE")throw new v.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}v.validator=te;function Ke(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ye(C._deepClone(e),C._deepClone(n),t||!0);else{t=t||te;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof v.JsonPatchError)return i;throw i}}v.validate=Ke;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var l=Object.keys(n);if(s=l.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=s;i--!==0;)if(a=l[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}v._areEquals=J});var Ze=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var A=Z(),Ot=ye(),Se=new WeakMap,_t=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Nt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Mt(n){return Se.get(n)}function Ht(n,e){return n.observers.get(e)}function Lt(n,e){n.observers.delete(e.callback)}function kt(n,e){e.unobserve()}q.unobserve=kt;function Ut(n,e){var t=[],r,i=Mt(n);if(!i)i=new _t(n),Se.set(n,i);else{var s=Ht(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=A._deepClone(n),e){r.callback=e,r.next=null;var a=function(){ve(r)},l=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",l),window.addEventListener("keyup",l),window.addEventListener("mousedown",l),window.addEventListener("keydown",l),window.addEventListener("change",l))}return r.patches=t,r.object=n,r.unobserve=function(){ve(r),clearTimeout(r.next),Lt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",l),window.removeEventListener("keyup",l),window.removeEventListener("mousedown",l),window.removeEventListener("keydown",l),window.removeEventListener("change",l))},i.observers.set(e,new Nt(e,r)),r}q.observe=Ut;function ve(n,e){e===void 0&&(e=!1);var t=Se.get(n.object);we(t.value,n.object,n.patches,"",e),n.patches.length&&Ot.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ve;function we(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=A._objectKeys(e),a=A._objectKeys(n),l=!1,d=!1,o=a.length-1;o>=0;o--){var c=a[o],h=n[c];if(A.hasOwnProperty(e,c)&&!(e[c]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var m=e[c];typeof h=="object"&&h!=null&&typeof m=="object"&&m!=null&&Array.isArray(h)===Array.isArray(m)?we(h,m,t,r+"/"+A.escapePathComponent(c),i):h!==m&&(l=!0,i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"replace",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(m)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"remove",path:r+"/"+A.escapePathComponent(c)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),l=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var c=s[o];!A.hasOwnProperty(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(e[c])})}}}function qt(n,e,t){t===void 0&&(t=!1);var r=[];return we(n,e,r,"",t),r}q.compare=qt});var et=B(M=>{var Qt=ye();Object.assign(M,Qt);var $t=Ze();Object.assign(M,$t);var re=Z();M.JsonPatchError=re.PatchError;M.deepClone=re._deepClone;M.escapePathComponent=re.escapePathComponent;M.unescapePathComponent=re.unescapePathComponent});var T=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};function rr(n){return n instanceof T&&n.disposition==="COMMITTED_PENDING_INDEX"?n.patternId:null}ft();import{existsSync as Zt}from"node:fs";import{join as ct}from"node:path";Oe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??Y,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{!this.embeddingSpaceId&&!x()&&await W();let e=x()?.spaceId??this.embeddingSpaceId??null;e?(this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),Qe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)):(this.rvfInitError=Ue,this.adapter=null,this.initialized=!0,qe())}catch(e){this.rvfInitError=b(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-AWRIS4MK.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),l=new Set((a.entries??[]).map(c=>Array.isArray(c)?c[0]:void 0).filter(c=>typeof c=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(c=>c.id)),o=[...l].filter(c=>!d.has(c));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${b(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return S(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=x()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return S(new T(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return S(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return S(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:V({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let d=x()?.spaceId??this.embeddingSpaceId;if(!d||t.embeddingSpaceId!==d)return S(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let d=e instanceof Float32Array?e:new Float32Array(e),o=this.adapter.search(d,i*2);for(let c of o){let h=await this.get(c.id);if(h&&this.matchesFilters(h,t)){let m=this.calculateReuseInfo(h,c.score);s.push({pattern:h,score:c.score,matchType:"vector",similarity:c.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}catch(d){console.warn("[RvfPatternStore] RVF search failed:",b(d))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let d=x()?.spaceId??this.embeddingSpaceId,o=this.sqliteStore.getAllEmbeddings(),c=e,h=Math.sqrt(c.reduce((m,u)=>m+u*u,0));if(h>0)for(let m of o){if(!d||m.spaceId!==d)continue;let u=this.sqliteStore.getPattern(m.patternId);if(!u||!this.matchesFilters(u,t))continue;let f=m.embedding;if(!f||f.length!==c.length)continue;let g=0,y=0;for(let E=0;E<c.length;E++)g+=c[E]*f[E],y+=f[E]*f[E];if(y=Math.sqrt(y),y===0)continue;let p=g/(h*y),w=this.calculateReuseInfo(u,p);s.push({pattern:u,score:p,matchType:"vector",similarity:p,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.getPatterns({limit:i*2}),o=new Set(s.map(c=>c.pattern.id));for(let c of d)o.has(c.id)||this.matchesFilters(c,t)&&s.push({pattern:c,score:c.confidence,matchType:"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}catch{}let a=typeof e=="string"?e:t.textQuery;if(a?.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(a,i*2),o=new Set(s.map(h=>h.pattern.id)),c=new Map(d.map(h=>[h.id,h.ftsScore*h.coverage]));for(let h of s){let m=c.get(h.pattern.id);m!==void 0&&(h.score=le(h.score,m))}for(let h of d){if(o.has(h.id))continue;let m=await this.get(h.id);if(m&&this.matchesFilters(m,t)){let u=.5*h.ftsScore*h.coverage;s.push({pattern:m,score:u,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}catch{}s.sort((d,o)=>o.score-d.score);let l=performance.now()-r;return this.searchOps++,this.totalSearchMs+=l,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return S(new Error(`recordUsage failed: ${b(s)}`))}}async promote(e){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return S(new Error(`promote failed: ${b(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,b(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return S(new Error(`SQLite delete failed: ${b(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=X&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",b(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};mt();Oe();_();function gt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let l of s){if(a==null)break;if(typeof a=="object")a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function yt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),l=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=l}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function K(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>K(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>K(n,r))}case"NOT":return e.child?!K(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=gt(n,e.field);return yt(t,e.operator,e.value)}default:return!0}}function $e(n,e){return e?n.filter(t=>K(t,e)):n}_();_();var Je=1e4,Be=2166136261;function je(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var he=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;he[n]=e}var ze="0123456789abcdef";function vt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=ze[i>>4]+ze[i&15]}return t}function St(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function wt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let l=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&l++;l>=r&&(s|=d)}t[i]=s}return t}function bt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=he[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function Pt(n,e,t){return 1-bt(n,e,t)}var de=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Je,this.baseSeed=e?.seed??Be,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=je(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=St(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return wt([r,i])}similarity(e,t){return Pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new oe(e),i=0;for(;i<this.byteLen;){let a=r.next(),l=Math.min(4,this.byteLen-i);for(let d=0;d<l;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ue=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Je,this.baseSeed=e?.seed??Be,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=je(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:vt(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=he[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new oe(e),s=0;for(;s<t;){let l=i.next(),d=t-s,o=d<4?d:4;for(let c=0;c<o;c++)r[s++]=l>>>c*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function We(n){return new ue(n)}function Ve(n){return $()?new de(n):null}var Pe=ht(et(),1),be=Pe.default??Pe,zt=`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
pattern_id TEXT NOT NULL,
|
|
@@ -46,7 +46,7 @@ import{d as V,e as X,g as ae,h as G}from"./chunk-V2SAEMZY.js";import{a as oe}fro
|
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};_();var Bt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Ee=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Bt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,l=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:l,metadata:i,compressedSize:l.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let l=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(l,o.sparseChanges)}return l}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),l=i.slice(s),d=a.findIndex(h=>h.deltaType==="genesis");d>=0&&(l.unshift(a[d]),a.splice(d,1)),this.history.set(e,l);let o=l[0]?.version??0,c=this.snapshots.get(e);return c&&this.snapshots.set(e,c.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,l=s<t.length?t[s]:0;Math.abs(a-l)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:l})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function nt(n){return L()?new Ee(n):null}_();var jt=128,Wt=8,Vt=1e4,Ae=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??jt,this.beta=e?.beta??Wt,this.maxPatterns=e?.maxPatterns??Vt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let c=0;c<this.patterns.length;c++)r[c]=this.beta*this.dotProduct(this.patterns[c].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let c=1;c<i.length;c++)i[c]>a&&(a=i[c],s=c);let l=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,l.pattern);return{pattern:new Float32Array(l.pattern),metadata:{...l.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let l=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-l+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function it(n){return new Ae(n)}_();var Xt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,st=1-H;function Gt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function I(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Yt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var D=class n{static poincareDistance(e,t){let r=I(Yt(e,t)),i=Math.max(H,1-I(e)),s=Math.max(H,1-I(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Gt(e,t),i=I(e),s=I(t),a=Math.max(H,1+2*r+i*s),l=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let c=0;c<e.length;c++)o[c]=(l*e[c]+d*t[c])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(H,1-I(e)),i=Math.sqrt(I(t));if(i<H)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let l=0;l<t.length;l++)a[l]=s/i*t[l];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(I(e));if(t<=st)return new Float32Array(e);let r=st/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(I(e));if(t<H)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Te=class{config;points=new Map;constructor(e){if(this.config={...Xt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:D.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=D.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:D.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let l=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;l.length>0;){let{id:d,depth:o,angOff:c,angSpan:h}=l.shift(),m=Math.tanh(.3*(o+.1)),u=c+h/2,f=new Float32Array(r);f[0]=m*Math.cos(u),f[1]=m*Math.sin(u);let g=s.get(d);if(g&&g.features.length>0){let w=m*.1;for(let E=2;E<r&&E-2<g.features.length;E++)f[E]=g.features[E-2]*w}let y=D.project(f);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:g?.parentId}});let p=i.get(d)??[];for(let w=0;w<p.length;w++){let E=h/Math.max(1,p.length);l.push({id:p[w],depth:o+1,angOff:c+w*E,angSpan:E})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function at(n){return Kt()?new Te(n):null}function Kt(){return F().useHyperbolicHnsw}_();var Re=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=at(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=D.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=D.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function ot(n){return new Re(n)}var xe=null;function lt(){return xe||(xe=We({dimensions:1e4})),xe}var Ce;function er(){return Ce===void 0&&(Ce=Ve()),Ce}var Q=null,Ie=0,dt;function ut(n,e){return(!Q||Ie!==n||dt!==e)&&(Q=it({dimension:n,maxPatterns:1e4}),Ie=n,dt=e),Q}var Y={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:X,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},De=class{constructor(e,t={}){this.memory=e;this.config={...Y,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ne(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=x()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(!x()&&!this.config.embeddingSpaceId&&await W(),this.hnswSpaceId=x()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-6MLLOGOE.js"),{HnswAdapter:l}=await import("./hnsw-adapter-P77OC7FM.js"),d=new l("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-3LBOTQAW.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,l)=>setTimeout(()=>l(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",b(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=x()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:l,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!l||l.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,l,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",b(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=nt()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",b(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return S(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=x()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,l=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),l=!0}catch(o){return d(),S(new T(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return S(new T(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),S(new T(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(c){return l||d(),S(new T(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if($())try{let c=lt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,b(o))}try{let o=er();if(o){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let h=o.fingerprintPattern(c);this.hdcTokenCache.set(e.id,h)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,b(o))}if(ie()&&e.embedding&&i)try{ut(e.embedding.length,i).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,b(o))}if(L()&&this.deltaTracker)try{let o={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,b(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,b(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{let a=x()?.spaceId??this.config.embeddingSpaceId;if(Array.isArray(e)&&(!a||t.embeddingSpaceId!==a))throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");if(Array.isArray(e)&&t.useVectorSearch!==!1&&a&&ie())try{let f=ut(e.length,a);if(f.getPatternCount()>0){let g=f.recall(new Float32Array(e));if(g&&g.similarity>.98){let y=g.metadata.id,p=await this.get(y);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,g.similarity);s.push({pattern:p,score:g.similarity,matchType:"vector",similarity:g.similarity,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",b(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=await this.ensureHNSW();if(f){let g=await f.search(e,i*2);for(let y of g){let p=await this.get(y.key);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,y.score);s.push({pattern:p,score:y.score,matchType:"vector",similarity:y.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}let l=typeof e=="string"?e:t.textQuery;if(l?.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(l,i*2);if(f.length>0){let g=new Map(f.map(p=>[p.id,p.ftsScore*p.coverage])),y=new Set(s.map(p=>p.pattern.id));for(let p of s){let w=g.get(p.pattern.id);w!==void 0&&(p.score=le(p.score,w))}for(let p of f){if(y.has(p.id))continue;let w=await this.get(p.id);if(w&&this.matchesFilters(w,t)){let E=.5*p.ftsScore*p.coverage;s.push({pattern:w,score:E,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(l??"",t,i-s.length),g=new Set(s.map(y=>y.pattern.id));for(let y of f)g.has(y.pattern.id)||s.push(y)}let d=720*60*60*1e3,o=Date.now();for(let f of s){let g=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),y=o-g,p=Math.pow(.5,y/d),w=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*w)}let c=this.sqliteStore?.getDatabase();if(c&&s.length>0)try{this.nullStore||(this.nullStore=new ce(c));let f=this.nullStore.getNullSummaries(s.map(g=>g.pattern.id));for(let g of s){let y=f.get(g.pattern.id);y&&(g.nullSummary=y,g.score=ce.applyNullDiscount(g.score,y,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",b(f))}s.sort((f,g)=>g.score-f.score);let h=s;t.filter&&(h=$e(s,t.filter));let m=h.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),P(m)}catch(a){return S(Fe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let l=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=lt(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),c=l.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));c.sort((u,f)=>f.similarity-u.similarity);let h=c.map(u=>u.id),m=l.filter(u=>!this.hdcCache.has(u));l=[...h,...m]}catch{}for(let d of l){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let c=0;if(s){let h=o.name.toLowerCase(),m=o.description.toLowerCase();h.includes(s)&&(c+=.5),m.includes(s)&&(s.length/m.length>.3?c+=.5:c+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){c+=.2;break}c=Math.min(c,1)}else c=o.qualityScore;(c>0||!s)&&i.push({pattern:o,score:s?.5*c:o.qualityScore,matchType:s?"lexical":"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,c=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,m=e.successRate,u=Math.min(e.reuseCount/10,1),f=o?h*.4+m*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:c,reuseConfidence:f}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return S(new Error(`Pattern not found: ${e}`));let a=new Date,l=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/l,c=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+c)),m=V({confidence:h,usageCount:l,successRate:o}),u={...s,usageCount:l,successfulUses:d,successRate:o,confidence:h,qualityScore:m,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,b(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},p={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,p,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,b(y))}let f=ae(u);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,c]of this.domainIndex)e[o]=c.size;for(let[o,c]of this.typeIndex)t[o]=c.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let l=await this.ensureHNSW(),d=l!==null?await l.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ae(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,c=o>10080*60*1e3,h=s.qualityScore<.2,m=s.usageCount===0&&o>1440*60*1e3;(c&&h||m)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let l=this.patternCache.get(a);l&&r.push(l)}r.sort((a,l)=>a.qualityScore-l.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Ie=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=ot({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let l=Math.exp(-s.distance),d=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l,matchType:"vector",similarity:l,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function le(n,e){return Math.max(n,.75*n+.25*e)}function hn(n,e){try{if(F().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??_e(),i=ct(r,".agentic-qe"),s=ct(i,"patterns.rvf");if(Zt(i)){let a={...Y,...e},l=!1;try{let d=ke(i,a.embeddingDimension);if(d){l=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!l){let d=new z((o,c)=>{let h,m=()=>{try{return He(o)}catch(f){return h=f,null}},u=m();if(!u&&j(h)&&(!Ne(o)||(u=m(),!u&&j(h))))throw h;if(u){let f=u.dimension();if(f!==c){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${f}, requested=${c})`)}return u}try{return se(o,c)}catch(f){if(u=m(),u){if(u.dimension()!==c){let g=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${g}, requested=${c})`)}return u}if(j(h))throw h;if(Me(o,f instanceof Error?f.message:String(f),h))return se(o,c);throw f}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new De(n,e)}export{T as a,rr as b,Y as c,le as d,hn as e};
|
|
49
|
+
)`).run(e,e,s)}}};_();var Bt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Ee=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Bt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,l=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:l,metadata:i,compressedSize:l.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let l=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(l,o.sparseChanges)}return l}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),l=i.slice(s),d=a.findIndex(h=>h.deltaType==="genesis");d>=0&&(l.unshift(a[d]),a.splice(d,1)),this.history.set(e,l);let o=l[0]?.version??0,c=this.snapshots.get(e);return c&&this.snapshots.set(e,c.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,l=s<t.length?t[s]:0;Math.abs(a-l)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:l})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function nt(n){return L()?new Ee(n):null}_();var jt=128,Wt=8,Vt=1e4,Ae=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??jt,this.beta=e?.beta??Wt,this.maxPatterns=e?.maxPatterns??Vt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let c=0;c<this.patterns.length;c++)r[c]=this.beta*this.dotProduct(this.patterns[c].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let c=1;c<i.length;c++)i[c]>a&&(a=i[c],s=c);let l=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,l.pattern);return{pattern:new Float32Array(l.pattern),metadata:{...l.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let l=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-l+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function it(n){return new Ae(n)}_();var Xt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,st=1-H;function Gt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function I(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Yt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var D=class n{static poincareDistance(e,t){let r=I(Yt(e,t)),i=Math.max(H,1-I(e)),s=Math.max(H,1-I(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Gt(e,t),i=I(e),s=I(t),a=Math.max(H,1+2*r+i*s),l=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let c=0;c<e.length;c++)o[c]=(l*e[c]+d*t[c])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(H,1-I(e)),i=Math.sqrt(I(t));if(i<H)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let l=0;l<t.length;l++)a[l]=s/i*t[l];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(I(e));if(t<=st)return new Float32Array(e);let r=st/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(I(e));if(t<H)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Te=class{config;points=new Map;constructor(e){if(this.config={...Xt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:D.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=D.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:D.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let l=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;l.length>0;){let{id:d,depth:o,angOff:c,angSpan:h}=l.shift(),m=Math.tanh(.3*(o+.1)),u=c+h/2,f=new Float32Array(r);f[0]=m*Math.cos(u),f[1]=m*Math.sin(u);let g=s.get(d);if(g&&g.features.length>0){let w=m*.1;for(let E=2;E<r&&E-2<g.features.length;E++)f[E]=g.features[E-2]*w}let y=D.project(f);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:g?.parentId}});let p=i.get(d)??[];for(let w=0;w<p.length;w++){let E=h/Math.max(1,p.length);l.push({id:p[w],depth:o+1,angOff:c+w*E,angSpan:E})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function at(n){return Kt()?new Te(n):null}function Kt(){return F().useHyperbolicHnsw}_();var Re=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=at(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=D.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=D.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function ot(n){return new Re(n)}var xe=null;function lt(){return xe||(xe=We({dimensions:1e4})),xe}var Ce;function er(){return Ce===void 0&&(Ce=Ve()),Ce}var Q=null,Ie=0,dt;function ut(n,e){return(!Q||Ie!==n||dt!==e)&&(Q=it({dimension:n,maxPatterns:1e4}),Ie=n,dt=e),Q}var Y={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:X,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},De=class{constructor(e,t={}){this.memory=e;this.config={...Y,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ne(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=x()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(!x()&&!this.config.embeddingSpaceId&&await W(),this.hnswSpaceId=x()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-RYUJPA7B.js"),{HnswAdapter:l}=await import("./hnsw-adapter-EPSA6AP7.js"),d=new l("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-RMFOPYGY.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,l)=>setTimeout(()=>l(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",b(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=x()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:l,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!l||l.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,l,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",b(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=nt()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",b(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return S(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=x()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,l=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),l=!0}catch(o){return d(),S(new T(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return S(new T(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),S(new T(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(c){return l||d(),S(new T(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if($())try{let c=lt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,b(o))}try{let o=er();if(o){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let h=o.fingerprintPattern(c);this.hdcTokenCache.set(e.id,h)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,b(o))}if(ie()&&e.embedding&&i)try{ut(e.embedding.length,i).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,b(o))}if(L()&&this.deltaTracker)try{let o={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,b(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,b(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{let a=x()?.spaceId??this.config.embeddingSpaceId;if(Array.isArray(e)&&(!a||t.embeddingSpaceId!==a))throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");if(Array.isArray(e)&&t.useVectorSearch!==!1&&a&&ie())try{let f=ut(e.length,a);if(f.getPatternCount()>0){let g=f.recall(new Float32Array(e));if(g&&g.similarity>.98){let y=g.metadata.id,p=await this.get(y);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,g.similarity);s.push({pattern:p,score:g.similarity,matchType:"vector",similarity:g.similarity,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",b(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=await this.ensureHNSW();if(f){let g=await f.search(e,i*2);for(let y of g){let p=await this.get(y.key);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,y.score);s.push({pattern:p,score:y.score,matchType:"vector",similarity:y.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}let l=typeof e=="string"?e:t.textQuery;if(l?.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(l,i*2);if(f.length>0){let g=new Map(f.map(p=>[p.id,p.ftsScore*p.coverage])),y=new Set(s.map(p=>p.pattern.id));for(let p of s){let w=g.get(p.pattern.id);w!==void 0&&(p.score=le(p.score,w))}for(let p of f){if(y.has(p.id))continue;let w=await this.get(p.id);if(w&&this.matchesFilters(w,t)){let E=.5*p.ftsScore*p.coverage;s.push({pattern:w,score:E,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(l??"",t,i-s.length),g=new Set(s.map(y=>y.pattern.id));for(let y of f)g.has(y.pattern.id)||s.push(y)}let d=720*60*60*1e3,o=Date.now();for(let f of s){let g=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),y=o-g,p=Math.pow(.5,y/d),w=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*w)}let c=this.sqliteStore?.getDatabase();if(c&&s.length>0)try{this.nullStore||(this.nullStore=new ce(c));let f=this.nullStore.getNullSummaries(s.map(g=>g.pattern.id));for(let g of s){let y=f.get(g.pattern.id);y&&(g.nullSummary=y,g.score=ce.applyNullDiscount(g.score,y,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",b(f))}s.sort((f,g)=>g.score-f.score);let h=s;t.filter&&(h=$e(s,t.filter));let m=h.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),P(m)}catch(a){return S(Fe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let l=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=lt(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),c=l.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));c.sort((u,f)=>f.similarity-u.similarity);let h=c.map(u=>u.id),m=l.filter(u=>!this.hdcCache.has(u));l=[...h,...m]}catch{}for(let d of l){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let c=0;if(s){let h=o.name.toLowerCase(),m=o.description.toLowerCase();h.includes(s)&&(c+=.5),m.includes(s)&&(s.length/m.length>.3?c+=.5:c+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){c+=.2;break}c=Math.min(c,1)}else c=o.qualityScore;(c>0||!s)&&i.push({pattern:o,score:s?.5*c:o.qualityScore,matchType:s?"lexical":"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,c=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,m=e.successRate,u=Math.min(e.reuseCount/10,1),f=o?h*.4+m*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:c,reuseConfidence:f}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return S(new Error(`Pattern not found: ${e}`));let a=new Date,l=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/l,c=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+c)),m=V({confidence:h,usageCount:l,successRate:o}),u={...s,usageCount:l,successfulUses:d,successRate:o,confidence:h,qualityScore:m,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,b(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},p={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,p,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,b(y))}let f=ae(u);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,c]of this.domainIndex)e[o]=c.size;for(let[o,c]of this.typeIndex)t[o]=c.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let l=await this.ensureHNSW(),d=l!==null?await l.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ae(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,c=o>10080*60*1e3,h=s.qualityScore<.2,m=s.usageCount===0&&o>1440*60*1e3;(c&&h||m)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let l=this.patternCache.get(a);l&&r.push(l)}r.sort((a,l)=>a.qualityScore-l.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Ie=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=ot({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let l=Math.exp(-s.distance),d=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l,matchType:"vector",similarity:l,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function le(n,e){return Math.max(n,.75*n+.25*e)}function hn(n,e){try{if(F().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??_e(),i=ct(r,".agentic-qe"),s=ct(i,"patterns.rvf");if(Zt(i)){let a={...Y,...e},l=!1;try{let d=ke(i,a.embeddingDimension);if(d){l=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!l){let d=new z((o,c)=>{let h,m=()=>{try{return He(o)}catch(f){return h=f,null}},u=m();if(!u&&j(h)&&(!Ne(o)||(u=m(),!u&&j(h))))throw h;if(u){let f=u.dimension();if(f!==c){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${f}, requested=${c})`)}return u}try{return se(o,c)}catch(f){if(u=m(),u){if(u.dimension()!==c){let g=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${g}, requested=${c})`)}return u}if(j(h))throw h;if(Me(o,f instanceof Error?f.message:String(f),h))return se(o,c);throw f}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new De(n,e)}export{T as a,rr as b,Y as c,le as d,hn as e};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|
|
@@ -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.9");process.exit(0)}
|
|
2
2
|
var i={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},l=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function u(t){return t?{AQE_MEMORY_BACKEND:"memory",AQE_V3_MODE:"true"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}}function m(t,o){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:u(o)};return t&&(e.disabled=!1,e.alwaysAllow=l),e}function g(t,o){let e=m(t.supportsAutoApprove,o);if(t.id==="copilot"){let r={[t.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(r,null,2)+`
|
|
3
3
|
`}let n={[t.configKey]:{"agentic-qe":e}};return JSON.stringify(n,null,2)+`
|
|
4
4
|
`}function f(t){return`# Agentic QE MCP Server
|
|
@@ -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{l 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.9");process.exit(0)}
|
|
2
|
+
import{l as m}from"./chunk-JK2ME6IT.js";import{a as l,e as d}from"./chunk-N3KEY4XJ.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-ZM43WGDO.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c 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.9");process.exit(0)}
|
|
2
|
+
function l(e){let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r.replace(/\*/g,".*").replace(/\?/g,".")}$`,"s")}function g(e,r,t){return l(t).test(e)?e:e.startsWith(`${r}:`)?e.slice(r.length+1):e}var p=1e4;async function o(e,r,t={}){let i=Math.max(1,Math.floor(t.pageSize??p)),s=await e.search(r,i,t.retrieve);for(;s.length>=i;)i*=2,s=await e.search(r,i,t.retrieve);let n=t.retrieve?.namespace,a=n?s.map(c=>g(c,n,r)):s;return[...new Set(a)].sort()}export{g as a,o as b};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as 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.9");process.exit(0)}
|
|
2
|
+
import{b as S}from"./chunk-HZ5NC6U5.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
|
|
3
3
|
`,{mode:384})}catch{}}var y,O=S(()=>{"use strict";y=["/","/tmp","/var/tmp","/usr/tmp","/dev/shm","/run/shm","/private","/private/tmp","/private/var","/private/var/tmp","/var","/usr","/etc","/opt","/srv","/mnt","/media","/run","/home","/Users","/Volumes"]});export{w as a,b,k as c,E as d,R as e,O 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.
|
|
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.9");process.exit(0)}
|
|
2
2
|
var i=/[\s\x00-\x1f\x7f]/;function e(t,n="git ref"){if(typeof t!="string"||t.length===0)return`Invalid ${n}: must be a non-empty string`;if(t.length>256)return`Invalid ${n}: longer than 256 characters`;if(t.startsWith("-"))return`Invalid ${n} "${t}": must not start with "-"`;if(i.test(t))return`Invalid ${n}: must not contain whitespace or control characters`}function s(t,n="git ref"){let r=e(t,n);if(r)throw new Error(r)}export{e as 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 u}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.9");process.exit(0)}
|
|
2
|
+
import{b as u}from"./chunk-HZ5NC6U5.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
|
|
@@ -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{g,n as f}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.9");process.exit(0)}
|
|
2
|
+
import{g,n as f}from"./chunk-XYCKHYBM.js";import{a as l,d as c,e as k}from"./chunk-OG2UI6A3.js";import{b as C}from"./chunk-HZ5NC6U5.js";import{randomUUID as T}from"crypto";function b(s){let t=Object.hasOwn(h,s)?h[s]:void 0;if(t)return{input:t.input,output:t.output};let e=g(s);if(e.inputCostPerMillion>0||e.outputCostPerMillion>0)return{input:e.inputCostPerMillion,output:e.outputCostPerMillion}}function w(){return d||(d=new m),d}function x(){d&&(d.dispose(),d=void 0)}var h,m,d,R=C(()=>{f();k();h={"claude-sonnet-5":{input:2,output:10,provider:"claude"},"claude-opus-5":{input:5,output:25,provider:"claude"},"claude-opus-5-5":{input:4,output:20,provider:"claude"},"claude-fable-5-1":{input:10,output:50,provider:"claude"},"claude-fable-5":{input:10,output:50,provider:"claude"},"claude-opus-4-8":{input:5,output:25,provider:"claude"},"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"claude-haiku-4-5":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:5,output:25,provider:"claude"},"claude-opus-4-6":{input:5,output:25,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-6-astra":{input:10,output:50,provider:"openai"},"gpt-6-sol":{input:2,output:10,provider:"openai"},"gpt-6-luna":{input:.1,output:.5,provider:"openai"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-sonnet-5":{input:2,output:10,provider:"openrouter"},"anthropic/claude-opus-5":{input:5,output:25,provider:"openrouter"},"anthropic/claude-opus-5.5":{input:4,output:20,provider:"openrouter"},"anthropic/claude-haiku-4.5":{input:1,output:5,provider:"openrouter"},"openai/gpt-6-sol":{input:2,output:10,provider:"openrouter"},"openai/gpt-6-luna":{input:.1,output:.5,provider:"openrouter"},"google/gemini-3.8-flash":{input:.75,output:3.75,provider:"openrouter"},"meta-llama/llama-4-maverick":{input:.1875,output:.6525,provider:"openrouter"},"openai/gpt-oss-120b":{input:.15,output:.6,provider:"openrouter"},"qwen/qwen3-coder":{input:.3,output:1,provider:"openrouter"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-3.8-flash":{input:.75,output:3.75,provider:"gemini"},"gemini-3.5-flash":{input:1.5,output:9,provider:"gemini"},"gemini-3.1-pro-preview":{input:2,output:12,provider:"gemini"},"gemini-2.5-flash":{input:.3,output:2.5,provider:"gemini"},"gemini-2.5-pro":{input:1.25,output:10,provider:"gemini"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}};m=class s{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,e){let o=b(t);if(!o)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=e.promptTokens/1e6*o.input+(e.cacheReadTokens??0)/1e6*o.input*.1+(e.cacheCreationTokens??0)/1e6*o.input*1.25,r=e.completionTokens/1e6*o.output;return{inputCost:i,outputCost:r,totalCost:i+r,currency:"USD"}}static getCostPerToken(t){let e=b(t);return e?{input:e.input/1e6,output:e.output/1e6}:{input:0,output:0}}recordUsage(t,e,o,i,r){let p=s.calculateCost(e,o),n={timestamp:new Date,provider:t,model:e,usage:o,cost:p,requestId:i,metadata:r};return this.records.push(n),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),p}getSummary(t){let e=new Date,o=this.getPeriodStart(e,t),i=e,r=this.records.filter(a=>a.timestamp>=o&&a.timestamp<=i),p={claude:0,"claude-code":0,codex:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0,cognitum:0},n=l(),u=0,v=0;for(let a of r)u+=a.cost.totalCost,v+=a.usage.totalTokens,c(p,a.provider,a.cost.totalCost),c(n,a.model,a.cost.totalCost);return{period:t,periodStart:o,periodEnd:i,totalCost:u,byProvider:p,byModel:n,totalTokens:v,totalRequests:r.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,e="all"){let o=this.getPeriodStart(new Date,e),i=this.records.filter(u=>u.provider===t&&u.timestamp>=o),r=l(),p=0,n=0;for(let u of i)p+=u.cost.totalCost,n+=u.usage.totalTokens,r[u.model]||(r[u.model]={cost:0,tokens:0,requests:0}),r[u.model].cost+=u.cost.totalCost,r[u.model].tokens+=u.usage.totalTokens,r[u.model].requests+=1;return{totalCost:p,totalTokens:n,totalRequests:i.length,models:r}}addAlert(t,e,o){let i=`alert-${Date.now()}-${T().slice(0,12)}`;return this.alerts.push({threshold:t,period:e,onThreshold:o,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let e of t)e.timestamp=new Date(e.timestamp),this.records.push(e);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,e,o){return s.calculateCost(t,{promptTokens:e,completionTokens:o,totalTokens:e+o})}wouldExceedLimit(t,e,o,i,r){let p=this.getCurrentCost(r),n=this.estimateCost(t,e,o);return p+n.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,e){let o=new Date(t);switch(e){case"minute":o.setSeconds(0,0),o.setMinutes(o.getMinutes()-1);break;case"hour":o.setMinutes(0,0,0),o.setHours(o.getHours()-1);break;case"day":o.setHours(0,0,0,0);break;case"week":o.setHours(0,0,0,0),o.setDate(o.getDate()-7);break;case"month":o.setHours(0,0,0,0),o.setDate(1);break;case"all":return new Date(0)}return o}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let e=this.getSummary(t.period);if(e.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(e)}catch(o){console.error("Cost alert callback error:",o)}}}}}});export{h as a,b,m as c,w as d,x as e,R 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 y}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
|
|
2
|
+
import{a as y}from"./chunk-JUVHZG7I.js";import{a as g,c as h}from"./chunk-XWIUFYM3.js";import{S as b,b as p}from"./chunk-2I2UPJS7.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a 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.9");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-ABFDB4X3.js";import{a as w}from"./chunk-47V7FQGX.js";import{d as k,f as q}from"./chunk-HGTWAZWU.js";import{o as M,s as U}from"./chunk-OCESWNAZ.js";import{b as f,d as P}from"./chunk-PVIA2FPD.js";import{a as g,e as F}from"./chunk-N3KEY4XJ.js";import{a as R}from"./chunk-HZ5NC6U5.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
|
|
3
3
|
SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
|
|
4
4
|
`).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
|
|
5
5
|
INSERT OR REPLACE INTO routing_outcomes (
|
|
@@ -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.9");process.exit(0)}
|
|
2
2
|
var h=Object.create;var f=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var n=(a,b,c)=>()=>{if(c)throw c[0];try{return a&&(b=a(a=0)),b}catch(d){throw c=[d],d}};var o=(a,b)=>()=>{try{return b||a((b={exports:{}}).exports,b),b.exports}catch(c){throw b=0,c}},p=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,d)=>{if(b&&typeof b=="object"||typeof b=="function")for(let e of j(b))!l.call(a,e)&&e!==c&&f(a,e,{get:()=>b[e],enumerable:!(d=i(b,e))||d.enumerable});return a};var q=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c,a)),r=a=>g(f({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r 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 l}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.9");process.exit(0)}
|
|
2
|
+
import{a as l}from"./chunk-37BIGMJI.js";import{i as a}from"./chunk-FV7VAG74.js";import{a as m}from"./chunk-JNNZK7KH.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y 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 t}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.9");process.exit(0)}
|
|
2
|
+
import{b as t}from"./chunk-HZ5NC6U5.js";function o(e){try{return e.prepare(`
|
|
3
3
|
SELECT COUNT(*) as count FROM sqlite_master
|
|
4
4
|
WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
|
|
5
5
|
`).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
|