agentic-qe 3.10.4 → 3.10.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/v3/qe-accessibility-auditor.md +8 -0
- package/.claude/agents/v3/qe-bdd-generator.md +8 -0
- package/.claude/agents/v3/qe-chaos-engineer.md +8 -0
- package/.claude/agents/v3/qe-code-complexity.md +8 -0
- package/.claude/agents/v3/qe-code-intelligence.md +8 -0
- package/.claude/agents/v3/qe-contract-validator.md +8 -0
- package/.claude/agents/v3/qe-coverage-specialist.md +8 -0
- package/.claude/agents/v3/qe-defect-predictor.md +8 -0
- package/.claude/agents/v3/qe-dependency-mapper.md +8 -0
- package/.claude/agents/v3/qe-deployment-advisor.md +8 -0
- package/.claude/agents/v3/qe-devils-advocate.md +8 -0
- package/.claude/agents/v3/qe-flaky-hunter.md +8 -0
- package/.claude/agents/v3/qe-fleet-commander.md +8 -0
- package/.claude/agents/v3/qe-gap-detector.md +8 -0
- package/.claude/agents/v3/qe-graphql-tester.md +8 -0
- package/.claude/agents/v3/qe-impact-analyzer.md +8 -0
- package/.claude/agents/v3/qe-integration-tester.md +8 -0
- package/.claude/agents/v3/qe-kg-builder.md +8 -0
- package/.claude/agents/v3/qe-learning-coordinator.md +8 -0
- package/.claude/agents/v3/qe-load-tester.md +8 -0
- package/.claude/agents/v3/qe-message-broker-tester.md +8 -0
- package/.claude/agents/v3/qe-metrics-optimizer.md +8 -0
- package/.claude/agents/v3/qe-middleware-validator.md +8 -0
- package/.claude/agents/v3/qe-mutation-tester.md +8 -0
- package/.claude/agents/v3/qe-odata-contract-tester.md +8 -0
- package/.claude/agents/v3/qe-parallel-executor.md +8 -0
- package/.claude/agents/v3/qe-pattern-learner.md +8 -0
- package/.claude/agents/v3/qe-pentest-validator.md +8 -0
- package/.claude/agents/v3/qe-performance-tester.md +8 -0
- package/.claude/agents/v3/qe-product-factors-assessor.md +8 -0
- package/.claude/agents/v3/qe-property-tester.md +8 -0
- package/.claude/agents/v3/qe-quality-criteria-recommender.md +8 -0
- package/.claude/agents/v3/qe-quality-gate.md +8 -0
- package/.claude/agents/v3/qe-qx-partner.md +8 -0
- package/.claude/agents/v3/qe-regression-analyzer.md +8 -0
- package/.claude/agents/v3/qe-requirements-validator.md +8 -0
- package/.claude/agents/v3/qe-responsive-tester.md +8 -0
- package/.claude/agents/v3/qe-retry-handler.md +8 -0
- package/.claude/agents/v3/qe-risk-assessor.md +8 -0
- package/.claude/agents/v3/qe-root-cause-analyzer.md +8 -0
- package/.claude/agents/v3/qe-sap-idoc-tester.md +8 -0
- package/.claude/agents/v3/qe-sap-rfc-tester.md +8 -0
- package/.claude/agents/v3/qe-security-auditor.md +8 -0
- package/.claude/agents/v3/qe-security-scanner.md +8 -0
- package/.claude/agents/v3/qe-soap-tester.md +8 -0
- package/.claude/agents/v3/qe-sod-analyzer.md +8 -0
- package/.claude/agents/v3/qe-tdd-specialist.md +8 -0
- package/.claude/agents/v3/qe-test-architect.md +8 -0
- package/.claude/agents/v3/qe-test-idea-rewriter.md +8 -0
- package/.claude/agents/v3/qe-transfer-specialist.md +8 -0
- package/.claude/agents/v3/qe-visual-tester.md +8 -0
- package/.claude/skills/qcsd-development-swarm/SKILL.md +27 -6
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +9012 -8863
- package/assets/agents/v3/qe-accessibility-auditor.md +8 -0
- package/assets/agents/v3/qe-bdd-generator.md +8 -0
- package/assets/agents/v3/qe-chaos-engineer.md +8 -0
- package/assets/agents/v3/qe-code-complexity.md +8 -0
- package/assets/agents/v3/qe-code-intelligence.md +8 -0
- package/assets/agents/v3/qe-contract-validator.md +8 -0
- package/assets/agents/v3/qe-coverage-specialist.md +8 -0
- package/assets/agents/v3/qe-defect-predictor.md +8 -0
- package/assets/agents/v3/qe-dependency-mapper.md +8 -0
- package/assets/agents/v3/qe-deployment-advisor.md +8 -0
- package/assets/agents/v3/qe-devils-advocate.md +8 -0
- package/assets/agents/v3/qe-flaky-hunter.md +8 -0
- package/assets/agents/v3/qe-fleet-commander.md +8 -0
- package/assets/agents/v3/qe-gap-detector.md +8 -0
- package/assets/agents/v3/qe-graphql-tester.md +8 -0
- package/assets/agents/v3/qe-impact-analyzer.md +8 -0
- package/assets/agents/v3/qe-integration-tester.md +8 -0
- package/assets/agents/v3/qe-kg-builder.md +8 -0
- package/assets/agents/v3/qe-learning-coordinator.md +8 -0
- package/assets/agents/v3/qe-load-tester.md +8 -0
- package/assets/agents/v3/qe-message-broker-tester.md +8 -0
- package/assets/agents/v3/qe-metrics-optimizer.md +8 -0
- package/assets/agents/v3/qe-middleware-validator.md +8 -0
- package/assets/agents/v3/qe-mutation-tester.md +8 -0
- package/assets/agents/v3/qe-odata-contract-tester.md +8 -0
- package/assets/agents/v3/qe-parallel-executor.md +8 -0
- package/assets/agents/v3/qe-pattern-learner.md +8 -0
- package/assets/agents/v3/qe-pentest-validator.md +8 -0
- package/assets/agents/v3/qe-performance-tester.md +8 -0
- package/assets/agents/v3/qe-product-factors-assessor.md +8 -0
- package/assets/agents/v3/qe-property-tester.md +8 -0
- package/assets/agents/v3/qe-quality-criteria-recommender.md +8 -0
- package/assets/agents/v3/qe-quality-gate.md +8 -0
- package/assets/agents/v3/qe-qx-partner.md +8 -0
- package/assets/agents/v3/qe-regression-analyzer.md +8 -0
- package/assets/agents/v3/qe-requirements-validator.md +8 -0
- package/assets/agents/v3/qe-responsive-tester.md +8 -0
- package/assets/agents/v3/qe-retry-handler.md +8 -0
- package/assets/agents/v3/qe-risk-assessor.md +8 -0
- package/assets/agents/v3/qe-root-cause-analyzer.md +8 -0
- package/assets/agents/v3/qe-sap-idoc-tester.md +8 -0
- package/assets/agents/v3/qe-sap-rfc-tester.md +8 -0
- package/assets/agents/v3/qe-security-auditor.md +8 -0
- package/assets/agents/v3/qe-security-scanner.md +8 -0
- package/assets/agents/v3/qe-soap-tester.md +8 -0
- package/assets/agents/v3/qe-sod-analyzer.md +8 -0
- package/assets/agents/v3/qe-tdd-specialist.md +8 -0
- package/assets/agents/v3/qe-test-architect.md +8 -0
- package/assets/agents/v3/qe-test-idea-rewriter.md +8 -0
- package/assets/agents/v3/qe-transfer-specialist.md +8 -0
- package/assets/agents/v3/qe-visual-tester.md +8 -0
- package/dist/arena/arena.d.ts +68 -0
- package/dist/arena/arena.js +169 -0
- package/dist/arena/mutator.d.ts +23 -0
- package/dist/arena/mutator.js +112 -0
- package/dist/arena/rng.d.ts +15 -0
- package/dist/arena/rng.js +34 -0
- package/dist/arena/runner.d.ts +44 -0
- package/dist/arena/runner.js +79 -0
- package/dist/cli/bundle.js +7 -7
- package/dist/cli/chunks/adapter-AMIHQ243.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-EJPDSWON.js → agent-booster-wasm-J5CITTTV.js} +2 -2
- package/dist/cli/chunks/{agent-handler-2DZB7LGI.js → agent-handler-HMN4ZBZ6.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-SSFYAVIK.js → agent-memory-branch-SCAKN4DU.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-LRG2UG6P.js +2 -0
- package/dist/cli/chunks/arena-CJOLCHZW.js +18 -0
- package/dist/cli/chunks/arena-FVBTSGKS.js +4 -0
- package/dist/cli/chunks/audit-SOF6L5RY.js +3 -0
- package/dist/cli/chunks/base-WDL3FANJ.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-3TZFES5I.js → better-sqlite3-5G7LRX7Q.js} +2 -2
- package/dist/cli/chunks/{brain-handler-LFHX2TYP.js → brain-handler-D2ZQQI2J.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-AX7DKGV7.js → branch-enumerator-QQXOCGOR.js} +2 -2
- package/dist/cli/chunks/{browser-4NYLZ7FA.js → browser-XASHKIEN.js} +2 -2
- package/dist/cli/chunks/browser-workflow-W7S4IKWD.js +2 -0
- package/dist/cli/chunks/{chunk-VJOPNK2L.js → chunk-2CZQA3NN.js} +2 -2
- package/dist/cli/chunks/{chunk-DPKECIKN.js → chunk-2I5RXDNO.js} +2 -2
- package/dist/cli/chunks/{chunk-M4ARHDY4.js → chunk-2IC2I525.js} +1 -1
- package/dist/cli/chunks/{chunk-M5DBKHM4.js → chunk-2RQSFRON.js} +2 -2
- package/dist/cli/chunks/{chunk-WYMQ6FZR.js → chunk-2UI5LQ7C.js} +3 -3
- package/dist/cli/chunks/{chunk-ISRTT4I7.js → chunk-3XUPDWMA.js} +8 -8
- package/dist/cli/chunks/chunk-434VUSZP.js +2 -0
- package/dist/cli/chunks/{chunk-SXMGNMFL.js → chunk-4B22URZJ.js} +3 -3
- package/dist/cli/chunks/{chunk-LHPR7ROV.js → chunk-4N4TU7ST.js} +1 -1
- package/dist/cli/chunks/{chunk-ND6YSW5N.js → chunk-4XEUJH2M.js} +1 -1
- package/dist/cli/chunks/{chunk-BEFRQOLH.js → chunk-5QTUGFFP.js} +2 -2
- package/dist/cli/chunks/{chunk-DAIM72HV.js → chunk-5V4IFRG5.js} +2 -2
- package/dist/cli/chunks/{chunk-F34OO2Q7.js → chunk-5VTRPOYL.js} +3 -3
- package/dist/cli/chunks/{chunk-GILL32E2.js → chunk-6DHJPKAH.js} +2 -2
- package/dist/cli/chunks/{chunk-YSLE6NNG.js → chunk-6RFPELCD.js} +2 -2
- package/dist/cli/chunks/{chunk-B6CT4ILU.js → chunk-6ZLVQTQ5.js} +4 -4
- package/dist/cli/chunks/{chunk-XJXCSCCP.js → chunk-7BPYFDWY.js} +1 -1
- package/dist/cli/chunks/{chunk-RJKYPWFD.js → chunk-7NXVVIJZ.js} +2 -2
- package/dist/cli/chunks/{chunk-USB7GCIC.js → chunk-7OK5H6ML.js} +1 -1
- package/dist/cli/chunks/{chunk-MDWJXSBA.js → chunk-7RTI5WT4.js} +2 -2
- package/dist/cli/chunks/{chunk-O3SG32PS.js → chunk-7SFCZ3AE.js} +1 -1
- package/dist/cli/chunks/{chunk-OV4BLIKJ.js → chunk-A2DCROAN.js} +2 -2
- package/dist/cli/chunks/{chunk-Y2EDDV5U.js → chunk-AJ2VDNPB.js} +3 -3
- package/dist/cli/chunks/chunk-AQPFTDGS.js +14 -0
- package/dist/cli/chunks/{chunk-MFWWPRBV.js → chunk-B3H2TTYT.js} +2 -2
- package/dist/cli/chunks/{chunk-PISW5HUX.js → chunk-BHD6THT5.js} +1 -1
- package/dist/cli/chunks/{chunk-5Q3L4QEE.js → chunk-BXOGLZGU.js} +2 -2
- package/dist/cli/chunks/{chunk-TWAWEP4X.js → chunk-C75ODWRP.js} +3 -3
- package/dist/cli/chunks/{chunk-AMW27FSS.js → chunk-CH7KUYGO.js} +3 -3
- package/dist/cli/chunks/{chunk-MHWYQHGN.js → chunk-CSM4LXTH.js} +1 -1
- package/dist/cli/chunks/{chunk-SC6UFGJ6.js → chunk-DAUQIXHW.js} +2 -2
- package/dist/cli/chunks/{chunk-NJYI7HX7.js → chunk-DF4Z7TKZ.js} +2 -2
- package/dist/cli/chunks/{chunk-IYFMDIYZ.js → chunk-DFBVWMX3.js} +2 -2
- package/dist/cli/chunks/{chunk-FQ7I4JBQ.js → chunk-EDPVATNH.js} +2 -2
- package/dist/cli/chunks/{chunk-STMMZXS6.js → chunk-EJWAKPZD.js} +1 -1
- package/dist/cli/chunks/{chunk-EGTOSQZK.js → chunk-ELC6JIXL.js} +2 -2
- package/dist/cli/chunks/{chunk-TBJ566KV.js → chunk-ELTN4F4R.js} +2 -2
- package/dist/cli/chunks/{chunk-UXJVR323.js → chunk-ESZDW6G7.js} +2 -2
- package/dist/cli/chunks/{chunk-XDZXLEJK.js → chunk-EYKID5HA.js} +2 -2
- package/dist/cli/chunks/{chunk-VRE2EBFI.js → chunk-F72A356B.js} +2 -2
- package/dist/cli/chunks/{chunk-AZJYDM2K.js → chunk-GWHDPEBT.js} +1 -1
- package/dist/cli/chunks/{chunk-L6VNEEN6.js → chunk-GXNNKM7F.js} +1 -1
- package/dist/cli/chunks/{chunk-NSRDP7RD.js → chunk-H4Q36ILL.js} +2 -2
- package/dist/cli/chunks/{chunk-2G2PVVQG.js → chunk-H6UPZFI6.js} +2 -2
- package/dist/cli/chunks/chunk-H73FLSBV.js +699 -0
- package/dist/cli/chunks/{chunk-Q53M4LI7.js → chunk-HDEFCRHI.js} +1 -1
- package/dist/cli/chunks/{chunk-G5FPWH5O.js → chunk-HFU3LTQX.js} +15 -15
- package/dist/cli/chunks/{chunk-C2446H7G.js → chunk-HMHQOEU7.js} +2 -2
- package/dist/cli/chunks/{chunk-IAK76TIZ.js → chunk-HWKFBRMX.js} +1 -1
- package/dist/cli/chunks/{chunk-7BQXEYRV.js → chunk-HZGOVRZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-VJ2D6FST.js → chunk-I7ADT6AZ.js} +2 -2
- package/dist/cli/chunks/{chunk-3UGUX34A.js → chunk-IB3QQDC4.js} +1 -1
- package/dist/cli/chunks/{chunk-5T2HDET6.js → chunk-J2SMTP2L.js} +3 -3
- package/dist/cli/chunks/{chunk-4FTLYIMW.js → chunk-J3WUBGLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-4BX72XG4.js → chunk-JADBRSQN.js} +2 -2
- package/dist/cli/chunks/{chunk-N4CXUGXE.js → chunk-JP2YXWJD.js} +2 -2
- package/dist/cli/chunks/chunk-JPL53G4V.js +20 -0
- package/dist/cli/chunks/{chunk-GLMDRGJD.js → chunk-JX7HZMW5.js} +1 -1
- package/dist/cli/chunks/{chunk-GDMH7NPV.js → chunk-JXCIRWLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-UFKVKNAA.js → chunk-K32AUACO.js} +1 -1
- package/dist/cli/chunks/{chunk-XVA56PXZ.js → chunk-KQOJYO5Z.js} +4 -4
- package/dist/cli/chunks/{chunk-PLD4IGDL.js → chunk-KVMY2ABO.js} +2 -2
- package/dist/cli/chunks/{chunk-7VO5IEJ2.js → chunk-L2IMTNZF.js} +2 -2
- package/dist/cli/chunks/{chunk-KCXE2LZU.js → chunk-LAGNWKAD.js} +2 -2
- package/dist/cli/chunks/{chunk-OIFJH7TF.js → chunk-LEDF3LGZ.js} +1 -1
- package/dist/cli/chunks/{chunk-F6QPAVWS.js → chunk-LHA4OQ7G.js} +2 -2
- package/dist/cli/chunks/{chunk-EMZ3DXMG.js → chunk-LHZOIXJ6.js} +2 -2
- package/dist/cli/chunks/{chunk-MU4P4P4E.js → chunk-LOQMQEKN.js} +1 -1
- package/dist/cli/chunks/{chunk-F77X5DAF.js → chunk-LWUIK5DH.js} +2 -2
- package/dist/cli/chunks/{chunk-KWZEBHAP.js → chunk-M3APJ7VS.js} +2 -2
- package/dist/cli/chunks/{chunk-RUC3FCRK.js → chunk-M4OYZMXE.js} +2 -2
- package/dist/cli/chunks/{chunk-IPAQ4HVX.js → chunk-MCMVRPNG.js} +2 -2
- package/dist/cli/chunks/{chunk-PMWWWYUM.js → chunk-MJLDZSFB.js} +1 -1
- package/dist/cli/chunks/{chunk-M3MKP5VN.js → chunk-MQN3HYFX.js} +1 -1
- package/dist/cli/chunks/{chunk-6OLHPWSN.js → chunk-MSJGDIRP.js} +2 -2
- package/dist/cli/chunks/{chunk-UW3ZSFFB.js → chunk-NEIJP6TG.js} +2 -2
- package/dist/cli/chunks/{chunk-XBFEHVBO.js → chunk-NHC635LL.js} +2 -2
- package/dist/cli/chunks/{chunk-Z4BTPQLG.js → chunk-NKEGEQ3J.js} +2 -2
- package/dist/cli/chunks/{chunk-6SCIX2W2.js → chunk-NN35QH6X.js} +2 -2
- package/dist/cli/chunks/{chunk-ZM4QGYGK.js → chunk-NUCJS3Z7.js} +3 -3
- package/dist/cli/chunks/{chunk-WI5WXYIS.js → chunk-O2H5WYFK.js} +2 -2
- package/dist/cli/chunks/{chunk-2B6ETC7C.js → chunk-O4MNYX4X.js} +2 -2
- package/dist/cli/chunks/{chunk-JYR3X4OC.js → chunk-OBLAWVXM.js} +1 -1
- package/dist/cli/chunks/{chunk-K7CW2X6U.js → chunk-OU4HRUVV.js} +2 -2
- package/dist/cli/chunks/{chunk-E6CGBOZY.js → chunk-P7EOYGR2.js} +2 -2
- package/dist/cli/chunks/{chunk-KJ56OXH4.js → chunk-PFSBUTDA.js} +1 -1
- package/dist/cli/chunks/{chunk-PZCSJZVJ.js → chunk-PIIBVLFC.js} +2 -2
- package/dist/cli/chunks/{chunk-LYKSIOOT.js → chunk-PIJ5XOMM.js} +2 -2
- package/dist/cli/chunks/{chunk-D7IWGQTW.js → chunk-Q4LYWIEX.js} +2 -2
- package/dist/cli/chunks/{chunk-TCV5DASI.js → chunk-Q5432RIH.js} +2 -2
- package/dist/cli/chunks/{chunk-U27GVYXA.js → chunk-QJXZ4SU7.js} +2 -2
- package/dist/cli/chunks/{chunk-K7K4TFJM.js → chunk-QNIL3D6E.js} +1 -1
- package/dist/cli/chunks/{chunk-D7PI4CYZ.js → chunk-QUQA4NNZ.js} +2 -2
- package/dist/cli/chunks/{chunk-N244P4MM.js → chunk-QZSNYXYC.js} +2 -2
- package/dist/cli/chunks/{chunk-NZGLDOU4.js → chunk-RA7HEY5G.js} +17 -17
- package/dist/cli/chunks/{chunk-HTLAPMTK.js → chunk-RBZWUWUG.js} +1 -1
- package/dist/cli/chunks/{chunk-3ISX5B77.js → chunk-RH3I4Q23.js} +2 -2
- package/dist/cli/chunks/{chunk-M2PSXKTG.js → chunk-ROXH622K.js} +2 -2
- package/dist/cli/chunks/{chunk-6WF2MOQB.js → chunk-RTAGNKCV.js} +2 -2
- package/dist/cli/chunks/{chunk-2L5VFVCG.js → chunk-RTFFD263.js} +1 -1
- package/dist/cli/chunks/{chunk-PWJZZCHJ.js → chunk-S574AFAT.js} +1 -1
- package/dist/cli/chunks/{chunk-SZKFT6CD.js → chunk-SA5FTDRS.js} +2 -2
- package/dist/cli/chunks/{chunk-AIBE3J4A.js → chunk-SHVTMMJB.js} +1 -1
- package/dist/cli/chunks/{chunk-MQIAN57O.js → chunk-SUGQZCNI.js} +2 -2
- package/dist/cli/chunks/{chunk-LOFA3U4X.js → chunk-T6CUKJHS.js} +1 -1
- package/dist/cli/chunks/{chunk-UWAUYDW4.js → chunk-T6SCQVWH.js} +2 -2
- package/dist/cli/chunks/{chunk-KUFC4DBX.js → chunk-TFA5UETW.js} +1 -1
- package/dist/cli/chunks/{chunk-OO7KJ34Y.js → chunk-TFJDJVPC.js} +2 -2
- package/dist/cli/chunks/chunk-TNVOINYC.js +12 -0
- package/dist/cli/chunks/{chunk-N3MM4Z33.js → chunk-TUFU3BAK.js} +2 -2
- package/dist/cli/chunks/{chunk-SJC7OKF3.js → chunk-TWH3ZL6B.js} +2 -2
- package/dist/cli/chunks/{chunk-VDKMBOUK.js → chunk-ULEVKOWQ.js} +1 -1
- package/dist/cli/chunks/{chunk-EWI37TJA.js → chunk-ULV5K4V5.js} +1 -1
- package/dist/cli/chunks/{chunk-SVILIQQQ.js → chunk-UNDPB5SS.js} +1 -1
- package/dist/cli/chunks/{chunk-K72J52JO.js → chunk-UQYDFT6I.js} +2 -2
- package/dist/cli/chunks/{chunk-5T4J3IPG.js → chunk-USPBUR6P.js} +2 -2
- package/dist/cli/chunks/{chunk-LKK3NIHC.js → chunk-UVWOIF6P.js} +1 -1
- package/dist/cli/chunks/{chunk-MKZQBBCU.js → chunk-UWDC3TZP.js} +2 -2
- package/dist/cli/chunks/{chunk-KGPAWNNR.js → chunk-VFFIMJWT.js} +1 -1
- package/dist/cli/chunks/{chunk-MIQBRVK2.js → chunk-VQM2TC2V.js} +1 -1
- package/dist/cli/chunks/{chunk-WIYWDON4.js → chunk-WNAFMYND.js} +2 -2
- package/dist/cli/chunks/{chunk-FDFJJFQT.js → chunk-X3YWLJGT.js} +2 -2
- package/dist/cli/chunks/{chunk-GS33ZRJH.js → chunk-X5R6SUWM.js} +2 -2
- package/dist/cli/chunks/{chunk-V5G3SMAJ.js → chunk-XKRJQIGP.js} +2 -2
- package/dist/cli/chunks/{chunk-5FNNCVXR.js → chunk-XLFYVBOD.js} +1 -1
- package/dist/cli/chunks/chunk-XOGBTPJI.js +65 -0
- package/dist/cli/chunks/{chunk-ICF5RPQU.js → chunk-XOYTW6LI.js} +2 -2
- package/dist/cli/chunks/{chunk-MWV4KPOB.js → chunk-Z3RPA3RD.js} +2 -2
- package/dist/cli/chunks/{chunk-QPMAXDJ2.js → chunk-ZBSEXVEI.js} +2 -2
- package/dist/cli/chunks/{chunk-JRBGHWAM.js → chunk-ZMCMSDXR.js} +2 -2
- package/dist/cli/chunks/{chunk-MQ5WMWUK.js → chunk-ZY4G7O7Y.js} +2 -2
- package/dist/cli/chunks/{ci-2BLMQNX3.js → ci-COQUVZH6.js} +2 -2
- package/dist/cli/chunks/{ci-output-XK4PPSN7.js → ci-output-KVUHUEOT.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-W7X4NPFE.js → circuit-breaker-O4JNXAYH.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-GLBLSYNJ.js → claude-flow-setup-J65U34NA.js} +2 -2
- package/dist/cli/chunks/client-VJNNIAMG.js +2 -0
- package/dist/cli/chunks/{cline-installer-7WX7DBGI.js → cline-installer-ZTG234Z2.js} +2 -2
- package/dist/cli/chunks/{code-SP3HAQWG.js → code-5GWPY4IX.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-44HH36UG.js → code-index-extractor-TWNKG4VS.js} +2 -2
- package/dist/cli/chunks/{codex-installer-LMXRWLPU.js → codex-installer-4TM4BLAE.js} +2 -2
- package/dist/cli/chunks/{completions-GL5FTZAN.js → completions-BBNHQXMV.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-CQMYGETL.js → complexity-analyzer-2SCI2VGH.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-CYVYS5B7.js → continuedev-installer-CTIORASU.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-M7XVII2A.js → copilot-installer-4R2V4IYB.js} +2 -2
- package/dist/cli/chunks/core-handlers-MV5CAR7O.js +2 -0
- package/dist/cli/chunks/{cost-tracker-S4ET4FH3.js → cost-tracker-KDBYQBKG.js} +2 -2
- package/dist/cli/chunks/{coverage-DFVSSQ4A.js → coverage-QQJQVDPZ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-ULY4NIML.js +2 -0
- package/dist/cli/chunks/{cursor-installer-KWDSQPQC.js → cursor-installer-5WEZCESZ.js} +2 -2
- package/dist/cli/chunks/{daemon-2HD54QVO.js → daemon-M4DKHEEA.js} +3 -3
- package/dist/cli/chunks/{daemon-CRX46BBO.js → daemon-Y7H3ZUXQ.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-SCP6WPZB.js → dag-attention-scheduler-SD2UIADT.js} +2 -2
- package/dist/cli/chunks/{detect-XS2GDCEX.js → detect-WONWUXFH.js} +2 -2
- package/dist/cli/chunks/{dist-node-U43MVQ3F.js → dist-node-Q5GQN2R6.js} +2 -2
- package/dist/cli/chunks/{domain-handler-HITMDULH.js → domain-handler-EMXE2XQW.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-TJF7DNI4.js → domain-transfer-QATUJJRP.js} +2 -2
- package/dist/cli/chunks/dream-PIGWXWE4.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-JKG33YZK.js → embed-and-insert-pattern-AAFHLBEJ.js} +2 -2
- package/dist/cli/chunks/{eval-NF5Y4W37.js → eval-73BDNLSK.js} +5 -5
- package/dist/cli/chunks/{experience-capture-middleware-VMMFYJ4D.js → experience-capture-middleware-YPAPVSYY.js} +3 -3
- package/dist/cli/chunks/{fast-paths-W2Q53IR2.js → fast-paths-33ZKMNYY.js} +2 -2
- package/dist/cli/chunks/{feature-flags-B4PBMQJO.js → feature-flags-F3DVW4ST.js} +2 -2
- package/dist/cli/chunks/{feature-flags-PVI7A4RE.js → feature-flags-QKO5YYDU.js} +2 -2
- package/dist/cli/chunks/{file-discovery-E4L3I33I.js → file-discovery-YYVZLRYD.js} +2 -2
- package/dist/cli/chunks/{fleet-LE5SHVLK.js → fleet-EJX6BXLR.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-MWWJBLOH.js → gnn-wrapper-TBNLYPTM.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-XOUVNPQK.js → heartbeat-handler-HPRTS6SI.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-5BBLZP6R.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-FMEBL5T4.js +2 -0
- package/dist/cli/chunks/hnsw-index-K2R24V4Z.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-W3T5ZDDP.js → hnsw-legacy-bridge-Z6V6TOF5.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-PX5JM3DG.js → hnswlib-node-LFVNGGCL.js} +2 -2
- package/dist/cli/chunks/hooks-GG2Z3BDB.js +285 -0
- package/dist/cli/chunks/hybrid-router-LVF6N345.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-VDFK3JYH.js → hypergraph-engine-X4Q2TTET.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-EUDGEF25.js → hypergraph-handler-6BZWV5PL.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-CCVVMGWE.js +2 -0
- package/dist/cli/chunks/{init-handler-MZEAJOZK.js → init-handler-EKUS7U6L.js} +6 -6
- package/dist/cli/chunks/init-wizard-KDPMO4G3.js +2 -0
- package/dist/cli/chunks/kernel-PBYNK5VA.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-ECBYWT6M.js → kilocode-installer-BWAVVSQG.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-KYFCSYTG.js → kiro-installer-UADO53E5.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-C7LVHHLN.js +2 -0
- package/dist/cli/chunks/{learning-4RAFMDSB.js → learning-HMUTCYQM.js} +3 -3
- package/dist/cli/chunks/{llm-router-JHBNLYP3.js → llm-router-453TBDUY.js} +4 -4
- package/dist/cli/chunks/llm-router-service-LMTRJCPP.js +2 -0
- package/dist/cli/chunks/{load-4DVQML7P.js → load-DBBSNP6T.js} +2 -2
- package/dist/cli/chunks/load-test-FHMZXTXD.js +2 -0
- package/dist/cli/chunks/{mcp-LCWMU4GZ.js → mcp-PK3SAKRF.js} +2 -2
- package/dist/cli/chunks/{memory-3DTJAURT.js → memory-63NHVBXS.js} +5 -5
- package/dist/cli/chunks/memory-backend-UZHPCQTB.js +2 -0
- package/dist/cli/chunks/memory-handlers-YIKKORRY.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-AVR5SZOO.js → multi-model-executor-HUGRXJ6D.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-DW2426QM.js → opencode-installer-A6IXNF26.js} +2 -2
- package/dist/cli/chunks/{orchestrator-AHF4W5GS.js → orchestrator-KDFYDNE3.js} +10 -10
- package/dist/cli/chunks/pattern-null-store-5PS4JN6V.js +2 -0
- package/dist/cli/chunks/{pipeline-N6THEWYE.js → pipeline-HSPRKEYE.js} +2 -2
- package/dist/cli/chunks/{platform-MRCFQF7X.js → platform-X74IBN2H.js} +2 -2
- package/dist/cli/chunks/{plugin-6YKUN5QM.js → plugin-KDJZ7VFD.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-2YPAHSVS.js → prime-radiant-advanced-wasm-2YZGKQE7.js} +2 -2
- package/dist/cli/chunks/protocol-executor-2GTGIOFD.js +2 -0
- package/dist/cli/chunks/{protocol-handler-Y2NMUKWQ.js → protocol-handler-I2SDHC7B.js} +2 -2
- package/dist/cli/chunks/{prove-DZUNWBFD.js → prove-JQJDNIZH.js} +2 -2
- package/dist/cli/chunks/provider-manager-VH6YTBB3.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-47JSO76G.js +2 -0
- package/dist/cli/chunks/{quality-AIFQMGUV.js → quality-2P7KHVY3.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-C7EDY7IS.js +2 -0
- package/dist/cli/chunks/{real-embeddings-5XL4LOG2.js → real-embeddings-L7NMMNDO.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-LV3WONT5.js → roocode-installer-LA4QN5AG.js} +2 -2
- package/dist/cli/chunks/router-7DVH66WB.js +2 -0
- package/dist/cli/chunks/routing-feedback-4I2MF235.js +2 -0
- package/dist/cli/chunks/{routing-handler-WSMUILGD.js → routing-handler-B5CDEZF3.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-BCEIDTW3.js → ruvector-commands-SOVCRLJ6.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-LRSPC6H3.js → rvf-dual-writer-M6WI2KFB.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-QHNX6353.js → rvf-migration-adapter-YDMZGPMA.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-SLNB3XPW.js → rvf-migration-coordinator-TFGQ5EO4.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-UN3ESMMW.js +2 -0
- package/dist/cli/chunks/safe-db-Y2ZXKWBK.js +2 -0
- package/dist/cli/chunks/schedule-PG2NVRGA.js +2 -0
- package/dist/cli/chunks/scheduler-CNH6WWU2.js +2 -0
- package/dist/cli/chunks/{security-CYY6TECQ.js → security-R3IXQXDA.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-U6JE4O6A.js → shared-rvf-adapter-GZX7LSQZ.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-PJBSNBRV.js → shared-rvf-dual-writer-YT7SJX7K.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-WWT4DRRP.js +2 -0
- package/dist/cli/chunks/{status-handler-W723LXX5.js → status-handler-7PZSPBHJ.js} +2 -2
- package/dist/cli/chunks/{structural-health-WZUPZBB5.js → structural-health-UMJS6IVR.js} +2 -2
- package/dist/cli/chunks/sync-HA5SLSBA.js +2 -0
- package/dist/cli/chunks/{sync-UA22CKUS.js → sync-UIREA3UG.js} +2 -2
- package/dist/cli/chunks/{task-handler-SENTEEXZ.js → task-handler-NV4HGMEG.js} +2 -2
- package/dist/cli/chunks/{task-handlers-FGVUZOCC.js → task-handlers-RXYWWOSU.js} +3 -3
- package/dist/cli/chunks/{test-Q37C3WI2.js → test-2Y6OXGEU.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-E6SPIBTH.js → test-scheduling-N55VFOYT.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-FW3ZVMRP.js +2 -0
- package/dist/cli/chunks/{token-usage-JHNWTZ7L.js → token-usage-YXKOB3U6.js} +2 -2
- package/dist/cli/chunks/{transformers-TEXDUVNI.js → transformers-GBRSFAVA.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-MWSS52H6.js → tree-sitter-wasm-parser-FJHMEHJS.js} +2 -2
- package/dist/cli/chunks/{types-YQRKHYH3.js → types-NVMRVSBH.js} +2 -2
- package/dist/cli/chunks/unified-memory-PXEJKKMN.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-M7OI5WUU.js +2 -0
- package/dist/cli/chunks/unified-persistence-WR4VDTAF.js +2 -0
- package/dist/cli/chunks/{upgrade-JKMEDURI.js → upgrade-L2OTYHD3.js} +2 -2
- package/dist/cli/chunks/{validate-URO7G6OE.js → validate-3NWRQYTP.js} +3 -3
- package/dist/cli/chunks/{validate-swarm-VZVJ56Z5.js → validate-swarm-MDURRWXK.js} +4 -4
- package/dist/cli/chunks/{vibium-G5WZILL6.js → vibium-SZX7RB4H.js} +2 -2
- package/dist/cli/chunks/visual-security-CKSZZHKG.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-LECH5T6H.js → web-tree-sitter-LGQT7JRD.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-2NPLC2YW.js → windsurf-installer-EYYGHPPX.js} +2 -2
- package/dist/cli/chunks/witness-chain-IOQX3XFG.js +2 -0
- package/dist/cli/chunks/{witness-chain-X347C36A.js → witness-chain-YYYA2CU3.js} +2 -2
- package/dist/cli/chunks/{workflow-V4ALYZ73.js → workflow-UD45FQAH.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-Z2ZJRWIN.js +2 -0
- package/dist/cli/chunks/wrappers-JXD3KNSR.js +2 -0
- package/dist/cli/commands/arena.d.ts +10 -0
- package/dist/cli/commands/arena.js +129 -0
- package/dist/cli/commands/hooks-handlers/command-hooks.js +38 -2
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +4 -0
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +66 -3
- package/dist/cli/commands/hooks-handlers/nesting-provenance.d.ts +27 -0
- package/dist/cli/commands/hooks-handlers/nesting-provenance.js +46 -0
- package/dist/cli/commands/hooks-handlers/task-hooks.js +22 -1
- package/dist/cli/commands/hooks-handlers/tool-loop-guardrail.d.ts +71 -0
- package/dist/cli/commands/hooks-handlers/tool-loop-guardrail.js +142 -0
- package/dist/cli/index.js +17 -0
- package/dist/contracts/verdicts.d.ts +297 -0
- package/dist/contracts/verdicts.js +178 -0
- package/dist/coordination/queen-types.d.ts +4 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +15 -6
- package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +12 -0
- 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 +3 -1
- package/dist/learning/aqe-learning-engine.js +32 -0
- package/dist/learning/experience-capture.d.ts +8 -0
- package/dist/learning/experience-capture.js +30 -0
- package/dist/learning/pattern-null-store.d.ts +32 -0
- package/dist/learning/pattern-null-store.js +77 -0
- package/dist/learning/pattern-store.d.ts +10 -0
- package/dist/learning/pattern-store.js +23 -0
- package/dist/mcp/bundle.js +400 -370
- package/dist/mcp/handlers/core-handlers.d.ts +20 -0
- package/dist/mcp/handlers/core-handlers.js +28 -0
- package/dist/mcp/handlers/domain-handler-configs.d.ts +3 -0
- package/dist/mcp/handlers/domain-handler-configs.js +22 -10
- package/dist/mcp/handlers/validation-pipeline-handler.d.ts +19 -0
- package/dist/mcp/handlers/validation-pipeline-handler.js +10 -0
- package/dist/migrations/20260611_add_pattern_nulls_table.d.ts +26 -0
- package/dist/migrations/20260611_add_pattern_nulls_table.js +63 -0
- package/dist/shared/llm/cost-tracker.js +6 -2
- package/dist/shared/llm/interfaces.d.ts +4 -0
- package/dist/shared/llm/providers/claude.js +16 -2
- package/dist/shared/reasoning-scrub.d.ts +29 -0
- package/dist/shared/reasoning-scrub.js +75 -0
- package/dist/validation/pipeline.d.ts +25 -0
- package/dist/validation/pipeline.js +28 -5
- package/dist/validation/steps/requirements.js +5 -0
- package/package.json +2 -1
- package/dist/cli/chunks/adapter-A62ETL5C.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MTCRAV6N.js +0 -2
- package/dist/cli/chunks/audit-42XG5JFB.js +0 -3
- package/dist/cli/chunks/base-KKEBUHZC.js +0 -2
- package/dist/cli/chunks/browser-workflow-XHYAJUB6.js +0 -2
- package/dist/cli/chunks/chunk-2TYO4VZH.js +0 -12
- package/dist/cli/chunks/chunk-HPYGMKZF.js +0 -2
- package/dist/cli/chunks/chunk-OKKTDHHF.js +0 -65
- package/dist/cli/chunks/chunk-PZ4PRZXN.js +0 -699
- package/dist/cli/chunks/client-C6CJOCRN.js +0 -2
- package/dist/cli/chunks/cross-domain-router-I3GEA5G6.js +0 -2
- package/dist/cli/chunks/dream-JCQMG2RL.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-FBHE4ZWH.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-EOOA4WXD.js +0 -2
- package/dist/cli/chunks/hnsw-index-TD3KRPND.js +0 -2
- package/dist/cli/chunks/hooks-RUPQVIUM.js +0 -250
- package/dist/cli/chunks/hybrid-router-64O6PXZ2.js +0 -2
- package/dist/cli/chunks/impact-analyzer-ITQHXGTM.js +0 -2
- package/dist/cli/chunks/init-wizard-DZ4IKGQI.js +0 -2
- package/dist/cli/chunks/kernel-HSVY4ZYK.js +0 -2
- package/dist/cli/chunks/knowledge-graph-H32TXXX4.js +0 -2
- package/dist/cli/chunks/llm-router-service-3FKESBUX.js +0 -2
- package/dist/cli/chunks/load-test-LKHURZGZ.js +0 -2
- package/dist/cli/chunks/memory-backend-XRJRZ6CK.js +0 -2
- package/dist/cli/chunks/memory-handlers-BL6E3XAK.js +0 -2
- package/dist/cli/chunks/protocol-executor-KABPB6PQ.js +0 -2
- package/dist/cli/chunks/provider-manager-U7EBM3FA.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-64O2OQIW.js +0 -2
- package/dist/cli/chunks/queen-coordinator-SV3COGIL.js +0 -2
- package/dist/cli/chunks/router-QARRPMED.js +0 -2
- package/dist/cli/chunks/routing-feedback-KD2JFTPK.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-4LLGF5AY.js +0 -2
- package/dist/cli/chunks/safe-db-RAX3H2P7.js +0 -2
- package/dist/cli/chunks/schedule-RQZGLLUY.js +0 -2
- package/dist/cli/chunks/scheduler-ACWTN4LN.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-SWNBO257.js +0 -2
- package/dist/cli/chunks/sync-ZLMF53TB.js +0 -2
- package/dist/cli/chunks/token-bootstrap-HQFFMZUF.js +0 -2
- package/dist/cli/chunks/unified-memory-QG3FDRKR.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-KOR4EOIG.js +0 -2
- package/dist/cli/chunks/unified-persistence-J6NIRYKM.js +0 -2
- package/dist/cli/chunks/visual-security-RAWV6YLN.js +0 -2
- package/dist/cli/chunks/witness-chain-ZO7FIM35.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-7SKITNIJ.js +0 -2
- package/dist/cli/chunks/wrappers-QXOPRPR4.js +0 -2
|
@@ -1,12 +0,0 @@
|
|
|
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.10.4");process.exit(0)}
|
|
2
|
-
import{a as N,b as G}from"./chunk-5Q3L4QEE.js";import{h as U}from"./chunk-AMW27FSS.js";import{a as W}from"./chunk-OKKTDHHF.js";import{e as T}from"./chunk-OIFJH7TF.js";import{b as v,c as x}from"./chunk-XBFEHVBO.js";import{b as k,d as q}from"./chunk-IYFMDIYZ.js";import{a as re}from"./chunk-HPYGMKZF.js";import{c as O}from"./chunk-VRE2EBFI.js";import{b,c as E}from"./chunk-UFKVKNAA.js";import{a as y,c as z}from"./chunk-2B6ETC7C.js";import{i as I}from"./chunk-PISW5HUX.js";import{S as ae,b as _}from"./chunk-D7IWGQTW.js";import{randomUUID as Y}from"crypto";z();q();import{randomUUID as se}from"node:crypto";var j=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",j,"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",j,"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",j,"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-QG3FDRKR.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 H=x(),V={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",H,"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",H,"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 V.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of V.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"}}};q();z();var B=x(),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",B,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=k(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",B,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return k(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",B,"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 i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],d=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),m=new Set,p=new Set;for(let u of d.slice(0,100))(u.endsWith(".ts")||u.endsWith(".tsx"))&&m.add("typescript"),(u.endsWith(".js")||u.endsWith(".jsx"))&&m.add("javascript"),u.endsWith(".py")&&m.add("python"),u.endsWith(".go")&&m.add("go"),u.endsWith(".rs")&&m.add("rust");let w=a(e,"package.json");if(n(w))try{let u=k(r(w,"utf-8")),f={...u.dependencies,...u.devDependencies};f.react&&p.add("react"),f.vue&&p.add("vue"),f.angular&&p.add("angular"),f.vitest&&p.add("vitest"),f.jest&&p.add("jest"),f.playwright&&p.add("playwright"),f.express&&p.add("express"),f.fastify&&p.add("fastify")}catch(u){console.debug("[PretrainBridge] package.json parse error:",u instanceof Error?u.message:u)}let g={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(m),frameworks:Array.from(p),patterns:[],complexity:d.length>500?3:d.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,g),g}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 D=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 J(l){return new D(l)}re();ae();var M=O.create("experience-capture"),K={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},oe=new Set(Object.keys(K));function X(l){return typeof l=="string"&&oe.has(l)}function ce(l){if(X(l))return K[l]}var le={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:T,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},Q=class{constructor(e,t,i,n={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...le,...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;setWitnessChain(e){this.witnessChain=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()}-${I().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};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.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let r=t.testOutcome??i.metadata?.testOutcome;if(r&&X(r)&&(i.testOutcome=r,i.reward=ce(r)),this.witnessChain&&_().useWitnessChain)try{let s=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=s.hash}catch(s){M.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:s instanceof Error?s.message:String(s)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward===void 0||i.reward>0;if(i.success&&i.quality>=this.config.minQualityForPatternExtraction&&a){let s=await this.extractPattern(i);(s.newPattern||s.reinforced)&&(i.patterns=[s.patternId])}return this.emitExperienceCaptured(i),b(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 M.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=await this.patternStore.search(e.task,{limit:1,domain:e.domain,useVectorSearch:!0});if(t.success&&t.value.length>0){let r=t.value[0];if(r.similarity>=this.config.similarityThreshold){let a=await this.patternStore.recordUsage(r.pattern.id,e.success),s=await this.patternStore.get(r.pattern.id),o=!1;return s&&s.tier==="short-term"&&s.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(r.pattern.id)).success&&(o=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${r.pattern.id} (${s.usageCount} uses)`)),{newPattern:!1,patternId:r.pattern.id,reinforced:a.success,promoted:o}}}let i=this.experienceToPatternOptions(e),n=await this.patternStore.create(i);return n.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(n.value.id,e.success),{newPattern:!0,patternId:n.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}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,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),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"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}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){M.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 Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...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 N(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=U(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-PJBSNBRV.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=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-X347C36A.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-X347C36A.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-J6NIRYKM.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{isCrossDomainTransferEnabled:e}=await import("./feature-flags-PVI7A4RE.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-TJF7DNI4.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=J({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});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=this.enhanceRoutingWithPatterns(i.value,t.value);return b(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 b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}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()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(o=>{let d=o.pattern;return`[Pattern: ${d.name}] ${d.description} (confidence: ${(d.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,d)=>o+d.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}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()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0}));let s={id:a||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.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 i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],d=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),m=new Set,p=new Set;for(let g of d.slice(0,100))(g.endsWith(".ts")||g.endsWith(".tsx"))&&m.add("typescript"),(g.endsWith(".js")||g.endsWith(".jsx"))&&m.add("javascript"),g.endsWith(".py")&&m.add("python"),g.endsWith(".go")&&m.add("go"),g.endsWith(".rs")&&m.add("rust");let w=a(e,"package.json");if(n(w))try{let g=k(r(w,"utf-8")),u={...g.dependencies,...g.devDependencies};u.react&&p.add("react"),u.vue&&p.add("vue"),u.vitest&&p.add("vitest"),u.jest&&p.add("jest"),u.playwright&&p.add("playwright")}catch(g){console.debug("[AQELearningEngine] package.json parse failed:",g instanceof Error?g.message:g)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(m),frameworks:Array.from(p),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}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...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(c=>c.tokenMetrics.costUsd)),o=h(n.map(c=>c.tokenMetrics.costUsd)),d=h(i.map(c=>c.tokenMetrics.savingsUsd)),m=h(n.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&m<=d*1.05){let c=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:F(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let p=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-p)<.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:F(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let u=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-u),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:F(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),A=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(A>C*1.2&&C>0){let c=Math.min(1,(A-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${A.toFixed(0)}ms`,confidence:F(c),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(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function F(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.10.4");process.exit(0)}
|
|
2
|
-
import{a as e,b as g,e as r}from"./chunk-VRE2EBFI.js";import{c as o}from"./chunk-SVILIQQQ.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
|
|
@@ -1,65 +0,0 @@
|
|
|
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.10.4");process.exit(0)}
|
|
2
|
-
import{a as ne}from"./chunk-KGPAWNNR.js";import{d as B,e as j,f as re,g as W}from"./chunk-OIFJH7TF.js";import{g as rt,h as nt}from"./chunk-MQIAN57O.js";import{b as xe,c as et}from"./chunk-U27GVYXA.js";import{a as Ce,d as De,e as tt,f as Fe}from"./chunk-KWZEBHAP.js";import{b as v,c as w}from"./chunk-UFKVKNAA.js";import{a as y,b as Ae,c as Te}from"./chunk-2B6ETC7C.js";import{i as C}from"./chunk-PISW5HUX.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-D7IWGQTW.js";import{a as Ee,d as J,f as Ze,g as Re}from"./chunk-SVILIQQQ.js";var V=J(S=>{var dt=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ft=Object.prototype.hasOwnProperty;function le(n,e){return ft.call(n,e)}S.hasOwnProperty=le;function Ue(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=Ue;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=pt;function mt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=mt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function gt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=gt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function yt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=yt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=Ue(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function ke(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
|
|
3
|
-
`)}var vt=(function(n){dt(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,ke(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=ke(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=vt});var he=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var b=V();g.JsonPatchError=b.PatchError;g.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=Y;function O(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,d=void 0,f=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(f=u[l],f&&f.indexOf("~")!=-1&&(f=b.unescapePathComponent(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[f]===void 0?d=u.slice(0,l).join("/"):l==h-1&&(d=e.path),d!==void 0&&p(e,0,n,d)),l++,Array.isArray(o)){if(f==="-")f=o.length;else{if(t&&!b.isInteger(f))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(f)&&(f=~~f)}if(l>=h){if(t&&e.op==="add"&&f>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=wt[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[f],t&&l<h&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function qe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=qe;function Pt(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=Pt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=K;function Qe(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)qe(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=Qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var ze=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),St=he(),fe=new WeakMap,bt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Et=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Rt(n){return fe.get(n)}function At(n,e){return n.observers.get(e)}function Tt(n,e){n.observers.delete(e.callback)}function xt(n,e){e.unobserve()}k.unobserve=xt;function Ct(n,e){var t=[],r,i=Rt(n);if(!i)i=new bt(n),fe.set(n,i);else{var s=At(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Tt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Et(e,r)),r}k.observe=Ct;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&St.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof h=="object"&&h!=null&&typeof d=="object"&&d!=null&&Array.isArray(h)===Array.isArray(d)?pe(h,d,t,r+"/"+P.escapePathComponent(l),i):h!==d&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function Dt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Dt});var $e=J(I=>{var Ft=he();Object.assign(I,Ft);var Ot=ze();Object.assign(I,Ot);var Z=V();I.JsonPatchError=Z.PatchError;I.deepClone=Z._deepClone;I.escapePathComponent=Z.escapePathComponent;I.unescapePathComponent=Z.unescapePathComponent});et();Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-SWNBO257.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),d=h?.embedding;if(!d||d.length!==u.length)continue;let f=0,p=0;for(let R=0;R<u.length;R++)f+=u[R]*d[R],p+=d[R]*d[R];if(p=Math.sqrt(p),p===0)continue;let m=f/(o*p),E=this.calculateReuseInfo(h,m);s.push({pattern:h,score:m,matchType:"vector",similarity:m,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};Fe();Te();F();function st(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function at(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=st(n,e.field);return at(t,e.operator,e.value)}default:return!0}}function Oe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var _e=1e4,Ne=2166136261;function He(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function ot(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function ct(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function lt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ut(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function ht(n,e,t){return 1-ut(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??_e,this.baseSeed=e?.seed??Ne,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=He(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=ct(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return lt([r,i])}similarity(e,t){return ht(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??_e,this.baseSeed=e?.seed??Ne,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=He(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ot(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Me(n){return new se(n)}function Le(n){return q()?new ie(n):null}var $=Ze($e(),1),It=`
|
|
4
|
-
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
|
-
id TEXT PRIMARY KEY,
|
|
6
|
-
pattern_id TEXT NOT NULL,
|
|
7
|
-
version INTEGER NOT NULL,
|
|
8
|
-
timestamp INTEGER NOT NULL,
|
|
9
|
-
type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
|
|
10
|
-
patch TEXT NOT NULL DEFAULT '[]',
|
|
11
|
-
reverse_patch TEXT NOT NULL DEFAULT '[]',
|
|
12
|
-
metadata TEXT
|
|
13
|
-
);
|
|
14
|
-
CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
|
|
15
|
-
ON pattern_deltas (pattern_id, version);
|
|
16
|
-
CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
|
|
17
|
-
ON pattern_deltas (timestamp);
|
|
18
|
-
`;function Je(n,e){let t=$.compare(n,e),r=$.compare(e,n);return{forward:t,reverse:r}}function _t(n,e){let t=JSON.parse(JSON.stringify(n));return $.applyPatch(t,e).newDocument}function Be(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ee=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(It),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
|
|
19
|
-
INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
|
|
20
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
21
|
-
`)),this.prepared.set("getHistory",this.db.prepare(`
|
|
22
|
-
SELECT * FROM pattern_deltas
|
|
23
|
-
WHERE pattern_id = ?
|
|
24
|
-
ORDER BY version ASC
|
|
25
|
-
`)),this.prepared.set("currentVersion",this.db.prepare(`
|
|
26
|
-
SELECT MAX(version) as max_version FROM pattern_deltas
|
|
27
|
-
WHERE pattern_id = ?
|
|
28
|
-
`)),this.prepared.set("incrementalSync",this.db.prepare(`
|
|
29
|
-
SELECT * FROM pattern_deltas
|
|
30
|
-
WHERE timestamp > ?
|
|
31
|
-
ORDER BY timestamp ASC
|
|
32
|
-
`)),this.prepared.set("countForPattern",this.db.prepare(`
|
|
33
|
-
SELECT COUNT(*) as cnt FROM pattern_deltas
|
|
34
|
-
WHERE pattern_id = ?
|
|
35
|
-
`)),this.prepared.set("deleteOldest",this.db.prepare(`
|
|
36
|
-
DELETE FROM pattern_deltas
|
|
37
|
-
WHERE pattern_id = ? AND version IN (
|
|
38
|
-
SELECT version FROM pattern_deltas
|
|
39
|
-
WHERE pattern_id = ?
|
|
40
|
-
ORDER BY version ASC
|
|
41
|
-
LIMIT ?
|
|
42
|
-
)
|
|
43
|
-
`))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:C(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Je(t,r),u={id:C(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:c,metadata:i};return this.insertEvent(u),this.enforceRetention(e),u}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:c,reverse:u}=Je(a,s),o={id:C(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:u,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Be)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Be)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=_t(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
|
|
44
|
-
WHERE pattern_id = ? AND version != 0 AND id IN (
|
|
45
|
-
SELECT id FROM pattern_deltas
|
|
46
|
-
WHERE pattern_id = ? AND version != 0
|
|
47
|
-
ORDER BY version ASC
|
|
48
|
-
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};F();var Nt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Nt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function je(n){return H()?new me(n):null}F();var Ht=128,Mt=8,Lt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ht,this.beta=e?.beta??Mt,this.maxPatterns=e?.maxPatterns??Lt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var kt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Xe=1-_;function Ut(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Ut(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Xe)return new Float32Array(e);let r=Xe/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...kt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),d=Math.tanh(.3*(o+.1)),f=l+h/2,p=new Float32Array(r);p[0]=d*Math.cos(f),p[1]=d*Math.sin(f);let m=s.get(u);if(m&&m.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:m?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ge(n){return Qt()?new ye(n):null}function Qt(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ge(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ve(n){return new ve(n)}var we=null;function Ye(){return we||(we=Me({dimensions:1e4})),we}var Pe;function zt(){return Pe===void 0&&(Pe=Le()),Pe}var U=null,Se=0;function Ke(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-W3T5ZDDP.js"),{HnswAdapter:c}=await import("./hnsw-adapter-EOOA4WXD.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-TD3KRPND.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=je()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ye().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=zt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ke(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ke(e.length);if(h.getPatternCount()>0){let d=h.recall(new Float32Array(e));if(d&&d.similarity>.98){let f=d.metadata.id,p=await this.get(f);if(p&&this.matchesFilters(p,t)){let m=this.calculateReuseInfo(p,d.similarity);s.push({pattern:p,score:d.similarity,matchType:"vector",similarity:d.similarity,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let d=await h.search(e,i*2);for(let f of d){let p=await this.get(f.key);if(p&&this.matchesFilters(p,t)){let m=this.calculateReuseInfo(p,f.score);s.push({pattern:p,score:f.score,matchType:"vector",similarity:f.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let d=new Map(h.map(p=>[p.id,p.ftsScore])),f=new Set(s.map(p=>p.pattern.id));for(let p of s){let m=d.get(p.pattern.id);m!==void 0&&(p.score=.75*p.score+.25*m)}for(let p of h){if(f.has(p.id))continue;let m=await this.get(p.id);if(m&&this.matchesFilters(m,t)){let E=this.calculateReuseInfo(m,p.ftsScore);s.push({pattern:m,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),d=new Set(s.map(f=>f.pattern.id));for(let f of h)d.has(f.pattern.id)||s.push(f)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let d=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),f=c-d,p=Math.pow(.5,f/a),m=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*m)}s.sort((h,d)=>d.score-h.score);let u=s;t.filter&&(u=Oe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ye(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(f=>this.hdcCache.has(f)).map(f=>({id:f,similarity:u.similarity(o.vector,this.hdcCache.get(f))}));l.sort((f,p)=>p.similarity-f.similarity);let h=l.map(f=>f.id),d=c.filter(f=>!this.hdcCache.has(f));c=[...h,...d]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),d=o.description.toLowerCase();h.includes(s)&&(l+=.5),d.includes(s)&&(s.length/d.length>.3?l+=.5:l+=.3);for(let f of o.context.tags)if(f.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,d=e.successRate,f=Math.min(e.reuseCount/10,1),p=o?h*.4+d*.4+f*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},m={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,m,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let d=re(h);return d.meetsUsageCriteria&&d.meetsQualityCriteria&&d.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,d=s.usageCount===0&&o>1440*60*1e3;(l&&h||d)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ve({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function qr(n,e){try{if(D().useRVFPatternStore&&De()){let{existsSync:r}=Ee("fs"),{join:i}=Ee("path"),s=process.env.AQE_PROJECT_ROOT??xe(),a=i(s,".agentic-qe"),c=i(a,"patterns.rvf");if(r(a)){let u={...X,...e},o=!1;try{let{getSharedRvfAdapter:l}=(nt(),Re(rt)),h=l(a,u.embeddingDimension);if(h){o=!0;let d=new Q(()=>h,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}catch{}if(!o){let l=new Q((h,d)=>{let{openRvfStore:f}=(Fe(),Re(tt)),p=()=>{try{return f(h)}catch{return null}},m=p();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return Ce(h,d)}catch(E){if(m=p(),m&&m.dimension()===d)return m;throw E}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{qr as a};
|
|
50
|
-
/*! Bundled license information:
|
|
51
|
-
|
|
52
|
-
fast-json-patch/commonjs/helpers.js:
|
|
53
|
-
(*!
|
|
54
|
-
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
55
|
-
* (c) 2017-2022 Joachim Wester
|
|
56
|
-
* MIT licensed
|
|
57
|
-
*)
|
|
58
|
-
|
|
59
|
-
fast-json-patch/commonjs/duplex.js:
|
|
60
|
-
(*!
|
|
61
|
-
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
62
|
-
* (c) 2017-2021 Joachim Wester
|
|
63
|
-
* MIT license
|
|
64
|
-
*)
|
|
65
|
-
*/
|