agentic-qe 3.15.9 → 3.15.10
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 +251 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/adapters/a2ui/catalog/component-schemas.js +2 -1
- package/dist/adapters/a2ui/data/json-pointer-resolver.js +10 -5
- package/dist/adapters/a2ui/integration/agui-sync.js +10 -6
- package/dist/adapters/a2ui/integration/surface-state-bridge.js +9 -5
- package/dist/adapters/ag-ui/json-patch.js +10 -6
- package/dist/audit/witness-chain.d.ts +1 -1
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-TR5SLAZC.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-H7ANGXW4.js +2 -0
- package/dist/cli/chunks/{agent-handler-RIYHTHVZ.js → agent-handler-SVXSHEET.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-WSUCUHOO.js → agent-memory-branch-WKQH36XL.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-DXWKCHY2.js +2 -0
- package/dist/cli/chunks/{arena-KRIBMIXX.js → arena-EKOOFVST.js} +2 -2
- package/dist/cli/chunks/{arena-YAJZX6MC.js → arena-OPS36NFZ.js} +4 -4
- package/dist/cli/chunks/{audit-7ZNOXWP3.js → audit-AO5NDZRI.js} +3 -3
- package/dist/cli/chunks/base-GTB6POYE.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-ZQAT4I6H.js → better-sqlite3-TFLVEMMY.js} +2 -2
- package/dist/cli/chunks/{brain-handler-452WCPZC.js → brain-handler-ADBBJPYW.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-IJFXJRPN.js → branch-enumerator-HGHUYYL5.js} +2 -2
- package/dist/cli/chunks/browser-5LU6P4SZ.js +4 -0
- package/dist/cli/chunks/browser-workflow-MSBOLYUY.js +2 -0
- package/dist/cli/chunks/{chunk-UOJBR4J3.js → chunk-2SXBBUM6.js} +2 -2
- package/dist/cli/chunks/{chunk-7JKB3Q7O.js → chunk-2T7RRL6G.js} +1 -1
- package/dist/cli/chunks/{chunk-HCYQHWI2.js → chunk-2XGVTYVX.js} +2 -2
- package/dist/cli/chunks/{chunk-3LYU7BLY.js → chunk-2ZI5FKSF.js} +2 -2
- package/dist/cli/chunks/chunk-2ZMF4NCF.js +4 -0
- package/dist/cli/chunks/{chunk-F3PQZX44.js → chunk-37OWRCUN.js} +1 -1
- package/dist/cli/chunks/{chunk-YRBBBUJX.js → chunk-3P34JFQH.js} +4 -4
- package/dist/cli/chunks/{chunk-ICP2ORGI.js → chunk-3Y7SPD72.js} +2 -2
- package/dist/cli/chunks/{chunk-WGDR2KIR.js → chunk-4G63WT4F.js} +2 -2
- package/dist/cli/chunks/chunk-4SJYIX54.js +3 -0
- package/dist/cli/chunks/chunk-5E6GHSTY.js +3 -0
- package/dist/cli/chunks/{chunk-OXTFSIGN.js → chunk-5LPYV3TK.js} +1 -1
- package/dist/cli/chunks/{chunk-XWIUFYM3.js → chunk-62OAY5KJ.js} +1 -1
- package/dist/cli/chunks/{chunk-VCMINU7K.js → chunk-6C3II5OM.js} +2 -2
- package/dist/cli/chunks/{chunk-EFBLP43U.js → chunk-6GP6W46M.js} +2 -2
- package/dist/cli/chunks/{chunk-4JCY45KV.js → chunk-6KIL6CMD.js} +2 -2
- package/dist/cli/chunks/{chunk-CTZJUV5I.js → chunk-6MVVSSID.js} +1 -1
- package/dist/cli/chunks/{chunk-JEP4ULR6.js → chunk-6P7424AO.js} +2 -2
- package/dist/cli/chunks/{chunk-SVHUYVUR.js → chunk-6PX4OXQO.js} +2 -2
- package/dist/cli/chunks/{chunk-LEAKYZ37.js → chunk-6S3WJGUV.js} +2 -2
- package/dist/cli/chunks/{chunk-7X2Y727E.js → chunk-6TB6YOCZ.js} +1 -1
- package/dist/cli/chunks/{chunk-VU2EL424.js → chunk-6X5DHU6Q.js} +1 -1
- package/dist/cli/chunks/{chunk-DDPPSSHW.js → chunk-6XCMKIZN.js} +1 -1
- package/dist/cli/chunks/{chunk-ZANDSVCK.js → chunk-7LFZ4CHM.js} +2 -2
- package/dist/cli/chunks/{chunk-UYLYMWV5.js → chunk-7OZVZIBE.js} +2 -2
- package/dist/cli/chunks/{chunk-32UTLDNY.js → chunk-7PJIR4ST.js} +2 -2
- package/dist/cli/chunks/{chunk-DINZR5CF.js → chunk-7TB6FK4B.js} +1 -1
- package/dist/cli/chunks/{chunk-KVBEGOJE.js → chunk-7ZCDZHDB.js} +2 -2
- package/dist/cli/chunks/{chunk-55HRSNGN.js → chunk-A55QKKT2.js} +2 -2
- package/dist/cli/chunks/{chunk-LCJTEUDC.js → chunk-ABFFWZPC.js} +428 -433
- package/dist/cli/chunks/{chunk-PVIA2FPD.js → chunk-ACWFKES2.js} +2 -2
- package/dist/cli/chunks/{chunk-2BA45H64.js → chunk-AH3ZD3NJ.js} +2 -2
- package/dist/cli/chunks/{chunk-OG2UI6A3.js → chunk-AI4VYSFS.js} +2 -2
- package/dist/cli/chunks/chunk-APSRPR4W.js +2 -0
- package/dist/cli/chunks/chunk-ATHWDAXB.js +3 -0
- package/dist/cli/chunks/{chunk-TSYQDRNK.js → chunk-B6LTH6YV.js} +2 -2
- package/dist/cli/chunks/chunk-BQUAE3CP.js +3 -0
- package/dist/cli/chunks/{chunk-OCESWNAZ.js → chunk-C522H7XR.js} +54 -33
- package/dist/cli/chunks/{chunk-TUYJ53V4.js → chunk-CESIR27V.js} +2 -2
- package/dist/cli/chunks/{chunk-PBZI2ZPV.js → chunk-CFBEBXLO.js} +3 -3
- package/dist/cli/chunks/{chunk-FJ4VTLLK.js → chunk-CMBLM26R.js} +2 -2
- package/dist/cli/chunks/{chunk-YZYDTABJ.js → chunk-CZ2IF6MC.js} +1 -1
- package/dist/cli/chunks/{chunk-GKPQ2GRR.js → chunk-CZGOSJQ4.js} +2 -2
- package/dist/cli/chunks/{chunk-FL3OYGCS.js → chunk-D6DA2KFD.js} +2 -2
- package/dist/cli/chunks/{chunk-37BIGMJI.js → chunk-DBMNJSBV.js} +1 -1
- package/dist/cli/chunks/{chunk-BHKXMIWX.js → chunk-DE4YJQJF.js} +2 -2
- package/dist/cli/chunks/{chunk-3CJCROMW.js → chunk-DEF34AFL.js} +2 -2
- package/dist/cli/chunks/chunk-DKAC3E3B.js +3 -0
- package/dist/cli/chunks/{chunk-AOFO4N32.js → chunk-DMFTELBS.js} +2 -2
- package/dist/cli/chunks/{chunk-KLGYIEJK.js → chunk-DNRWGATA.js} +10 -10
- package/dist/cli/chunks/{chunk-JWGRWMZP.js → chunk-DT7SIJOA.js} +2 -2
- package/dist/cli/chunks/{chunk-6PXA2BQJ.js → chunk-DURHK377.js} +67 -67
- package/dist/cli/chunks/{chunk-HAROIAJE.js → chunk-EAU5KDFO.js} +1 -1
- package/dist/cli/chunks/{chunk-L42JPFCC.js → chunk-EDLFX4ZB.js} +2 -2
- package/dist/cli/chunks/{chunk-6OOYIO3W.js → chunk-EN2QSKFF.js} +2 -2
- package/dist/cli/chunks/{chunk-UNUTC6TX.js → chunk-ERQKYIP7.js} +2 -2
- package/dist/cli/chunks/{chunk-KFUUIAR4.js → chunk-ESUO3GTJ.js} +2 -2
- package/dist/cli/chunks/{chunk-4V27J6YN.js → chunk-EWFECZ2U.js} +2 -2
- package/dist/cli/chunks/{chunk-4W4DYVSH.js → chunk-FAUCT5KR.js} +3 -3
- package/dist/cli/chunks/{chunk-IFEIY3NQ.js → chunk-FB6TI3BH.js} +2 -2
- package/dist/cli/chunks/{chunk-2TDIS6YK.js → chunk-FBXTQNRH.js} +2 -2
- package/dist/cli/chunks/{chunk-XOLDMK23.js → chunk-FESZBPUB.js} +2 -2
- package/dist/cli/chunks/chunk-FFTPAWM6.js +141 -0
- package/dist/cli/chunks/{chunk-A6YIH4C4.js → chunk-FKL3R5JQ.js} +2 -2
- package/dist/cli/chunks/{chunk-N5PDFGCQ.js → chunk-FPUDRSFJ.js} +2 -2
- package/dist/cli/chunks/{chunk-7QGYJ5OY.js → chunk-FZOWULMH.js} +1 -1
- package/dist/cli/chunks/{chunk-AVB5QY2Q.js → chunk-G3CZCUPM.js} +2 -2
- package/dist/cli/chunks/{chunk-FV3NHVC7.js → chunk-G5I6KGMW.js} +3 -3
- package/dist/cli/chunks/{chunk-N3KEY4XJ.js → chunk-GHBNRMSJ.js} +2 -2
- package/dist/cli/chunks/{chunk-2YH62JCN.js → chunk-GJHWY3ZX.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXBCCO2H.js → chunk-GJMLK5UT.js} +2 -2
- package/dist/cli/chunks/{chunk-NHZIWIQZ.js → chunk-GRCIBCJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-J3DTDJDT.js → chunk-GWZZ7DAO.js} +2 -2
- package/dist/cli/chunks/{chunk-4SUOVLJ6.js → chunk-GZLZCZ42.js} +2 -2
- package/dist/cli/chunks/{chunk-MZS32SYS.js → chunk-H2PYU7MN.js} +1 -1
- package/dist/cli/chunks/{chunk-ABFDB4X3.js → chunk-H32EPIR2.js} +1 -1
- package/dist/cli/chunks/{chunk-KIXYKUCI.js → chunk-H74Q7TJN.js} +1 -1
- package/dist/cli/chunks/chunk-HOZUDE4C.js +2 -0
- package/dist/cli/chunks/{chunk-PMCRCEW5.js → chunk-I33O4BRQ.js} +2 -2
- package/dist/cli/chunks/{chunk-N3NP6PTT.js → chunk-IKISCIGH.js} +2 -2
- package/dist/cli/chunks/{chunk-Q3JVJRVJ.js → chunk-IPJ7Q3AJ.js} +1 -1
- package/dist/cli/chunks/{chunk-WRRCQ2UE.js → chunk-IU2IV4NE.js} +1 -1
- package/dist/cli/chunks/{chunk-QQ5SZH4D.js → chunk-JHIY4VCC.js} +2 -2
- package/dist/cli/chunks/{chunk-W32YU3VI.js → chunk-KG336OV3.js} +2 -2
- package/dist/cli/chunks/{chunk-W5VJRDDG.js → chunk-KI73QCR5.js} +2 -2
- package/dist/cli/chunks/{chunk-HGTWAZWU.js → chunk-KNQ2ERFX.js} +2 -2
- package/dist/cli/chunks/{chunk-SNBYYO6F.js → chunk-KOBVYY6H.js} +2 -2
- package/dist/cli/chunks/{chunk-VQHVHVSF.js → chunk-KSIWGGJI.js} +8 -8
- package/dist/cli/chunks/{chunk-REUFWGMA.js → chunk-LMS3Y7JD.js} +2 -2
- package/dist/cli/chunks/{chunk-LMU5DUDK.js → chunk-LQEURY7C.js} +1 -1
- package/dist/cli/chunks/{chunk-AJ4YDSOI.js → chunk-LRZY4KS2.js} +2 -2
- package/dist/cli/chunks/{chunk-KIKWJM6J.js → chunk-M2QV7PT7.js} +2 -2
- package/dist/cli/chunks/{chunk-TNMQVG4A.js → chunk-MA7JIQ6U.js} +2 -2
- package/dist/cli/chunks/{chunk-I6S35FRO.js → chunk-MG27QY4D.js} +2 -2
- package/dist/cli/chunks/chunk-MNN5J4GU.js +12 -0
- package/dist/cli/chunks/chunk-N6PIIK6G.js +3 -0
- package/dist/cli/chunks/chunk-NAXGWDVM.js +12 -0
- package/dist/cli/chunks/{chunk-XOVNZT7F.js → chunk-NGKNYIQZ.js} +1 -1
- package/dist/cli/chunks/chunk-NNFZUTDH.js +2 -0
- package/dist/cli/chunks/{chunk-ZVSLCEVC.js → chunk-NPPHWFA2.js} +3 -3
- package/dist/cli/chunks/{chunk-JNNZK7KH.js → chunk-NSHU347M.js} +1 -1
- package/dist/cli/chunks/{chunk-PX2B5TS2.js → chunk-NVYIZCSR.js} +2 -2
- package/dist/cli/chunks/{chunk-5NS3USRW.js → chunk-NW5JUCCG.js} +1 -1
- package/dist/cli/chunks/{chunk-KR3M44CF.js → chunk-NZYLNXT6.js} +3 -3
- package/dist/cli/chunks/{chunk-5D2I7JUP.js → chunk-OBAREPDC.js} +2 -2
- package/dist/cli/chunks/{chunk-F4JYIRW2.js → chunk-ODJNUMV3.js} +2 -2
- package/dist/cli/chunks/{chunk-K5DJXMAA.js → chunk-OEKP73MC.js} +2 -2
- package/dist/cli/chunks/{chunk-2URBI52G.js → chunk-OPFGRS5S.js} +2 -2
- package/dist/cli/chunks/{chunk-HZ5NC6U5.js → chunk-OY2AHLSF.js} +1 -1
- package/dist/cli/chunks/{chunk-GII5WVAK.js → chunk-OY3NJNP2.js} +1 -1
- package/dist/cli/chunks/{chunk-P73W2K7T.js → chunk-PCEW6Q2C.js} +1 -1
- package/dist/cli/chunks/{chunk-7QTB5VJZ.js → chunk-PFG6VQ5Z.js} +2 -2
- package/dist/cli/chunks/{chunk-7KII4CQG.js → chunk-PGYMKGOE.js} +2 -2
- package/dist/cli/chunks/{chunk-BXO536GT.js → chunk-PPSAMXYN.js} +3 -3
- package/dist/cli/chunks/chunk-RK73HB2F.js +2 -0
- package/dist/cli/chunks/{chunk-ZBDRLF43.js → chunk-RPHY2DU6.js} +2 -2
- package/dist/cli/chunks/{chunk-XDBD4GXO.js → chunk-RWWOHCMG.js} +25 -20
- package/dist/cli/chunks/{chunk-J5KNRVXR.js → chunk-S75EYIJG.js} +1 -1
- package/dist/cli/chunks/{chunk-ETG7O5E5.js → chunk-SKQUUE4F.js} +5 -5
- package/dist/cli/chunks/chunk-SO45NA4D.js +180 -0
- package/dist/cli/chunks/{chunk-47V7FQGX.js → chunk-SU5H66SD.js} +2 -2
- package/dist/cli/chunks/{chunk-NTAD5UX4.js → chunk-SY2IB442.js} +2 -2
- package/dist/cli/chunks/{chunk-D6XVGFTI.js → chunk-TBLI254A.js} +2 -2
- package/dist/cli/chunks/{chunk-47TYABPD.js → chunk-TNMBRDCA.js} +3 -3
- package/dist/cli/chunks/{chunk-P2CXVNKK.js → chunk-TYFZXDGZ.js} +2 -2
- package/dist/cli/chunks/{chunk-2XITOPYV.js → chunk-U4OICXV2.js} +2 -2
- package/dist/cli/chunks/{chunk-JAV5WPSY.js → chunk-U53ZB4IX.js} +2 -2
- package/dist/cli/chunks/chunk-UARKIZAS.js +2 -0
- package/dist/cli/chunks/{chunk-2HL3UM5P.js → chunk-UCJMVXO4.js} +2 -2
- package/dist/cli/chunks/{chunk-HWK5L7IJ.js → chunk-UHTTW3IT.js} +2 -2
- package/dist/cli/chunks/{chunk-OXZLKP6C.js → chunk-V2M2XCR5.js} +1 -1
- package/dist/cli/chunks/{chunk-YZGSJG34.js → chunk-V2RSNVMW.js} +1 -1
- package/dist/cli/chunks/{chunk-5JWGCIQW.js → chunk-V6JBOIMX.js} +1 -1
- package/dist/cli/chunks/{chunk-JUVHZG7I.js → chunk-VFKF2XO7.js} +1 -1
- package/dist/cli/chunks/{chunk-XQ3DDY7X.js → chunk-VFSYMOAL.js} +2 -2
- package/dist/cli/chunks/{chunk-V5PXQSFS.js → chunk-VJQYDYAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-A4RU67VX.js → chunk-VKRTTFB6.js} +2 -2
- package/dist/cli/chunks/{chunk-H3KBIWTO.js → chunk-VWNFAW2M.js} +2 -2
- package/dist/cli/chunks/{chunk-72AMFDC7.js → chunk-WBM6N6IM.js} +1 -1
- package/dist/cli/chunks/{chunk-XUIA5KMS.js → chunk-WDQ7IEZY.js} +2 -2
- package/dist/cli/chunks/{chunk-FLASM2XB.js → chunk-WDVRE6GN.js} +2 -2
- package/dist/cli/chunks/{chunk-FV7VAG74.js → chunk-WQ4PYWSW.js} +1 -1
- package/dist/cli/chunks/{chunk-DGTLJNJH.js → chunk-WSF24I3D.js} +2 -2
- package/dist/cli/chunks/{chunk-6YL6JOQB.js → chunk-XBVUVFJK.js} +2 -2
- package/dist/cli/chunks/{chunk-VRGCKBF7.js → chunk-XEB3NLJR.js} +2 -2
- package/dist/cli/chunks/{chunk-XYCKHYBM.js → chunk-XFVTGAAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-2I2UPJS7.js → chunk-XLZYRTNO.js} +2 -2
- package/dist/cli/chunks/{chunk-AR2E4B7K.js → chunk-XUZDBQ5X.js} +5 -5
- package/dist/cli/chunks/{chunk-AQTVVLNP.js → chunk-Y76IAYQD.js} +1 -1
- package/dist/cli/chunks/{chunk-UOWHE77F.js → chunk-YAKGBHO4.js} +2 -2
- package/dist/cli/chunks/{chunk-JK2ME6IT.js → chunk-YBSBABOS.js} +2 -2
- package/dist/cli/chunks/{chunk-NDKLQW6N.js → chunk-YCGP5VFP.js} +2 -2
- package/dist/cli/chunks/{chunk-GBUIG3FS.js → chunk-YDAQK5UF.js} +1 -1
- package/dist/cli/chunks/{chunk-HTZJSQ3C.js → chunk-YK3BVZY6.js} +2 -2
- package/dist/cli/chunks/{chunk-GCWSX2NY.js → chunk-YK7JN5N7.js} +4 -4
- package/dist/cli/chunks/{chunk-C6RTMTEH.js → chunk-YKMU4LBV.js} +1 -1
- package/dist/cli/chunks/{chunk-JP4P3P3D.js → chunk-YYTGXD3R.js} +2 -2
- package/dist/cli/chunks/{chunk-763SUL4B.js → chunk-Z2O2YJAF.js} +2 -2
- package/dist/cli/chunks/{chunk-QTVWUQTB.js → chunk-Z7IYW5U7.js} +1 -1
- package/dist/cli/chunks/{chunk-XZJ2O3VC.js → chunk-ZG5666GJ.js} +1 -1
- package/dist/cli/chunks/{chunk-6EPHNJTL.js → chunk-ZXPY654C.js} +1 -1
- package/dist/cli/chunks/{ci-7SGRCFPS.js → ci-MSKMVH5X.js} +2 -2
- package/dist/cli/chunks/{ci-config-MX3URPZA.js → ci-config-7ODMNAUM.js} +2 -2
- package/dist/cli/chunks/{ci-output-M47NJY6D.js → ci-output-FXZ7ZZW3.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-5GAK45SW.js → circuit-breaker-4VOUEPOX.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-YXYSRH4Y.js → claude-flow-setup-7D4SGLM4.js} +2 -2
- package/dist/cli/chunks/client-POSVREVS.js +2 -0
- package/dist/cli/chunks/{cline-installer-DLJ5QD5N.js → cline-installer-WRRT7BGQ.js} +2 -2
- package/dist/cli/chunks/{code-ONKLMVQ2.js → code-ZDJRIL3S.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-2232LGZN.js → code-index-extractor-4S4SHM56.js} +2 -2
- package/dist/cli/chunks/{codex-installer-UOWLYCMH.js → codex-installer-YTRHNDWR.js} +2 -2
- package/dist/cli/chunks/{completions-MHX7GCC7.js → completions-6N64JUXJ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-43ZUJKZU.js → complexity-analyzer-I4A26VCJ.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-6Q5JR4FF.js → continuedev-installer-IIDR66LB.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-CZUMVHSI.js → copilot-installer-SVVFY3S2.js} +2 -2
- package/dist/cli/chunks/core-handlers-V243GY7X.js +2 -0
- package/dist/cli/chunks/{cost-tracker-VS5ZW3XN.js → cost-tracker-VGFS6IBX.js} +2 -2
- package/dist/cli/chunks/{coverage-VWKTWZ6D.js → coverage-B7MCGNTE.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-N3AIEM3B.js +2 -0
- package/dist/cli/chunks/{cursor-installer-YIFEMORH.js → cursor-installer-UPETT57E.js} +2 -2
- package/dist/cli/chunks/daemon-7BDJHEIJ.js +18 -0
- package/dist/cli/chunks/{daemon-SHWJSJW5.js → daemon-CQFNZLXU.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-TCC2WM46.js → dag-attention-scheduler-PJVABHON.js} +2 -2
- package/dist/cli/chunks/{detect-IGTWSQMA.js → detect-56SKAGWX.js} +2 -2
- package/dist/cli/chunks/{dist-node-TCOTJVQX.js → dist-node-UYTYUMLN.js} +2 -2
- package/dist/cli/chunks/{domain-handler-55ZVYODR.js → domain-handler-YOYLBYJE.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-GJRWOHQP.js → domain-plugins-7TARX2XF.js} +2 -2
- package/dist/cli/chunks/domain-transfer-AKVSBD6E.js +2 -0
- package/dist/cli/chunks/dream-UA7MKOPQ.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-XAMNIKQL.js → embed-and-insert-pattern-IS6HSR66.js} +2 -2
- package/dist/cli/chunks/{eval-GO22R4OZ.js → eval-GNB574IM.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-F2BRMJ3Y.js → experience-capture-middleware-RCAOCKM7.js} +3 -3
- package/dist/cli/chunks/{fast-paths-6RGPYALD.js → fast-paths-KTZ5SF54.js} +2 -2
- package/dist/cli/chunks/{feature-flags-ZGS3KLPH.js → feature-flags-ITX5LQ57.js} +2 -2
- package/dist/cli/chunks/{feature-flags-MIWQIOHU.js → feature-flags-KFHSR5YF.js} +2 -2
- package/dist/cli/chunks/file-discovery-YCMNKZAK.js +2 -0
- package/dist/cli/chunks/fleet-2Y3ZE6CE.js +46 -0
- package/dist/cli/chunks/{gnn-wrapper-ALBJVW6T.js → gnn-wrapper-RLFW3GSX.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ZMM53NDY.js → heartbeat-handler-EM2URCYZ.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-QH5V6G2P.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-OJNFAGJS.js +2 -0
- package/dist/cli/chunks/hnsw-index-DFUNARVD.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-RYUJPA7B.js → hnsw-legacy-bridge-JMHEOIBH.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-XM6XF3YV.js → hnswlib-node-CBP73QHY.js} +2 -2
- package/dist/cli/chunks/{hooks-X62O7TJO.js → hooks-IP7XE34Z.js} +34 -34
- package/dist/cli/chunks/hybrid-backend-SSGQQEQ2.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-ZBWUPTVD.js → hypergraph-engine-ONAYHU25.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-DUMF6SJV.js → hypergraph-handler-VINJRAID.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-CRGCA7ZD.js +2 -0
- package/dist/cli/chunks/{init-guard-S4I2R46S.js → init-guard-RYVV5R3Z.js} +2 -2
- package/dist/cli/chunks/{init-handler-L4KJHVWS.js → init-handler-MPRGWMOE.js} +6 -6
- package/dist/cli/chunks/init-wizard-NIMZ4J55.js +2 -0
- package/dist/cli/chunks/kernel-JQK7PRAI.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-GNNB5FCZ.js → kilocode-installer-OPD7JBRL.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-HR6ZAH7T.js → kiro-installer-M4OPUNK2.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-YPVVIKEU.js +2 -0
- package/dist/cli/chunks/{learning-4IEEOHJS.js → learning-4UWTQLMF.js} +24 -24
- package/dist/cli/chunks/{llm-router-ZFMORP36.js → llm-router-SQ56FF6Z.js} +4 -4
- package/dist/cli/chunks/llm-router-service-5OGAUOXF.js +2 -0
- package/dist/cli/chunks/{load-ZM43WGDO.js → load-HPHKDGGL.js} +2 -2
- package/dist/cli/chunks/load-test-UKNV5MWW.js +2 -0
- package/dist/cli/chunks/mcp-TELMAC7Z.js +2 -0
- package/dist/cli/chunks/{memory-W5FZGVAD.js → memory-PFQ3KPVJ.js} +5 -5
- package/dist/cli/chunks/memory-backend-ZW4BTRNK.js +2 -0
- package/dist/cli/chunks/memory-handlers-FCXN437E.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-SXXGAQ2G.js → multi-model-executor-3VDRX6TZ.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-PIRBUAB5.js → opencode-installer-PJ576R63.js} +2 -2
- package/dist/cli/chunks/{orchestrator-H5SQCQTB.js → orchestrator-72QP4UU7.js} +63 -19
- package/dist/cli/chunks/pattern-null-store-4DUV6MQC.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-XZTWDI2T.js → pattern-usage-recorder-754YQW7C.js} +2 -2
- package/dist/cli/chunks/pipeline-AVXY4MVB.js +19 -0
- package/dist/cli/chunks/{platform-KJDABL5C.js → platform-3E3DXLYB.js} +2 -2
- package/dist/cli/chunks/{plugin-V4KSBVVM.js → plugin-7FUQAKRE.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-JDHTKQAT.js → prime-radiant-advanced-wasm-NIB4F5NV.js} +2 -2
- package/dist/cli/chunks/project-root-JCAUNL6O.js +2 -0
- package/dist/cli/chunks/protocol-executor-RNZNZP3A.js +2 -0
- package/dist/cli/chunks/{protocol-handler-BNRONTQV.js → protocol-handler-BQRYMUTG.js} +2 -2
- package/dist/cli/chunks/{prove-ELLL6XMX.js → prove-H52QGC6B.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-WK6TQOG2.js +2 -0
- package/dist/cli/chunks/{quality-NH2QA4D4.js → quality-QO4XPAUM.js} +2 -2
- package/dist/cli/chunks/{quality-gate-JTKLF7GW.js → quality-gate-FBKE5E6F.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-4452SXZQ.js +2 -0
- package/dist/cli/chunks/{real-embeddings-J3KCKLPB.js → real-embeddings-RWGOVOXO.js} +2 -2
- package/dist/cli/chunks/{ref-validation-HNXQRP4F.js → ref-validation-LF76ZOBD.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-COJ6CX6S.js → roocode-installer-3BYEBTQ7.js} +2 -2
- package/dist/cli/chunks/router-3DIS5X4R.js +2 -0
- package/dist/cli/chunks/routing-feedback-OPXRCXM7.js +2 -0
- package/dist/cli/chunks/{routing-handler-WM33ZILE.js → routing-handler-DST7BVCU.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-BBLXEA7A.js → ruvector-commands-XE32PGKC.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-JL6T727I.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-V7IBDUCS.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-P7H6HCAG.js → rvf-migration-coordinator-VP32XC75.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-O3UQTEBK.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-R5SPVRFP.js → rvf-store-integrity-SH2AMVI7.js} +2 -2
- package/dist/cli/chunks/safe-db-EVB4ZC7T.js +2 -0
- package/dist/cli/chunks/schedule-ORDDXXY4.js +2 -0
- package/dist/cli/chunks/scheduler-XFLJSFIU.js +2 -0
- package/dist/cli/chunks/{security-AUDTRX3I.js → security-VSPNKCDS.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-PVDGBGI2.js → shared-rvf-adapter-HX6AHL3P.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-LZ2GMSS2.js → shared-rvf-dual-writer-MX4FC2JE.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-Y7B42CJ3.js +2 -0
- package/dist/cli/chunks/{standalone-memory-XNOAI4G4.js → standalone-memory-O4QUTK6L.js} +2 -2
- package/dist/cli/chunks/{status-handler-K72XZE4T.js → status-handler-Z2BP6EOG.js} +2 -2
- package/dist/cli/chunks/{structural-health-NF3YY7U5.js → structural-health-R36WNLQG.js} +2 -2
- package/dist/cli/chunks/sync-2ELWUFQU.js +2 -0
- package/dist/cli/chunks/{sync-VBD5Y3E2.js → sync-QF5Y3EMZ.js} +2 -2
- package/dist/cli/chunks/{task-handler-24S3WFVJ.js → task-handler-43PYE75J.js} +2 -2
- package/dist/cli/chunks/task-handlers-KPWAEMKH.js +9 -0
- package/dist/cli/chunks/{test-XFSGQELD.js → test-UWA377D4.js} +16 -16
- package/dist/cli/chunks/test-runner-process-3XZUYST2.js +2 -0
- package/dist/cli/chunks/{test-scheduling-VYUQ4CDE.js → test-scheduling-YQZPJRRN.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-F7C6UKTC.js +2 -0
- package/dist/cli/chunks/{token-usage-VLQ6WO2L.js → token-usage-DO6WLMXP.js} +2 -2
- package/dist/cli/chunks/{transformers-TOFMWWNM.js → transformers-H5RGFKVO.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-YTBCBHUO.js +2 -0
- package/dist/cli/chunks/{types-JTWLBAZJ.js → types-PJS2FGPF.js} +2 -2
- package/dist/cli/chunks/unified-memory-EHD4VNFW.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-ZODGM4UK.js +2 -0
- package/dist/cli/chunks/unified-persistence-MHSI7ABK.js +2 -0
- package/dist/cli/chunks/{upgrade-4ABM72T4.js → upgrade-4IC4F6AB.js} +2 -2
- package/dist/cli/chunks/{validate-UDJCWKXI.js → validate-DHUWW7PF.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-TODOUWNN.js → validate-swarm-OERQNOX5.js} +2 -2
- package/dist/cli/chunks/visual-security-54MLFKWY.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-WBMAJPM5.js → web-tree-sitter-TV7DMKES.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-BTT53TUL.js → windsurf-installer-QZPWSH37.js} +2 -2
- package/dist/cli/chunks/witness-chain-LC6Q2W27.js +2 -0
- package/dist/cli/chunks/witness-chain-QUIBAF3W.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-RUXIOE7F.js +2 -0
- package/dist/cli/chunks/{witness-chain-verifier-FRY3LMGH.js → witness-chain-verifier-YXENHB42.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-X7QHQQWL.js → witness-key-manager-HL26AGFO.js} +2 -2
- package/dist/cli/chunks/{workflow-QMZPAWQW.js → workflow-EOVVCN2E.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-UKHEJVSK.js +2 -0
- package/dist/cli/chunks/wrappers-AGODHBOO.js +2 -0
- package/dist/cli/commands/fleet.js +19 -12
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +9 -2
- package/dist/cli/commands/hooks-handlers/session-hooks.js +2 -2
- package/dist/cli/commands/hooks-handlers/stats-hooks.js +3 -2
- package/dist/cli/commands/learning.js +5 -3
- package/dist/cli/commands/ruvector-commands.js +2 -1
- package/dist/cli/commands/test.js +6 -0
- package/dist/cli/utils/ci-output.d.ts +9 -0
- package/dist/cli/utils/fleet-operation.d.ts +32 -0
- package/dist/cli/utils/fleet-operation.js +71 -0
- package/dist/cli/utils/fleet-result.d.ts +31 -0
- package/dist/cli/utils/fleet-result.js +124 -0
- package/dist/context/sources/git-source.js +6 -2
- package/dist/coordination/handlers/code-intelligence-handlers.js +60 -5
- package/dist/coordination/handlers/coverage-handlers.js +10 -1
- package/dist/coordination/handlers/requirements-handlers.js +16 -2
- package/dist/coordination/handlers/security-handlers.js +11 -1
- package/dist/coordination/handlers/test-execution-handlers.js +25 -7
- package/dist/coordination/mincut/queen-integration.d.ts +39 -1
- package/dist/coordination/mincut/queen-integration.js +83 -6
- package/dist/coordination/protocols/learning-consolidation-archive.d.ts +2 -6
- package/dist/coordination/protocols/learning-consolidation-archive.js +4 -27
- package/dist/coordination/protocols/learning-consolidation.d.ts +24 -0
- package/dist/coordination/protocols/learning-consolidation.js +71 -22
- package/dist/coordination/queen-coordinator.d.ts +1 -1
- package/dist/coordination/queen-coordinator.js +19 -7
- package/dist/coordination/queen-event-handlers.js +13 -0
- package/dist/coordination/queen-task-management.d.ts +18 -24
- package/dist/coordination/queen-task-management.js +62 -168
- package/dist/coordination/queen-task-queue.d.ts +41 -0
- package/dist/coordination/queen-task-queue.js +194 -0
- package/dist/coordination/queen-types.d.ts +1 -1
- package/dist/coordination/queen-work-stealing.d.ts +6 -1
- package/dist/coordination/queen-work-stealing.js +7 -4
- package/dist/coordination/result-saver-adapters.d.ts +15 -0
- package/dist/coordination/result-saver-adapters.js +57 -0
- package/dist/coordination/result-saver.d.ts +1 -1
- package/dist/coordination/result-saver.js +8 -5
- package/dist/coordination/yaml-pipeline-loader.js +5 -2
- package/dist/domains/code-intelligence/index-path-guard.d.ts +5 -2
- package/dist/domains/code-intelligence/index-path-guard.js +20 -50
- package/dist/domains/code-intelligence/plugin.js +5 -1
- package/dist/domains/code-intelligence/services/metric-collector/index.d.ts +2 -2
- package/dist/domains/code-intelligence/services/metric-collector/index.js +2 -3
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.d.ts +1 -1
- package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +11 -36
- package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
- package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +45 -103
- package/dist/domains/contract-testing/services/api-compatibility.js +7 -6
- package/dist/domains/contract-testing/services/contract-validator.js +6 -4
- package/dist/domains/contract-testing/services/schema-validator.js +8 -5
- package/dist/domains/defect-intelligence/interfaces.d.ts +2 -0
- package/dist/domains/defect-intelligence/plugin.js +11 -2
- package/dist/domains/defect-intelligence/prediction-history.d.ts +27 -0
- package/dist/domains/defect-intelligence/prediction-history.js +68 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +25 -10
- package/dist/domains/enterprise-integration/services/message-broker-service.js +3 -2
- package/dist/domains/enterprise-integration/services/odata-service.js +2 -1
- package/dist/domains/enterprise-integration/services/sap-integration-service.js +3 -2
- package/dist/domains/learning-optimization/active-patterns.d.ts +2 -2
- package/dist/domains/learning-optimization/active-patterns.js +2 -2
- package/dist/domains/learning-optimization/coordinator.js +9 -5
- package/dist/domains/learning-optimization/interfaces.d.ts +6 -2
- package/dist/domains/learning-optimization/pattern-archive.d.ts +31 -0
- package/dist/domains/learning-optimization/pattern-archive.js +56 -0
- package/dist/domains/learning-optimization/pattern-consolidation.d.ts +12 -0
- package/dist/domains/learning-optimization/pattern-consolidation.js +41 -0
- package/dist/domains/learning-optimization/reward-source.d.ts +13 -0
- package/dist/domains/learning-optimization/reward-source.js +8 -1
- package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +5 -3
- package/dist/domains/learning-optimization/services/learning-coordinator.js +45 -58
- package/dist/domains/security-compliance/plugin.js +17 -3
- package/dist/domains/security-compliance/sast-path-guard.d.ts +9 -0
- package/dist/domains/security-compliance/sast-path-guard.js +17 -0
- package/dist/domains/security-compliance/services/scanners/dast-auth-testing.js +46 -56
- package/dist/domains/security-compliance/services/scanners/dast-helpers.js +76 -91
- package/dist/domains/security-compliance/services/scanners/dast-injection-testing.js +52 -62
- package/dist/domains/security-compliance/services/scanners/dast-scanner.d.ts +21 -1
- package/dist/domains/security-compliance/services/scanners/dast-scanner.js +29 -24
- package/dist/domains/security-compliance/services/scanners/scanner-orchestrator.js +4 -1
- package/dist/domains/test-execution/coordinator.d.ts +5 -0
- package/dist/domains/test-execution/coordinator.js +35 -20
- package/dist/domains/test-execution/interfaces.d.ts +25 -0
- package/dist/domains/test-execution/plugin.js +19 -4
- package/dist/domains/test-execution/services/flaky-detector.js +9 -7
- package/dist/domains/test-execution/services/retry-handler.js +46 -7
- package/dist/domains/test-execution/services/runner-test-cases.d.ts +11 -0
- package/dist/domains/test-execution/services/runner-test-cases.js +20 -2
- package/dist/domains/test-execution/services/test-executor.js +8 -8
- package/dist/domains/test-generation/plugin.js +7 -2
- package/dist/domains/test-generation/services/test-data-generator.js +3 -1
- package/dist/domains/visual-accessibility/services/axe-core-audit.js +1 -1
- package/dist/hooks/cross-phase-hooks.js +2 -1
- package/dist/init/phases/10-workers.js +50 -6
- package/dist/integrations/browser/agent-browser/client.js +37 -52
- package/dist/integrations/browser/agent-browser/command-executor.d.ts +33 -27
- package/dist/integrations/browser/agent-browser/command-executor.js +53 -54
- package/dist/integrations/browser/agent-browser/session-manager.d.ts +1 -1
- package/dist/integrations/browser/agent-browser/session-manager.js +8 -9
- package/dist/integrations/browser/web-content-fetcher.js +9 -3
- package/dist/integrations/vibium/client.js +2 -2
- package/dist/integrations/vibium/runtime.d.ts +1 -1
- package/dist/integrations/vibium/runtime.js +14 -11
- package/dist/kernel/unified-memory-schemas.d.ts +3 -2
- package/dist/kernel/unified-memory-schemas.js +3 -2
- package/dist/kernel/unified-memory.js +25 -6
- package/dist/learning/dream/dream-commit.d.ts +65 -0
- package/dist/learning/dream/dream-commit.js +104 -0
- package/dist/learning/dream/dream-engine.d.ts +81 -31
- package/dist/learning/dream/dream-engine.js +225 -168
- package/dist/learning/dream/dream-insights-pruner.d.ts +9 -3
- package/dist/learning/dream/dream-insights-pruner.js +16 -30
- package/dist/learning/dream/index.d.ts +3 -2
- package/dist/learning/dream/index.js +3 -1
- package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -1
- package/dist/learning/dream/rvcow-branch-manager.js +8 -1
- package/dist/learning/dream/speculative-dreamer.d.ts +50 -74
- package/dist/learning/dream/speculative-dreamer.js +64 -111
- package/dist/learning/dream/spreading-activation.d.ts +2 -1
- package/dist/learning/dream/spreading-activation.js +15 -6
- package/dist/learning/experience-capture.d.ts +9 -0
- package/dist/learning/experience-capture.js +18 -4
- package/dist/learning/qe-reasoning-bank-types.d.ts +17 -2
- package/dist/learning/qe-reasoning-bank.js +22 -11
- package/dist/learning/sqlite-persistence.d.ts +6 -0
- package/dist/learning/sqlite-persistence.js +16 -2
- package/dist/learning/usage-outcome.d.ts +68 -0
- package/dist/learning/usage-outcome.js +84 -0
- package/dist/mcp/background-workers.d.ts +13 -1
- package/dist/mcp/background-workers.js +17 -3
- package/dist/mcp/bundle.js +607 -580
- package/dist/mcp/handlers/core-handlers.js +11 -0
- package/dist/mcp/handlers/domain-handler-configs.d.ts +5 -0
- package/dist/mcp/handlers/domain-handler-configs.js +11 -3
- package/dist/mcp/handlers/handler-factory.d.ts +2 -1
- package/dist/mcp/handlers/handler-factory.js +36 -15
- package/dist/mcp/handlers/orchestrate-routes.d.ts +36 -0
- package/dist/mcp/handlers/orchestrate-routes.js +88 -0
- package/dist/mcp/handlers/task-handlers.d.ts +3 -0
- package/dist/mcp/handlers/task-handlers.js +35 -8
- package/dist/mcp/handlers/validation-pipeline-handler.js +6 -2
- package/dist/mcp/protocol-server.js +2 -0
- package/dist/mcp/security/schema-validator.js +3 -2
- package/dist/mcp/tools/code-intelligence/c4.js +11 -1
- package/dist/mcp/tools/coverage-analysis/index.js +31 -2
- package/dist/mcp/tools/learning-optimization/dream.d.ts +8 -8
- package/dist/mcp/tools/learning-optimization/dream.js +38 -34
- package/dist/mcp/tools/learning-optimization/optimize.d.ts +18 -2
- package/dist/mcp/tools/learning-optimization/optimize.js +58 -10
- package/dist/mcp/tools/quality-assessment/gate.js +12 -1
- package/dist/mcp/tools/requirements-validation/quality-criteria.js +9 -2
- package/dist/migration/agent-compat.js +7 -5
- package/dist/migrations/20261018_add_dream_insights_archive.d.ts +27 -0
- package/dist/migrations/20261018_add_dream_insights_archive.js +57 -0
- package/dist/shared/git/git-analyzer.d.ts +49 -0
- package/dist/shared/git/git-analyzer.js +159 -319
- package/dist/shared/git/git-process.d.ts +22 -0
- package/dist/shared/git/git-process.js +37 -0
- package/dist/shared/git/index.d.ts +1 -0
- package/dist/shared/git/index.js +1 -0
- package/dist/shared/io/payload-path-guard.d.ts +75 -0
- package/dist/shared/io/payload-path-guard.js +190 -0
- package/dist/shared/llm/router/agent-router-config.js +2 -1
- package/dist/shared/llm/translation/tool-translator.js +2 -1
- package/dist/shared/test-runner-args.d.ts +5 -0
- package/dist/shared/test-runner-args.js +6 -1
- package/dist/shared/test-runner-process.d.ts +6 -0
- package/dist/shared/test-runner-process.js +14 -0
- package/dist/shared/test-runner-verdict.d.ts +9 -1
- package/dist/shared/test-runner-verdict.js +15 -4
- package/dist/shared/utils/namespaced-search.d.ts +14 -0
- package/dist/shared/utils/namespaced-search.js +19 -1
- package/dist/shared/utils/safe-expression-evaluator.js +4 -3
- package/dist/strange-loop/infra-healing/recovery-playbook.js +13 -3
- package/dist/validation/gate-reexecute.js +7 -4
- package/dist/workers/daemon.js +13 -1
- package/dist/workers/quality-daemon/git-watcher.js +9 -9
- package/dist/workers/workers/defect-predictor.d.ts +8 -3
- package/dist/workers/workers/defect-predictor.js +48 -49
- package/dist/workers/workers/learning-consolidation.d.ts +2 -0
- package/dist/workers/workers/learning-consolidation.js +12 -1
- package/dist/workflows/browser/workflow-loader.js +8 -5
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-R2Q4QGXQ.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-427FRKWG.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-3RENLQWP.js +0 -2
- package/dist/cli/chunks/base-67DXSAYM.js +0 -2
- package/dist/cli/chunks/browser-CT3MTV6G.js +0 -4
- package/dist/cli/chunks/browser-workflow-NDXRROWZ.js +0 -2
- package/dist/cli/chunks/chunk-4URT6JO2.js +0 -2
- package/dist/cli/chunks/chunk-5LAAZLUC.js +0 -4
- package/dist/cli/chunks/chunk-7DMA5NYL.js +0 -4
- package/dist/cli/chunks/chunk-F2SQPP6U.js +0 -4
- package/dist/cli/chunks/chunk-G3BKZNFL.js +0 -120
- package/dist/cli/chunks/chunk-GR3JYE5A.js +0 -2
- package/dist/cli/chunks/chunk-J3WGK22W.js +0 -2
- package/dist/cli/chunks/chunk-KHSRIPBP.js +0 -180
- package/dist/cli/chunks/chunk-KTSLTZSG.js +0 -2
- package/dist/cli/chunks/chunk-O3JLOVZX.js +0 -4
- package/dist/cli/chunks/chunk-THAY7WHO.js +0 -12
- package/dist/cli/chunks/chunk-VXZJOKOX.js +0 -2
- package/dist/cli/chunks/chunk-VYLM2YV5.js +0 -12
- package/dist/cli/chunks/client-ZP3CTVRF.js +0 -2
- package/dist/cli/chunks/core-handlers-JSRXQWPE.js +0 -2
- package/dist/cli/chunks/cross-domain-router-7UKODQWG.js +0 -2
- package/dist/cli/chunks/daemon-YIFT46FH.js +0 -34
- package/dist/cli/chunks/domain-transfer-6EF75EKU.js +0 -2
- package/dist/cli/chunks/dream-UDLM6M55.js +0 -2
- package/dist/cli/chunks/file-discovery-THWOUQ7Z.js +0 -2
- package/dist/cli/chunks/fleet-ADL57COA.js +0 -44
- package/dist/cli/chunks/heartbeat-scheduler-HGOC5KH3.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-EPSA6AP7.js +0 -2
- package/dist/cli/chunks/hnsw-index-RMFOPYGY.js +0 -2
- package/dist/cli/chunks/hybrid-backend-NZ3G4WBX.js +0 -2
- package/dist/cli/chunks/impact-analyzer-WZC6NHFP.js +0 -2
- package/dist/cli/chunks/init-wizard-422UZYQ5.js +0 -2
- package/dist/cli/chunks/kernel-N7PJ6FCE.js +0 -2
- package/dist/cli/chunks/knowledge-graph-SZCVQF37.js +0 -2
- package/dist/cli/chunks/llm-router-service-4DE5WDUZ.js +0 -2
- package/dist/cli/chunks/load-test-POMIF4Q4.js +0 -2
- package/dist/cli/chunks/mcp-CRZKZE37.js +0 -2
- package/dist/cli/chunks/memory-backend-4P6AHSOY.js +0 -2
- package/dist/cli/chunks/memory-handlers-NK6NV3GE.js +0 -2
- package/dist/cli/chunks/pattern-null-store-CCHQHGQG.js +0 -2
- package/dist/cli/chunks/pipeline-5LMLBIJ7.js +0 -19
- package/dist/cli/chunks/project-root-X72FSM2F.js +0 -2
- package/dist/cli/chunks/protocol-executor-QW6XN6QN.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-ZD3WF647.js +0 -2
- package/dist/cli/chunks/queen-coordinator-S4U4MKK2.js +0 -2
- package/dist/cli/chunks/router-CXZKOOTR.js +0 -2
- package/dist/cli/chunks/routing-feedback-IYFANYY5.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-HCLQ5WUQ.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-XCLUWOO3.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-MRT5H3IP.js +0 -2
- package/dist/cli/chunks/safe-db-WFODRGVZ.js +0 -2
- package/dist/cli/chunks/schedule-RO55OQXG.js +0 -2
- package/dist/cli/chunks/scheduler-XXMJCH24.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-AWRIS4MK.js +0 -2
- package/dist/cli/chunks/sync-UVXA6CT2.js +0 -2
- package/dist/cli/chunks/task-handlers-GUYW2EPJ.js +0 -9
- package/dist/cli/chunks/token-bootstrap-EDK6FNQ3.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-MI3NZKUD.js +0 -2
- package/dist/cli/chunks/unified-memory-6JWHV6EF.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-4UANU6NU.js +0 -2
- package/dist/cli/chunks/unified-persistence-KGGNA46H.js +0 -2
- package/dist/cli/chunks/visual-security-6VZNQLH7.js +0 -2
- package/dist/cli/chunks/witness-chain-AKKHWEWU.js +0 -2
- package/dist/cli/chunks/witness-chain-TATPXQRK.js +0 -2
- package/dist/cli/chunks/witness-chain-repair-2HGJGE7O.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-4GAW7HNZ.js +0 -2
- package/dist/cli/chunks/wrappers-ZD5NBHYI.js +0 -2
|
@@ -0,0 +1,12 @@
|
|
|
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.10");process.exit(0)}
|
|
2
|
+
import{c as H,d as J}from"./chunk-2ZI5FKSF.js";import{h as G}from"./chunk-DNRWGATA.js";import{e as U}from"./chunk-H2PYU7MN.js";import{e as N}from"./chunk-YK7JN5N7.js";import{e as T}from"./chunk-37OWRCUN.js";import{b as v,c as C}from"./chunk-7OZVZIBE.js";import{b as B}from"./chunk-RWWOHCMG.js";import{b,d as _}from"./chunk-ACWFKES2.js";import{i as W}from"./chunk-WQ4PYWSW.js";import{c as k,d as E}from"./chunk-NSHU347M.js";import{a as oe}from"./chunk-HOZUDE4C.js";import{c as q}from"./chunk-ATHWDAXB.js";import{a as y,e as $}from"./chunk-GHBNRMSJ.js";import{S as se,b as z}from"./chunk-XLZYRTNO.js";import{randomUUID as te}from"crypto";$();_();import{randomUUID as ce}from"node:crypto";var D=C(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${ce()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",D,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let s=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",D,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),n!==void 0&&s.push("--quality",String(n)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",D,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-EHD4VNFW.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
|
|
3
|
+
INSERT OR REPLACE INTO qe_trajectories
|
|
4
|
+
(id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
|
|
5
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
+
`).run(e.id,e.task,e.agent||null,null,r,a,e.success?1:0,JSON.stringify(e.steps),e.feedback||null)}catch(t){console.debug("[TrajectoryBridge] Trajectory persistence failed:",t instanceof Error?t.message:t)}}};var V=C(),X={low:[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i],high:[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/database.*migration/i,/distributed/i,/concurrent/i]},R=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;routingHistory=[];async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async routeTask(e){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",V,"hooks","model-route","--task",e],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}),n=i.match(/model[:\s]+["']?(haiku|sonnet|opus)/i),r=i.match(/confidence[:\s]+([0-9.]+)/i),a=i.match(/reason(?:ing)?[:\s]+["']?([^"'\n]+)/i);if(n)return{model:n[1].toLowerCase(),confidence:r?parseFloat(r[1]):.7,reasoning:a?.[1]?.trim()}}catch(t){console.debug("[ModelRouterBridge] Claude Flow routing failed:",t instanceof Error?t.message:t)}return this.localRoute(e)}async recordOutcome(e){if(this.routingHistory.push(e),this.routingHistory.length>1e3&&(this.routingHistory=this.routingHistory.slice(-500)),this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process");t("npx",["--no-install",V,"hooks","model-outcome","--task",e.task,"--model",e.model,"--outcome",e.outcome],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch(t){console.debug("[ModelRouterBridge] Outcome recording failed:",t instanceof Error?t.message:t)}}getStats(){let e={totalRoutings:this.routingHistory.length,modelDistribution:{haiku:0,sonnet:0,opus:0},successRate:{haiku:0,sonnet:0,opus:0}},t={haiku:0,sonnet:0,opus:0};for(let i of this.routingHistory)e.modelDistribution[i.model]++,i.outcome==="success"&&t[i.model]++;for(let i of["haiku","sonnet","opus"]){let n=e.modelDistribution[i];e.successRate[i]=n>0?t[i]/n:0}return e}isClaudeFlowAvailable(){return this.claudeFlowAvailable}localRoute(e){let t=e.toLowerCase();for(let i of X.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of X.high)if(i.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task detected - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task description - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity task - using sonnet for balance"}}};_();$();var M=C(),S=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;analysisCache=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async analyze(e,t="medium"){let i=e||this.options.projectRoot,n=`${i}:${t}`,r=this.analysisCache.get(n);if(r)return r;if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=a("npx",["--no-install",M,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=b(s),d={success:!0,repositoryPath:i,depth:t,analysis:o.analysis||void 0,agentConfigs:o.agentConfigs};return this.analysisCache.set(n,d),d}catch{return{success:!0,repositoryPath:i,depth:t}}}catch(a){console.debug("[PretrainBridge] Claude Flow analyze failed, using local:",a instanceof Error?a.message:a)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",M,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return b(i)}catch(n){return console.debug("[PretrainBridge] Agent config parse error:",n instanceof Error?n.message:n),[]}}catch(t){console.debug("[PretrainBridge] Claude Flow generateAgentConfigs failed:",t instanceof Error?t.message:t)}return this.generateLocalAgentConfigs()}async transferPatterns(e,t=.7){if(this.claudeFlowAvailable)try{let{execFileSync:i}=await import("child_process"),n=i("npx",["--no-install",M,"hooks","transfer","--source-path",e,"--min-confidence",String(t)],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot}),r=n.match(/transferred[:\s]+(\d+)/i),a=n.match(/skipped[:\s]+(\d+)/i);return{transferred:r?parseInt(r[1]):0,skipped:a?parseInt(a[1]):0}}catch(i){console.debug("[PretrainBridge] Claude Flow transferPatterns failed:",i instanceof Error?i.message:i)}return{transferred:0,skipped:0}}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let p of d.slice(0,100))(p.endsWith(".ts")||p.endsWith(".tsx"))&&c.add("typescript"),(p.endsWith(".js")||p.endsWith(".jsx"))&&c.add("javascript"),p.endsWith(".py")&&c.add("python"),p.endsWith(".go")&&c.add("go"),p.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let p=b(r(w,"utf-8")),f={...p.dependencies,...p.devDependencies};f.react&&g.add("react"),f.vue&&g.add("vue"),f.angular&&g.add("angular"),f.vitest&&g.add("vitest"),f.jest&&g.add("jest"),f.playwright&&g.add("playwright"),f.express&&g.add("express"),f.fastify&&g.add("fastify")}catch(p){console.debug("[PretrainBridge] package.json parse error:",p instanceof Error?p.message:p)}let m={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,m),m}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}generateLocalAgentConfigs(){return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-quality-gate",type:"worker",capabilities:["quality-assessment","risk-scoring"],model:"sonnet"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}};var Q=class{constructor(e){this.options=e;this.trajectory=new P(e),this.modelRouter=new R(e),this.pretrain=new S(e)}options;trajectory;modelRouter;pretrain;initialized=!1;async initialize(){this.initialized||(await Promise.all([this.trajectory.initialize(),this.modelRouter.initialize(),this.pretrain.initialize()]),this.initialized=!0)}getStatus(){return{available:this.isAvailable(),features:{trajectories:this.trajectory.isClaudeFlowAvailable(),modelRouting:this.modelRouter.isClaudeFlowAvailable(),pretrain:this.pretrain.isClaudeFlowAvailable(),patternSearch:this.trajectory.isClaudeFlowAvailable()}}}isAvailable(){return this.trajectory.isClaudeFlowAvailable()||this.modelRouter.isClaudeFlowAvailable()||this.pretrain.isClaudeFlowAvailable()}};function K(u){return new Q(u)}import{createHash as le}from"node:crypto";oe();se();var F=q.create("experience-capture"),Z={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},ue=new Set(Object.keys(Z));function Y(u){return typeof u=="string"&&ue.has(u)}function de(u){if(Y(u))return Z[u]}var pe={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:T,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},L=class{constructor(e,t,i,n={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...pe,...n}}memory;patternStore;eventBus;config;initialized=!1;cleanupTimer;activeExperiences=new Map;stats={totalCaptured:0,successfulCaptures:0,patternsExtracted:0,patternsPromoted:0,byDomain:new Map};sessionCaptureCount=0;witnessChain;nullRecorder;setWitnessChain(e){this.witnessChain=e}setNullRecorder(e){this.nullRecorder=e}async initialize(){this.initialized||(await this.loadStats(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0,console.log("[ExperienceCapture] Initialized"))}startCapture(e,t){let i=`exp-${Date.now()}-${W().slice(0,8)}`,n={id:i,task:e,agent:t?.agent,domain:t?.domain,model:t?.model,startedAt:Date.now(),completedAt:0,durationMs:0,steps:[],success:!1,quality:0,trajectoryId:t?.trajectoryId,metadata:t?.metadata,appliedPatterns:t?.appliedPatterns};return this.activeExperiences.set(i,n),i}recordStep(e,t){let i=this.activeExperiences.get(e);if(!i){console.warn(`[ExperienceCapture] Experience not found: ${e}`);return}i.steps.push({...t,timestamp:Date.now()})}async completeCapture(e,t){let i=this.activeExperiences.get(e);if(!i)return E(new Error(`Experience not found: ${e}`));let n=Date.now();i.completedAt=n,i.durationMs=n-i.startedAt,i.success=t.success,i.feedback=t.feedback,t.outcomeBasis&&(i.outcomeBasis=t.outcomeBasis),t.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let r=t.testOutcome??i.metadata?.testOutcome;if(r&&Y(r)&&(i.testOutcome=r,i.reward=de(r)),this.witnessChain&&z().useWitnessChain)try{let o=this.witnessChain.appendWitness({type:"experience-capture",decision:i.success?"PASS":"FAIL",context:{experienceId:i.id,task:i.task,quality:i.quality,domain:i.domain,reward:i.reward},evidence:i.reward});i.witnessHash=o.hash}catch(o){F.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:o instanceof Error?o.message:String(o)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward!==void 0?i.reward<0:!i.success;if(this.nullRecorder&&a&&i.appliedPatterns?.length){let o=`${i.domain??"unknown"}:${i.agent??"unknown"}`;for(let d of i.appliedPatterns)try{this.nullRecorder({patternId:d,contextFingerprint:o,failureMode:i.testOutcome??i.feedback??"task-failure",trajectoryRef:i.trajectoryId,evidenceClass:"EXECUTED"})}catch(c){F.warn("Failed to record pattern null",{patternId:d,error:c instanceof Error?c.message:String(c)})}}let s=i.reward===void 0||i.reward>0;if(i.outcomeBasis!==void 0||i.success&&i.quality>=this.config.minQualityForPatternExtraction&&s){let o=await this.extractPattern(i);(o.newPattern||o.reinforced)&&(i.patterns=[o.patternId])}return this.emitExperienceCaptured(i),k(i)}getActiveExperience(e){return this.activeExperiences.get(e)}getPendingCount(){return this.activeExperiences.size}async flushPending(){let e=Array.from(this.activeExperiences.entries());if(e.length===0)return 0;let t=0;for(let[i,n]of e){let r=Date.now();n.completedAt=r,n.durationMs=r-n.startedAt,n.quality=n.quality||this.calculateQuality(n),n.metadata={...n.metadata,flushedByCompaction:!0},await this.storeExperience(n),this.updateStats(n),this.activeExperiences.delete(i),t++}return F.info(`Flushed ${t} pending experiences before compaction`),t}async getExperience(e){let t=`${this.config.namespace}:experience:${e}`;return await this.memory.get(t)??null}async searchExperiences(e={}){let t=e.limit||100,i=[],n;e.domain?n=await this.memory.search(`${this.config.namespace}:index:domain:${e.domain}:*`,t*2):n=await this.memory.search(`${this.config.namespace}:experience:*`,t*2);for(let r of n){if(i.length>=t)break;let a=r.includes(":index:")?await this.memory.get(r):null,s=a?await this.getExperience(a):await this.memory.get(r);s&&(e.agent&&s.agent!==e.agent||e.success!==void 0&&s.success!==e.success||e.minQuality!==void 0&&s.quality<e.minQuality||i.push(s))}return i}async getStats(){let e={};for(let[t,i]of this.stats.byDomain)e[t]=i;return{totalExperiences:this.stats.totalCaptured,byDomain:e,successRate:this.stats.totalCaptured>0?this.stats.successfulCaptures/this.stats.totalCaptured:0,avgQuality:await this.calculateAvgQuality(),patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted}}async extractPattern(e){if(!this.patternStore)return{newPattern:!1,reinforced:!1,promoted:!1};let t=this.experienceIdentity(e),i=await this.patternStore.search(t,{limit:1,domain:e.domain,patternType:this.detectPatternType(e.task),useVectorSearch:!1});if(i.success&&i.value.length>0){let a=i.value[0],s=a.pattern.context?.experienceOrigin;if(s?.task===e.task&&s.domain===(e.domain??null)&&s.patternType===this.detectPatternType(e.task)&&a.pattern.patternType===s.patternType&&(!e.domain||a.pattern.qeDomain===e.domain)){let o=await this.patternStore.recordUsage(a.pattern.id,e.success,this.usageOutcomeTag(e)),d=await this.patternStore.get(a.pattern.id),c=!1;return d&&e.success&&d.tier==="short-term"&&d.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(a.pattern.id)).success&&(c=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${a.pattern.id} (${d.usageCount} uses)`)),{newPattern:!1,patternId:a.pattern.id,reinforced:o.success,promoted:c}}}let n=this.experienceToPatternOptions(e),r=await this.patternStore.create(n);return r.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(r.value.id,e.success,this.usageOutcomeTag(e)),{newPattern:!0,patternId:r.value.id,reinforced:!1,promoted:!1}):{newPattern:!1,reinforced:!1,promoted:!1}}async shareAcrossDomains(e){if(!this.config.enableCrossDomainSharing||!e.domain)return;let t=this.getRelatedDomains(e.domain);for(let i of t){let n=`${this.config.namespace}:shared:${i}:${e.id}`;await this.memory.set(n,{sourceExperience:e.id,sourceDomain:e.domain,sharedAt:Date.now()},{persist:!0})}}async cleanup(){let t=0;for(let i of this.stats.byDomain.keys()){let n=this.stats.byDomain.get(i)||0;if(n>this.config.maxExperiencesPerDomain){let r=await this.searchExperiences({domain:i,limit:n});r.sort((s,o)=>s.quality-o.quality||s.startedAt-o.startedAt);let a=n-this.config.maxExperiencesPerDomain;for(let s=0;s<Math.min(a,r.length);s++){let o=r[s];await this.softDeleteExperience(o.id),t++}}}return console.log(`[ExperienceCapture] Cleanup: ${t} archived (0 destroyed)`),{removed:0,consolidated:0,archived:t}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),await this.saveStats(),this.sessionCaptureCount===0&&console.warn("[ExperienceCapture] WARNING: Zero experiences captured this session. Learning cannot improve without experience data. Ensure tasks call startCapture()/completeCapture() to feed the learning loop."),this.activeExperiences.clear(),this.initialized=!1}async storeExperience(e){let t=`${this.config.namespace}:experience:${e.id}`;if(await this.memory.set(t,e,{persist:!0}),e.domain){let i=`${this.config.namespace}:index:domain:${e.domain}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}if(e.agent){let i=`${this.config.namespace}:index:agent:${e.agent}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}}async deleteExperience(e){await this.softDeleteExperience(e)}async softDeleteExperience(e){let t=await this.getExperience(e);if(!t)return;let i=`${this.config.namespace}:experience:${e}`,n={...t,_archived:!0};await this.memory.set(i,n,{persist:!0})}calculateQuality(e){if(e.steps.length===0)return e.success?.5:.2;let t=e.steps.filter(n=>n.quality!==void 0);if(t.length===0)return e.success?.6:.3;let i=t.reduce((n,r)=>n+(r.quality||0),0)/t.length;return e.success?Math.min(1,i+.1):Math.max(0,i-.2)}updateStats(e){if(this.stats.totalCaptured++,this.sessionCaptureCount++,e.success&&this.stats.successfulCaptures++,e.domain){let t=this.stats.byDomain.get(e.domain)||0;this.stats.byDomain.set(e.domain,t+1)}}async calculateAvgQuality(){let e=await this.searchExperiences({limit:100});return e.length===0?0:e.reduce((i,n)=>i+n.quality,0)/e.length}usageOutcomeTag(e){let t=typeof e.metadata?.runId=="string"?e.metadata.runId:void 0;return e.outcomeBasis!==void 0?B({measured:!0,success:e.success,basis:e.outcomeBasis},t):B({measured:!1,success:null,basis:"task-completed"},t)}experienceToPatternOptions(e){let t=this.detectPatternType(e.task),n=`Task: {{task}}
|
|
7
|
+
|
|
8
|
+
Steps:
|
|
9
|
+
${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
|
|
10
|
+
`)}
|
|
11
|
+
|
|
12
|
+
Duration: ${e.durationMs}ms`;return{patternType:t,qeDomain:e.domain,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:[...this.extractTags(e),this.experienceIdentity(e)],experienceOrigin:{task:e.task,domain:e.domain??null,patternType:t},testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}experienceIdentity(e){return le("sha256").update(JSON.stringify([e.task,e.domain??null,this.detectPatternType(e.task)])).digest("hex")}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t} ${this.experienceIdentity(e)}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){F.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function ee(u,e,t,i){return new L(u,e,t,i)}var ge={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},I=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ge,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await H(J),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=N(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=G(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-MX4FC2JE.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=ee(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-LC6Q2W27.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-LC6Q2W27.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-MHSI7ABK.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-MHSI7ABK.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-4DUV6MQC.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-KFHSR5YF.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-AKVSBD6E.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=r.byDomain?.[a]??0,o=r.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:r.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=K({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=U(i.value,t.value);return k(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return k([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),k([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${te().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${te().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(c){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(c))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let c=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});c.success&&c.value.length>0&&(s=c.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:s}));let d={id:o||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(d.id,d),d.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let m of d.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&c.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&c.add("javascript"),m.endsWith(".py")&&c.add("python"),m.endsWith(".go")&&c.add("go"),m.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let m=b(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},me={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ie=class{config;constructor(e){this.config={...me,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),s=h(i.map(l=>l.tokenMetrics.costUsd)),o=h(n.map(l=>l.tokenMetrics.costUsd)),d=h(i.map(l=>l.tokenMetrics.savingsUsd)),c=h(n.map(l=>l.tokenMetrics.savingsUsd));if(o>s*1.1&&c<=d*1.05){let l=Math.min(1,(o-s)/(s||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(l),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(l=>l.qualityMetrics.gatePassRate)),w=h(n.map(l=>l.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(l=>l.learningMetrics.patternCount)),f=h(n.map(l=>l.learningMetrics.patternCount)),ne=h(i.map(l=>l.learningMetrics.averageConfidence)),O=h(n.map(l=>l.learningMetrics.averageConfidence)),re=Math.abs(f-p),ae=Math.abs(O-ne);re<1&&ae<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${O.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let x=h(i.map(l=>l.performanceMetrics.p95LatencyMs)),j=h(n.map(l=>l.performanceMetrics.p95LatencyMs));if(j>x*1.2&&x>0){let l=Math.min(1,(j-x)/(x||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${x.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(l),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(u){return u.length===0?0:u.reduce((e,t)=>e+t,0)/u.length}function A(u){return Math.max(0,Math.min(1,u))}function he(u,e,t){return new I(u,e,t)}function st(u,e,t){return he(u,{projectRoot:e},t)}export{ge as a,I as b,me as c,ie as d,he as e,st 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.10");process.exit(0)}
|
|
2
2
|
var v="quality-assessment";var p=["coverage","testsPassing","criticalBugs","codeSmells","securityVulnerabilities","technicalDebt","duplications"],g={coverage:{direction:"min",value:80,severity:"high"},testsPassing:{direction:"min",value:95,severity:"critical"},criticalBugs:{direction:"max",value:0,severity:"critical"},codeSmells:{direction:"max",value:20,severity:"medium"},securityVulnerabilities:{direction:"max",value:0,severity:"critical"},technicalDebt:{direction:"max",value:5,severity:"medium"},duplications:{direction:"max",value:5,severity:"low"}};function f(e){return`quality-evidence:${e}:latest`}function E(e,t,r){if(typeof e!="string")throw new Error("Measured quality evidence is malformed: measuredAt is required.");let i=Date.parse(e);if(!Number.isFinite(i))throw new Error("Measured quality evidence is malformed: measuredAt is invalid.");if(i>t+6e4)throw new Error("Measured quality evidence is malformed: measuredAt is in the future.");if(t-i>r)throw new Error("Measured quality evidence is stale. Run the relevant quality analyzers again.");return i}function h(e,t,r,i){if(!e||typeof e!="object")throw new Error(`No measured quality evidence found for ${t}.`);let a=e;if(a.schemaVersion!==1||a.metric!==t||!Number.isFinite(a.value)||a.value<0||typeof a.source!="string"||a.source.trim().length===0)throw new Error(`Measured quality evidence for ${t} is malformed or incomplete.`);E(a.measuredAt,r,i)}async function b(e,t,r){let i=Date.now();if(E(r.measuredAt,i,Number.POSITIVE_INFINITY),r.source.trim().length===0)throw new Error("Quality evidence source is required.");for(let a of p){let s=t[a];if(s===void 0)continue;if(!Number.isFinite(s)||s<0)throw new Error(`Quality evidence value for ${a} must be a non-negative finite number.`);let n={schemaVersion:1,metric:a,value:s,measuredAt:r.measuredAt,source:r.source,...r.runId?{runId:r.runId}:{},...r.runStatus?{runStatus:r.runStatus}:{}};await e.set(f(a),n,{namespace:v,persist:!0})}}function Q(e){let t=e.passed+e.failed+(e.skipped??0);return t>0?e.passed/t*100:0}async function A(e,t,r){let i=t.failed>0?"failed":"passed",a={measuredAt:r.measuredAt??new Date().toISOString(),source:r.source,runId:t.runId,runStatus:i};await b(e,{testsPassing:Q(t),...typeof r.coverage=="number"&&Number.isFinite(r.coverage)?{coverage:r.coverage}:{}},a)}var m="insufficient-evidence",c="no MCP tool or CLI command records it yet, so supply it from your own measurement",M={coverage:"run the tests with coverage instrumentation enabled so measured line coverage is recorded (a static estimate is not measured coverage)",testsPassing:"run the test suite (test_execute_parallel, or `aqe test execute`)",security:"static analysis never measures security; drop it from metrics and use security_scan_comprehensive (or `aqe security`) for findings",securityVulnerabilities:`a measured vulnerability count is required; ${c}`,criticalBugs:`a measured critical-bug count is required; ${c}`,codeSmells:`a measured code-smell count is required; ${c}`,technicalDebt:`a measured technical-debt ratio is required; ${c}`,duplications:`a measured duplication percentage is required; ${c}`,complexity:"make sure the target contains readable TypeScript/JavaScript source the analyzer can parse",maintainability:"make sure the target contains readable TypeScript/JavaScript source the analyzer can parse",testability:"make sure the target contains readable TypeScript/JavaScript source the analyzer can parse",duplication:"make sure the target contains readable TypeScript/JavaScript source the analyzer can parse"};function I(e){return e.map(t=>`Insufficient evidence: ${t} not measured \u2014 ${M[t]??"measure it"}.`)}var y=class extends Error{status=m;unmeasured;problems;constructor(t){super(t[0]?.reason??"Measured quality evidence is unavailable."),this.name="InsufficientQualityEvidenceError",this.problems=t,this.unmeasured=t.map(r=>r.metric)}toDetails(){return{passed:!1,status:m,evidenceStatus:m,unmeasured:this.unmeasured,gateEvaluated:!1,recommendations:I(this.unmeasured)}}};async function w(e,t={}){let r=t.now??Date.now(),i=t.maxAgeMs??864e5,a={},s=[],n={};for(let u of p){let d=await e.get(f(u),{namespace:v});try{h(d,u,r,i),a[u]=d.value,n[u]=d}catch(l){s.push({metric:u,reason:l instanceof Error?l.message:String(l)})}}let o=n.coverage;return o?.runStatus==="failed"&&(!o.runId||n.testsPassing?.runId!==o.runId)&&(delete a.coverage,s.push({metric:"coverage",reason:"Measured coverage comes from a run with failing tests, but no testsPassing evidence from that same run was recorded. Re-run the test suite."})),{values:a,problems:s}}async function N(e,t,r={}){let i=await e.get(f(t),{namespace:v});try{return h(i,t,r.now??Date.now(),r.maxAgeMs??864e5),i}catch{return null}}async function S(e,t={}){let{values:r,problems:i}=await w(e,t);if(i.length>0)throw new y(i);return r}function x(e={}){if(e.coverage!==void 0&&(!Number.isFinite(e.coverage)||e.coverage<0||e.coverage>100))throw new Error("Coverage quality threshold must be a finite number between 0 and 100.");return{...g,...e.coverage!==void 0?{coverage:{...g.coverage,value:e.coverage}}:{}}}function T(e,t={}){let r=x(t),i=p.map(a=>{let s=r[a],n=e[a];return{name:a,value:n,threshold:s.value,direction:s.direction,severity:s.severity,passed:s.direction==="min"?n>=s.value:n<=s.value}});return{passed:i.every(a=>a.passed),checks:i,recommendations:i.filter(a=>!a.passed).map(a=>`${a.name} failed its measured ${a.direction} threshold.`)}}export{p as a,g as b,b as c,A as d,m as e,I as f,y as g,w as h,N as i,S as j,x as k,T as l};
|
|
@@ -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.10");process.exit(0)}
|
|
2
|
+
var l="defect-intelligence",d=["critical","high","medium","low","info"],m=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function u(e){if(!m(e))return null;let{file:i,probability:t,riskLevel:r}=e;if(typeof i!="string"||i.length===0||typeof t!="number"||!Number.isFinite(t)||t<0||t>1||!d.includes(r))return null;let c=Array.isArray(e.factors)?e.factors.filter(o=>m(o)&&typeof o.name=="string"&&typeof o.contribution=="number"&&Number.isFinite(o.contribution)):[],a=Array.isArray(e.recommendations)?e.recommendations.filter(o=>typeof o=="string"):[];return{file:i,probability:t,riskLevel:r,factors:c,recommendations:a}}function f(e,i){if(!m(e)||typeof e.id!="string"||typeof e.timestamp!="string")return null;let t=Date.parse(e.timestamp);if(!Number.isFinite(t)||t>i+6e4||i-t>6048e5||!Array.isArray(e.predictions)||e.predictions.length===0)return null;let r=e.predictions.map(u);return r.some(c=>c===null)?null:{id:e.id,timestamp:e.timestamp,predictions:r,...e.predictionMethod==="static-code-indicators"?{predictionMethod:"static-code-indicators",estimated:!0,filesSkipped:typeof e.filesSkipped=="number"&&Number.isSafeInteger(e.filesSkipped)&&e.filesSkipped>=0?e.filesSkipped:0}:{}}}async function A(e,i="defect-intelligence:predictor"){let t=`${i}:prediction:`,r=await e.search(`${t}*`,Number.MAX_SAFE_INTEGER,{namespace:l}),c=Date.now(),a=[],o=[];for(let n of r){let s=n.startsWith(`${l}:${t}`)?n.slice(l.length+1):n;if(!s.startsWith(t))continue;let p=f(await e.get(s,{namespace:l}),c);p?a.push({key:s,timestamp:Date.parse(p.timestamp),id:p.id}):o.push(s)}a.sort((n,s)=>s.timestamp-n.timestamp||(n.id===s.id?n.key===s.key?0:n.key>s.key?-1:1:n.id>s.id?-1:1));for(let n of[...o,...a.slice(32).map(s=>s.key)])await e.delete(n,{namespace:l})}function g(e){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/\*/g,".*").replace(/\?/g,".")}$`,"s")}function y(e,i,t){return g(t).test(e)?e:e.startsWith(`${i}:`)?e.slice(i.length+1):e}var k=1e4,h=32;async function b(e,i,t={}){let r=Math.max(1,Math.floor(t.pageSize??k)),c=await e.search(i,r,t.retrieve);for(let n=1;c.length>=r;n++){if(n>=h)throw new Error(`searchAllKeys('${i}'): the backend never returned a short page after ${n} requests (last limit ${r}); refusing to return a possibly incomplete key list`);r*=2,c=await e.search(i,r,t.retrieve)}let a=t.retrieve?.namespace,o=a?c.map(n=>y(n,a,i)):c;return[...new Set(o)].sort()}export{f as a,A as b,y as c,b as d};
|
|
@@ -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-L42JPFCC.js";import{a as Ae,c as Me}from"./chunk-PMCRCEW5.js";import{b as a,g as we}from"./chunk-XUIA5KMS.js";import{a as me,b as $e}from"./chunk-UOJBR4J3.js";import{b as Re,c as w,d as _e,f as x}from"./chunk-HGTWAZWU.js";import{e as z,h as Ce,i as de,n as H}from"./chunk-XYCKHYBM.js";import{b as W,d as ke}from"./chunk-PVIA2FPD.js";import{a as pe,e as Ge}from"./chunk-OG2UI6A3.js";import{b as Ee,d as Fe}from"./chunk-EFBLP43U.js";import{b as _,e as O}from"./chunk-N3KEY4XJ.js";import{b as $}from"./chunk-HZ5NC6U5.js";async function A(g,t,e,r,o="absolute",s){let n=new AbortController,i=!1,l,d=()=>{i=!0;let u=r();l?.(u),n.abort(u)},h=setTimeout(d,e),c=s!==void 0&&s>0?setTimeout(d,s):void 0;c?.unref?.();let p=()=>{clearTimeout(h),c&&clearTimeout(c)},m=()=>{o==="idle"&&(clearTimeout(h),h=setTimeout(d,e),h.unref?.())};h.unref?.();try{let u=await fetch(g,{...t,signal:n.signal});if(!u.body)return p(),u;m();let f=u.body.getReader(),b=!1,y=()=>{b=!0,p()},E=new ReadableStream({start(R){l=C=>{b||(y(),R.error(C),f.cancel(C).catch(()=>{}).finally(()=>f.releaseLock()))}},async pull(R){try{let C=await f.read();if(b)return;C.done?(y(),f.releaseLock(),R.close()):(m(),R.enqueue(C.value))}catch(C){if(b)return;y(),f.releaseLock(),R.error(C)}},async cancel(R){if(!b){y();try{await f.cancel(R)}finally{f.releaseLock()}}}},{highWaterMark:0}),v=new Response(E,{status:u.status,statusText:u.statusText,headers:u.headers});for(let R of["url","redirected","type"])Object.defineProperty(v,R,{value:u[R]});return v}catch(u){throw p(),i||u instanceof Error&&u.name==="AbortError"?r():u}}var I=$(()=>{"use strict"});import{readFileSync as Ve}from"fs";import*as Ie from"path";function J(g){return typeof g=="string"&&Ye.includes(g)}function Xe(g){try{let e=Ve(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&J(e[1])?e[1]:null}catch{return null}}function Se(g={}){if(g.override&&J(g.override))return g.override;if(g.agentEffort&&J(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&J(e))return e;let r=g.fleetDefaultsPath??Ie.join(process.cwd(),"config","fleet-defaults.yaml");return Y===void 0&&(Y=Xe(r)),Y||Je}var Ye,Je,Y,xe=$(()=>{"use strict";Ye=["low","medium","high","xhigh","max"],Je="xhigh"});function Qe(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function X(g,t,e){let r=Qe(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(Ze(t)?Se():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function Ze(g){return Ce(g)?.tier==="flagship"}var be=$(()=>{"use strict";H();xe()});function gt(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return dt.test(g)?{...ht}:{...mt}}}function D(g,t,e){let r=gt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var dt,mt,ht,ve=$(()=>{"use strict";H();dt=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,mt={sendSampling:!0,maxTokensField:"max_tokens"},ht={sendSampling:!1,maxTokensField:"max_completion_tokens"}});Fe();O();var Le={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},he=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Le,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(_(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},j=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Le,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new he(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};import{createHash as We}from"node:crypto";var Pe={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},L=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...Pe,...t}}static generateKey(t,e,r){let o=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e],s=[r?.stopSequences,r?.effort,r?.preferredProvider];s.some(i=>i!==void 0)&&o.push(JSON.stringify(s));let n=We("sha256").update(JSON.stringify(o)).digest("hex");return`${t}:${n}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.config.enableLRU&&this.updateAccessOrder(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t!==void 0&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},V=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...Pe,...t},this.generationCache=new L(t),this.embeddingCache=new L(t),this.completionCache=new L(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=L.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations||e.finishReason==="content_filter")return;let s=L.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=L.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=L.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=L.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions||e.completion.length===0)return;let s=L.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};x();Ge();var ge="(unattributed)",ze=`
|
|
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.10");process.exit(0)}
|
|
2
|
+
import{b as T}from"./chunk-EDLFX4ZB.js";import{a as Ae,c as Me}from"./chunk-I33O4BRQ.js";import{b as a,g as we}from"./chunk-WDQ7IEZY.js";import{a as me,b as $e}from"./chunk-2SXBBUM6.js";import{b as Re,c as w,d as _e,f as x}from"./chunk-KNQ2ERFX.js";import{e as z,h as Ce,i as de,n as H}from"./chunk-XFVTGAAJ.js";import{b as W,d as ke}from"./chunk-ACWFKES2.js";import{a as pe,e as Ge}from"./chunk-AI4VYSFS.js";import{b as Ee,d as Fe}from"./chunk-6GP6W46M.js";import{b as _,e as O}from"./chunk-GHBNRMSJ.js";import{b as $}from"./chunk-OY2AHLSF.js";async function A(g,t,e,r,o="absolute",s){let n=new AbortController,i=!1,l,d=()=>{i=!0;let u=r();l?.(u),n.abort(u)},h=setTimeout(d,e),c=s!==void 0&&s>0?setTimeout(d,s):void 0;c?.unref?.();let p=()=>{clearTimeout(h),c&&clearTimeout(c)},m=()=>{o==="idle"&&(clearTimeout(h),h=setTimeout(d,e),h.unref?.())};h.unref?.();try{let u=await fetch(g,{...t,signal:n.signal});if(!u.body)return p(),u;m();let f=u.body.getReader(),b=!1,y=()=>{b=!0,p()},E=new ReadableStream({start(R){l=C=>{b||(y(),R.error(C),f.cancel(C).catch(()=>{}).finally(()=>f.releaseLock()))}},async pull(R){try{let C=await f.read();if(b)return;C.done?(y(),f.releaseLock(),R.close()):(m(),R.enqueue(C.value))}catch(C){if(b)return;y(),f.releaseLock(),R.error(C)}},async cancel(R){if(!b){y();try{await f.cancel(R)}finally{f.releaseLock()}}}},{highWaterMark:0}),v=new Response(E,{status:u.status,statusText:u.statusText,headers:u.headers});for(let R of["url","redirected","type"])Object.defineProperty(v,R,{value:u[R]});return v}catch(u){throw p(),i||u instanceof Error&&u.name==="AbortError"?r():u}}var I=$(()=>{"use strict"});import{readFileSync as Ve}from"fs";import*as Ie from"path";function J(g){return typeof g=="string"&&Ye.includes(g)}function Xe(g){try{let e=Ve(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&J(e[1])?e[1]:null}catch{return null}}function Se(g={}){if(g.override&&J(g.override))return g.override;if(g.agentEffort&&J(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&J(e))return e;let r=g.fleetDefaultsPath??Ie.join(process.cwd(),"config","fleet-defaults.yaml");return Y===void 0&&(Y=Xe(r)),Y||Je}var Ye,Je,Y,xe=$(()=>{"use strict";Ye=["low","medium","high","xhigh","max"],Je="xhigh"});function Qe(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,supportsEffort:t.supportsEffortXHigh===!0}}catch{return{sendSampling:!1,supportsEffort:!1}}}function X(g,t,e){let r=Qe(t);if(r.sendSampling&&e.temperature!==void 0&&(g.temperature=e.temperature),r.supportsEffort){let o=e.effort??(Ze(t)?Se():void 0);o!==void 0&&(g.output_config={effort:o})}return g}function Ze(g){return Ce(g)?.tier==="flagship"}var be=$(()=>{"use strict";H();xe()});function gt(g){try{let t=z(g);return{sendSampling:t.supportsSamplingParams!==!1,maxTokensField:t.usesMaxCompletionTokens===!0?"max_completion_tokens":"max_tokens"}}catch{return dt.test(g)?{...ht}:{...mt}}}function D(g,t,e){let r=gt(t),o=g;return e.maxTokens!==void 0&&(o[r.maxTokensField]=e.maxTokens),r.sendSampling&&e.temperature!==void 0&&(o.temperature=e.temperature),g}var dt,mt,ht,ve=$(()=>{"use strict";H();dt=/^(openai\/)?(gpt-5|gpt-6|o\d)/i,mt={sendSampling:!0,maxTokensField:"max_tokens"},ht={sendSampling:!1,maxTokensField:"max_completion_tokens"}});Fe();O();var Le={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},he=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...Le,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(_(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},j=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...Le,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new he(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};import{createHash as We}from"node:crypto";var Pe={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},L=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...Pe,...t}}static generateKey(t,e,r){let o=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e],s=[r?.stopSequences,r?.effort,r?.preferredProvider];s.some(i=>i!==void 0)&&o.push(JSON.stringify(s));let n=We("sha256").update(JSON.stringify(o)).digest("hex");return`${t}:${n}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.config.enableLRU&&this.updateAccessOrder(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t!==void 0&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},V=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...Pe,...t},this.generationCache=new L(t),this.embeddingCache=new L(t),this.completionCache=new L(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=L.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations||e.finishReason==="content_filter")return;let s=L.generateKey("generation",t,r);this.generationCache.set(s,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=L.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let s=L.generateKey("embedding",t,r);this.embeddingCache.set(s,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=L.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions||e.completion.length===0)return;let s=L.generateKey("completion",t,r);this.completionCache.set(s,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,s=t.misses+e.misses+r.misses,n=o+s;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:s,hitRate:n>0?o/n:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};x();Ge();var ge="(unattributed)",ze=`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS llm_spend (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
ts INTEGER NOT NULL,
|
|
@@ -17,7 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
|
|
|
17
17
|
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
|
|
18
18
|
(ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
|
|
19
19
|
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
|
|
20
|
-
FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ge,e-t,ge),o=pe();for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},B=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ge})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o=pe();for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Oe(){try{let t=(await import("./unified-memory-
|
|
20
|
+
FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ge,e-t,ge),o=pe();for(let s of r)o[s.agent]=s.total;return o}catch{return{}}}},B=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ge})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let s of this.entries)s.ts>=r&&(o+=s.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o=pe();for(let s of this.entries)s.ts>=r&&(o[s.agent]=(o[s.agent]??0)+s.costUsd);return o}};async function Oe(){try{let t=(await import("./unified-memory-EHD4VNFW.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new fe(t.getDatabase())}catch{return new B}}x();O();O();function ye(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),s=Math.random()*r*o;return o+s}var He=1e3,je=3e4;function k(g,t=He,e=je){return ye(g,t,e,0)}I();be();H();var et={model:de,maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},Q=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...et,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let s=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${s}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),s=e?.model??this.config.model,n=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,d=Date.now(),h={model:s,max_tokens:n,messages:o};X(h,s,{temperature:i,effort:e?.effort}),e?.systemPrompt&&(h.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(h.stop_sequences=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-d;if(!c.ok){let v=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,v,s)}let m=await c.json(),u=m.usage.cache_creation_input_tokens??0,f=m.usage.cache_read_input_tokens??0,b={promptTokens:m.usage.input_tokens,completionTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+u+f+m.usage.output_tokens,cacheCreationTokens:u,cacheReadTokens:f},y=w.calculateCost(s,b);return T.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:m.usage.input_tokens,outputTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+m.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:m.content.filter(v=>v.type==="text").map(v=>v.text).join(""),model:m.model,provider:"claude",usage:b,cost:y,latencyMs:p,finishReason:this.mapFinishReason(m.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:s,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
21
21
|
|
|
22
22
|
`,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return w.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let o="error"in e?e.error?.message??"Unknown API error":"Unknown API error",s="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){return A(t,e,r,()=>a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}))}async fetchWithRetry(t,e,r,o){let s;for(let n=0;n<o;n++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&n<o-1){let l=k(n);await this.sleep(l);continue}return i}catch(i){if(s=_(i),n<o-1){let l=k(n);await this.sleep(l)}}throw s??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as tt}from"node:child_process";var rt=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],ot={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},Z=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...ot,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:s,systemPrompt:n}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];n&&i.push("--append-system-prompt",n);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let d=Date.now(),h=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:p,stderr:m}=await this.withConcurrency(()=>this.runProcess(i,s,h)),u=Date.now()-d;if(c!==0&&!p.trim())throw this.classifyError(m||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(p)}catch{throw a(`Could not parse claude -p JSON output: ${p.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},E=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return T.recordTokenUsage(o,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:E,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:u,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(s=>s.role==="system").map(s=>s.content);return e&&r.unshift(e),{prompt:t.filter(s=>s.role!=="system").map(s=>`${s.role==="assistant"?"Assistant":"User"}: ${s.content}`).join(`
|
|
23
23
|
|
|
@@ -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.10");process.exit(0)}
|
|
2
2
|
var t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function r(e){return typeof e=="string"&&t.includes(e)}function i(e){return{success:!0,value:e}}function o(e){return{success:!1,error:e}}var n=["p0","p1","p2","p3"];function a(e){return typeof e=="string"&&n.includes(e)}function s(e){return`Invalid priority: ${String(e)}. Valid priorities: ${n.join(", ")}`}export{t as a,r as b,i as c,o as d,a as e,s 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{c as h,d 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.10");process.exit(0)}
|
|
2
|
+
import{c as h,d as $}from"./chunk-EWFECZ2U.js";import{a as b,b as y,c as R,e as S,f as A}from"./chunk-V2M2XCR5.js";import{e as N,f as w}from"./chunk-KOBVYY6H.js";import{a as g,f as C}from"./chunk-OY2AHLSF.js";$();var i=null,f=!1,p=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e));this.lockError=e;this.name="RvfLiveLockError"}lockError};function V(r){i=r,f=r!==null}var B=(()=>{let r=process.env.AQE_RVF_SIZE_GUARD_BYTES,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0?t:256*1024*1024})(),F=(()=>{let r=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,t=r?Number(r):NaN;return Number.isFinite(t)&&t>0&&t<=1?t:.3})();function k(r=".agentic-qe",t=384){if(f)return i;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:n,openRvfStore:o}=(w(),C(N));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let s=g("path"),l=s.isAbsolute(r)?r:s.join(process.env.AQE_PROJECT_ROOT??h(),r),u=s.join(l,"patterns.rvf");return i=_(o,n,u,t),T(i,u),i}catch(e){return e instanceof p||console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function _(r,t,e,n){let o=()=>{try{return{adapter:r(e),err:null}}catch(a){return{adapter:null,err:a}}},{adapter:s,err:l}=o(),u=!1;if(!s&&R(l))try{let a=g("fs"),c=`${e}.lock`;a.existsSync(c)&&y(e)?(u=!0,console.warn(`[RVF] ${e} is locked by a live process (pid ${b(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`)):S(e)&&(console.warn(`[RVF] Removed stale lock file at ${c} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:s,err:l}=o())}catch(a){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",a instanceof Error?a.message:a)}if(u)throw new p(l);if(s){let a=s.dimension();if(a===n)return s;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${a} requested=${n} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{s.close()}catch{}throw new Error(`RVF dimension mismatch (file=${a}, requested=${n})`)}try{return t(e,n)}catch(a){let c;try{c=r(e)}catch(m){if(R(m))throw m;if(A(e,a instanceof Error?a.message:String(a),m))return t(e,n);throw a instanceof Error?a:new Error(String(a))}let v=c.dimension();if(v!==n){try{c.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${v}, requested=${n})`)}return c}}function E(r,t){if(t?.force)return{shouldCompact:!0,trigger:"force"};let e=t?.sizeGuardBytes??B,n=t?.deadRatioThreshold??F;return r.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(r.deadSpaceRatio??0)>=n?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function q(r){if(!i)return null;let t;try{t=i.status()}catch{return null}let e=E(t,r);if(!e.shouldCompact)return null;let n=t.fileSizeBytes,o;try{o=i.compact()}catch{return null}return o?((o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(o.bytesReclaimed)} (${o.segmentsCompacted} segments, fileSize ${d(n)} \u2192 ${d(Math.max(0,n-o.bytesReclaimed))}, trigger: ${e.trigger})`),o):null}function T(r,t){try{let e=r.status(),n=E(e);if(!n.shouldCompact)return null;let o=r.compact();return o&&(o.bytesReclaimed>0||o.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${t}): reclaimed ${d(o.bytesReclaimed)} from ${o.segmentsCompacted} segments (trigger: ${n.trigger})`),o}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(r){if(!Number.isFinite(r)||r<0)return`${r}B`;let t=["B","KB","MB","GB","TB"],e=0,n=r;for(;n>=1024&&e<t.length-1;)n/=1024,e++;return`${n.toFixed(e===0?0:1)}${t[e]}`}function z(){if(i){try{i.close()}catch{}i=null}f=!1}export{p as a,V as b,k as c,_ as d,E as e,q as f,T as g,z as h};
|
|
@@ -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.10");process.exit(0)}
|
|
2
2
|
var i=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],s="claude-sonnet-4-6",a=`anthropic/${s.replace("4-6","4.6")}`,u=s,p=new Set(["opus","fable"]),l=/claude-(opus|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/,o={major:4,minor:7};function E(e){let r=e.trim().toLowerCase();if(p.has(r))return!0;let n=l.exec(r);if(!n)return!1;let t=Number(n[2]),c=n[3]===void 0?0:Number(n[3]);return t>o.major||t===o.major&&c>=o.minor}function _(e,r=process.env){return r.AQE_CYBER_VERIFIED==="true"?!1:i.includes(e)}function d(e,r,n,t=process.env){return!_(e,t)||!E(r)?r:n}function f(e){switch(e){case"openrouter":return a;case"bedrock":return"anthropic.claude-sonnet-4-6-v1:0";default:return u}}export{a,u as b,E as c,_ as d,d as e,f};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as w,c as E,d as k,o as de,s as ue}from"./chunk-OCESWNAZ.js";import{a as Ce,b as _,d as ee}from"./chunk-PVIA2FPD.js";import{a as le,d as Te}from"./chunk-SVHUYVUR.js";import{i as j}from"./chunk-FV7VAG74.js";import{a as v}from"./chunk-KTSLTZSG.js";import{e as b}from"./chunk-O3JLOVZX.js";import{a as d,b as L,e as P}from"./chunk-N3KEY4XJ.js";import{c as I}from"./chunk-4V27J6YN.js";import{a as T,b as z}from"./chunk-6YL6JOQB.js";import{e as Ee}from"./chunk-HZ5NC6U5.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Re={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as me from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=me.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var pe=Ee(Ce(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=_e({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=ve("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return he(this.getConnectionString())}};function ke(l){return new $(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Ae}from"module";var N=b.create("postgres-writer"),$e=Ae(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
|
|
2
|
+
import{b as w,c as E,d as k,r as de,v as ue}from"./chunk-C522H7XR.js";import{a as Ce,b as _,d as ee}from"./chunk-ACWFKES2.js";import{a as le,d as Te}from"./chunk-6PX4OXQO.js";import{i as j}from"./chunk-WQ4PYWSW.js";import{a as v}from"./chunk-HOZUDE4C.js";import{c as b}from"./chunk-ATHWDAXB.js";import{a as d,b as L,e as P}from"./chunk-GHBNRMSJ.js";import{c as I}from"./chunk-EWFECZ2U.js";import{a as T,b as z}from"./chunk-XBVUVFJK.js";import{e as Ee}from"./chunk-OY2AHLSF.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Re={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as me from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=me.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var pe=Ee(Ce(),1);P();import{randomUUID as Pe}from"crypto";import*as C from"fs";import*as ge from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=pe.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${Pe().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as ve}from"child_process";import{createConnection as _e}from"net";var xe=b.create("tunnel-manager");function he(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return xe.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=_e({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=ve("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return he(this.getConnectionString())}};function ke(l){return new $(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return he(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Ae}from"module";var N=b.create("postgres-writer"),$e=Ae(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let we=f[R];S.push(`$${c++}`),a.push(this.serializeValue(we,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
|
|
3
3
|
INSERT INTO ${u} (${p.join(", ")})
|
|
4
4
|
VALUES ${s.join(", ")}
|
|
5
5
|
${h}
|
|
@@ -26,4 +26,4 @@ import{b as w,c as E,d as k,o as de,s as ue}from"./chunk-OCESWNAZ.js";import{a a
|
|
|
26
26
|
INSERT OR REPLACE INTO embeddings
|
|
27
27
|
(key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
|
|
28
28
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
29
|
-
`).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-TOFMWWNM.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();k();P();ee();v();import{resolve as ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){be.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){be.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function Se(l){return new q(l)}export{A as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,ke as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se as A};
|
|
29
|
+
`).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-H5RGFKVO.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();k();P();ee();v();import{resolve as ze,dirname as je}from"path";import{fileURLToPath as Fe}from"url";var be=b.create("sync-embedding-generator"),We=Fe(import.meta.url),Ue=je(We),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||ze(Ue,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){be.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){be.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function Se(l){return new q(l)}export{A as a,Re as b,x as c,W as d,re as e,U as f,ne as g,$ as h,ke as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Ne as t,Oe as u,X as v,ce as w,De as x,qe as y,q as z,Se as A};
|
|
@@ -1,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 N,d as P}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.10");process.exit(0)}
|
|
2
|
+
import{a as N,d as P}from"./chunk-6GP6W46M.js";import{b,e as k}from"./chunk-PGYMKGOE.js";import{a as T,b as E}from"./chunk-GZLZCZ42.js";import{a as H,b as O}from"./chunk-GJMLK5UT.js";import{a as p,d as F}from"./chunk-6PX4OXQO.js";import{b as z,f as S}from"./chunk-OY2AHLSF.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
|