agentic-qe 3.9.12 → 3.9.13
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-coverage-specialist.md +1 -1
- package/.claude/agents/v3/qe-fleet-commander.md +1 -1
- package/.claude/agents/v3/qe-pentest-validator.md +4 -2
- package/.claude/agents/v3/qe-queen-coordinator.md +1 -1
- package/.claude/agents/v3/qe-risk-assessor.md +1 -1
- package/.claude/agents/v3/qe-root-cause-analyzer.md +1 -1
- package/.claude/agents/v3/qe-security-auditor.md +4 -2
- package/.claude/agents/v3/qe-security-scanner.md +3 -1
- package/.claude/agents/v3/qe-test-architect.md +1 -1
- package/.claude/commands/aqe-costs.md +6 -6
- package/.claude/skills/.validation/schemas/skill-eval.schema.json +3 -0
- package/.claude/skills/.validation/test-data/sample-output.json +1 -1
- package/.claude/skills/a11y-ally/SKILL.md +1 -1
- package/.claude/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
- package/.claude/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -2
- package/.claude/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
- package/.claude/skills/contract-testing/evals/contract-testing.yaml +2 -2
- package/.claude/skills/database-testing/evals/database-testing.yaml +2 -2
- package/.claude/skills/localization-testing/evals/localization-testing.yaml +1 -1
- package/.claude/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
- package/.claude/skills/performance-testing/evals/performance-testing.yaml +1 -1
- package/.claude/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/.claude/skills/testability-scoring/evals/testability-scoring.yaml +2 -2
- package/CHANGELOG.md +21 -0
- package/assets/agents/v3/qe-coverage-specialist.md +1 -1
- package/assets/agents/v3/qe-fleet-commander.md +1 -1
- package/assets/agents/v3/qe-pentest-validator.md +4 -2
- package/assets/agents/v3/qe-queen-coordinator.md +1 -1
- package/assets/agents/v3/qe-risk-assessor.md +1 -1
- package/assets/agents/v3/qe-root-cause-analyzer.md +1 -1
- package/assets/agents/v3/qe-security-auditor.md +4 -2
- package/assets/agents/v3/qe-security-scanner.md +3 -1
- package/assets/agents/v3/qe-test-architect.md +1 -1
- package/assets/skills/.validation/schemas/skill-eval.schema.json +3 -0
- package/assets/skills/.validation/test-data/sample-output.json +1 -1
- package/assets/skills/a11y-ally/SKILL.md +1 -1
- package/assets/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
- package/assets/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -2
- package/assets/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
- package/assets/skills/contract-testing/evals/contract-testing.yaml +2 -2
- package/assets/skills/database-testing/evals/database-testing.yaml +2 -2
- package/assets/skills/localization-testing/evals/localization-testing.yaml +1 -1
- package/assets/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
- package/assets/skills/performance-testing/evals/performance-testing.yaml +1 -1
- package/assets/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/assets/skills/testability-scoring/evals/testability-scoring.yaml +2 -2
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-VP3WBXE5.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-LB7XIYUI.js → agent-booster-wasm-3RBPTJAU.js} +2 -2
- package/dist/cli/chunks/{agent-handler-VVLNITPB.js → agent-handler-XV45GCWC.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-QAJOHQYI.js → agent-memory-branch-V6EXWWMY.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-ASPPEOKQ.js +2 -0
- package/dist/cli/chunks/{audit-BJIGY6LA.js → audit-WXFI4AC4.js} +2 -2
- package/dist/cli/chunks/base-SIAOYPTD.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-X6P6KJS6.js → better-sqlite3-23MIVVHF.js} +2 -2
- package/dist/cli/chunks/{brain-handler-7FGHAVL5.js → brain-handler-LQUMAACV.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-YXYZMQ4P.js → branch-enumerator-HE37VX7G.js} +2 -2
- package/dist/cli/chunks/{browser-WC2JTT32.js → browser-3VG5M7WM.js} +2 -2
- package/dist/cli/chunks/browser-workflow-BG3M3RZU.js +2 -0
- package/dist/cli/chunks/{chunk-NXZDG2ED.js → chunk-2RTGP76Y.js} +2 -2
- package/dist/cli/chunks/{chunk-LJTRN6ZE.js → chunk-3AOWTHLS.js} +2 -2
- package/dist/cli/chunks/{chunk-HBQRFR7Q.js → chunk-3I6KWFJT.js} +2 -2
- package/dist/cli/chunks/{chunk-4LEYR7AH.js → chunk-3IJ4NRJF.js} +2 -2
- package/dist/cli/chunks/{chunk-MBISKOYR.js → chunk-3RM2VNYG.js} +2 -2
- package/dist/cli/chunks/{chunk-PBZLLYB3.js → chunk-4MZZMWF6.js} +1 -1
- package/dist/cli/chunks/{chunk-XZYW2RNI.js → chunk-4PCHU2X7.js} +1 -1
- package/dist/cli/chunks/{chunk-W26THOMZ.js → chunk-4VETZICF.js} +1 -1
- package/dist/cli/chunks/{chunk-XEHMWICD.js → chunk-4WJ3BHCN.js} +3 -3
- package/dist/cli/chunks/{chunk-OOV2W3PM.js → chunk-54A2LVKM.js} +2 -2
- package/dist/cli/chunks/{chunk-7WP5HEJQ.js → chunk-5TDHUYYF.js} +2 -2
- package/dist/cli/chunks/{chunk-HJL4CRV6.js → chunk-67TMNSO3.js} +1 -1
- package/dist/cli/chunks/{chunk-IQAEANMY.js → chunk-6GYMFSPA.js} +2 -2
- package/dist/cli/chunks/{chunk-PVYTP7CC.js → chunk-6HSHLSGU.js} +2 -2
- package/dist/cli/chunks/{chunk-PJENW5A2.js → chunk-6LDRSG7C.js} +2 -2
- package/dist/cli/chunks/{chunk-PGKGFKSS.js → chunk-77GZ7LXL.js} +2 -2
- package/dist/cli/chunks/{chunk-AUWWCPVO.js → chunk-7HX2PMBB.js} +2 -2
- package/dist/cli/chunks/{chunk-OAWDBVKN.js → chunk-AEKTVLLF.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLDOPUZY.js → chunk-AOTEEGQA.js} +2 -2
- package/dist/cli/chunks/{chunk-2FW56URL.js → chunk-APQYMAKG.js} +4 -4
- package/dist/cli/chunks/{chunk-OSGQFRT2.js → chunk-AV23XNRL.js} +2 -2
- package/dist/cli/chunks/{chunk-AZCTNUUN.js → chunk-AXDGBI4Y.js} +1 -1
- package/dist/cli/chunks/{chunk-WKORFEXG.js → chunk-AZPDX4KS.js} +2 -2
- package/dist/cli/chunks/{chunk-RUD4F7IT.js → chunk-BE2DYHUB.js} +2 -2
- package/dist/cli/chunks/{chunk-K5TK4HNR.js → chunk-BSTCXDVH.js} +1 -1
- package/dist/cli/chunks/{chunk-LURKOKOG.js → chunk-BUIMIUJA.js} +1 -1
- package/dist/cli/chunks/{chunk-V7LIKEGA.js → chunk-CF5EJGOV.js} +2 -2
- package/dist/cli/chunks/{chunk-FZY2AFLS.js → chunk-CPRYUCPC.js} +1 -1
- package/dist/cli/chunks/{chunk-WJGATF2P.js → chunk-D22MEX2U.js} +2 -2
- package/dist/cli/chunks/{chunk-STRHCEUL.js → chunk-DHYJMGKC.js} +1 -1
- package/dist/cli/chunks/{chunk-JTE3QBBI.js → chunk-DY5JRJXV.js} +3 -3
- package/dist/cli/chunks/{chunk-FCUJTBDG.js → chunk-E7P6GAD7.js} +2 -2
- package/dist/cli/chunks/{chunk-I4JO4LD3.js → chunk-EBQUXPIG.js} +2 -2
- package/dist/cli/chunks/{chunk-ZXLAY3BL.js → chunk-EC2CI3ZC.js} +2 -2
- package/dist/cli/chunks/{chunk-FT3BXL44.js → chunk-ERGY45RL.js} +1 -1
- package/dist/cli/chunks/{chunk-C2ICHYJH.js → chunk-ES6CEZG2.js} +1 -1
- package/dist/cli/chunks/{chunk-AAHBVTUJ.js → chunk-F74IVEON.js} +2 -2
- package/dist/cli/chunks/{chunk-MJY6FD6N.js → chunk-FEGITTAE.js} +1 -1
- package/dist/cli/chunks/{chunk-A3YIGC75.js → chunk-FHWDVN65.js} +2 -2
- package/dist/cli/chunks/{chunk-OZNBJZTT.js → chunk-FLML5IT7.js} +2 -2
- package/dist/cli/chunks/{chunk-ZZ2E6WS6.js → chunk-FS4TPAAA.js} +1 -1
- package/dist/cli/chunks/{chunk-ONF657XE.js → chunk-GHAEDZDE.js} +2 -2
- package/dist/cli/chunks/{chunk-4UIACR5V.js → chunk-GKRKCJ6D.js} +2 -2
- package/dist/cli/chunks/{chunk-PMRJHQIW.js → chunk-H53V7GI3.js} +1 -1
- package/dist/cli/chunks/{chunk-5F2CEYZG.js → chunk-HEHGQM2H.js} +23 -23
- package/dist/cli/chunks/{chunk-XTGVTVLN.js → chunk-HHRUXDLT.js} +2 -2
- package/dist/cli/chunks/{chunk-FE2R7DOJ.js → chunk-HJHFGPGP.js} +2 -2
- package/dist/cli/chunks/{chunk-UGCPQGQV.js → chunk-HRD7LL7Q.js} +2 -2
- package/dist/cli/chunks/{chunk-R2E73QTH.js → chunk-HXLAXSEM.js} +2 -2
- package/dist/cli/chunks/{chunk-4HTPZ67G.js → chunk-I6O4MVEY.js} +4 -4
- package/dist/cli/chunks/{chunk-CX5TTKTB.js → chunk-IQGVQBVS.js} +1 -1
- package/dist/cli/chunks/{chunk-AXJTWYCF.js → chunk-JOCR5TWI.js} +2 -2
- package/dist/cli/chunks/chunk-JV7HKHQS.js +2 -0
- package/dist/cli/chunks/{chunk-QRP7WPSO.js → chunk-KULWZMVC.js} +3 -3
- package/dist/cli/chunks/{chunk-B5OL6C4A.js → chunk-LHZLH6I4.js} +2 -2
- package/dist/cli/chunks/{chunk-FHNDCWXZ.js → chunk-LRHJOYKY.js} +3 -3
- package/dist/cli/chunks/{chunk-E7WWAJK5.js → chunk-MXT7YUOZ.js} +2 -2
- package/dist/cli/chunks/{chunk-DQ3ZEAMM.js → chunk-OBDM6OJL.js} +1 -1
- package/dist/cli/chunks/{chunk-E6MBYXCI.js → chunk-OGHIQCJU.js} +2 -2
- package/dist/cli/chunks/{chunk-VC4X36JJ.js → chunk-OHG6SNIA.js} +2 -2
- package/dist/cli/chunks/{chunk-YNHB6NGD.js → chunk-OJGR56BP.js} +2 -2
- package/dist/cli/chunks/{chunk-FYVNVHMI.js → chunk-OKCI6BNZ.js} +2 -2
- package/dist/cli/chunks/{chunk-T5WF5HBA.js → chunk-OM7A3YC3.js} +2 -2
- package/dist/cli/chunks/{chunk-JDUJCNS5.js → chunk-OP54A7C6.js} +2 -2
- package/dist/cli/chunks/{chunk-MT4ZZUPF.js → chunk-OUNZPHTA.js} +1 -1
- package/dist/cli/chunks/{chunk-SILMLIWR.js → chunk-Q3MQYATA.js} +2 -2
- package/dist/cli/chunks/{chunk-6ZTKAP4X.js → chunk-Q7TWE55T.js} +3 -3
- package/dist/cli/chunks/{chunk-XD7W2BE6.js → chunk-QHCOAG7D.js} +1 -1
- package/dist/cli/chunks/{chunk-M7QYRRRS.js → chunk-QIE76ERL.js} +1 -1
- package/dist/cli/chunks/{chunk-E6HTC3I2.js → chunk-QKTB5FZP.js} +2 -2
- package/dist/cli/chunks/{chunk-QANDN6CW.js → chunk-QNUVC6OX.js} +1 -1
- package/dist/cli/chunks/{chunk-7IJIOZHW.js → chunk-R4B2B6MZ.js} +2 -2
- package/dist/cli/chunks/{chunk-K2UQR3NX.js → chunk-RMNZSGTE.js} +2 -2
- package/dist/cli/chunks/{chunk-WNM64IA6.js → chunk-RURYOWWU.js} +1 -1
- package/dist/cli/chunks/{chunk-XQHTGKXD.js → chunk-RYPUA6E2.js} +2 -2
- package/dist/cli/chunks/{chunk-4GGDA6PF.js → chunk-SI7AQK7I.js} +2 -2
- package/dist/cli/chunks/{chunk-DDNFBXJJ.js → chunk-SL66MHDM.js} +1 -1
- package/dist/cli/chunks/{chunk-BC6LRNKU.js → chunk-SSZMISGC.js} +2 -2
- package/dist/cli/chunks/{chunk-JAVMUPY3.js → chunk-TNQBHQFH.js} +2 -2
- package/dist/cli/chunks/{chunk-CGXLVTVK.js → chunk-TOS3PI5Q.js} +1 -1
- package/dist/cli/chunks/{chunk-I6J7AYIL.js → chunk-TPTKR5ZO.js} +1 -1
- package/dist/cli/chunks/{chunk-UOD76Y2C.js → chunk-TRJRRJV3.js} +1 -1
- package/dist/cli/chunks/{chunk-WZYG4SKQ.js → chunk-TU3JIH3U.js} +5 -5
- package/dist/cli/chunks/{chunk-NVMJS347.js → chunk-TVASP2E6.js} +2 -2
- package/dist/cli/chunks/{chunk-45SNY726.js → chunk-TWRGM5TY.js} +2 -2
- package/dist/cli/chunks/{chunk-FYJSJLTP.js → chunk-UCCNB75R.js} +2 -2
- package/dist/cli/chunks/{chunk-ESYALM4A.js → chunk-UDIRBCZW.js} +1 -1
- package/dist/cli/chunks/{chunk-Q3BVPPHB.js → chunk-V2CV6J2A.js} +2 -2
- package/dist/cli/chunks/{chunk-6DDT5OHC.js → chunk-V6UODTBP.js} +1 -1
- package/dist/cli/chunks/{chunk-WEMOVPQS.js → chunk-VCJP7HQG.js} +2 -2
- package/dist/cli/chunks/chunk-VHSDZEYF.js +2 -0
- package/dist/cli/chunks/{chunk-SVEC7C63.js → chunk-VJN7NQGI.js} +9 -9
- package/dist/cli/chunks/{chunk-X7IRGKAM.js → chunk-VLZBQ3XN.js} +2 -2
- package/dist/cli/chunks/{chunk-ALW3NHF2.js → chunk-VU7ENCSU.js} +2 -2
- package/dist/cli/chunks/{chunk-FGE33JCO.js → chunk-VVVIRGO7.js} +2 -2
- package/dist/cli/chunks/chunk-VWEGO7BY.js +2 -0
- package/dist/cli/chunks/{chunk-LNHOWUSG.js → chunk-W2YCNX4O.js} +2 -2
- package/dist/cli/chunks/{chunk-TKV2X6EP.js → chunk-W6LEOFA4.js} +2 -2
- package/dist/cli/chunks/{chunk-RLVQDFZ2.js → chunk-WQGP5ULD.js} +2 -2
- package/dist/cli/chunks/{chunk-Q2JAC625.js → chunk-WQIB5ERQ.js} +2 -2
- package/dist/cli/chunks/{chunk-KYO7ME7T.js → chunk-WVWB7K6H.js} +1 -1
- package/dist/cli/chunks/{chunk-GK4QGLN6.js → chunk-X3UVXJIK.js} +2 -2
- package/dist/cli/chunks/{chunk-2BDTKGEH.js → chunk-XV42SKJD.js} +2 -2
- package/dist/cli/chunks/{chunk-NWL7UQPY.js → chunk-XXQYSDLV.js} +2 -2
- package/dist/cli/chunks/chunk-Y2ONHWXI.js +2 -0
- package/dist/cli/chunks/{chunk-52GDG6LU.js → chunk-Y7YSJD4I.js} +2 -2
- package/dist/cli/chunks/{chunk-CBD772DQ.js → chunk-YBKSENTJ.js} +3 -3
- package/dist/cli/chunks/{chunk-ZYAIIW3U.js → chunk-YCQ2GHFH.js} +2 -2
- package/dist/cli/chunks/{chunk-6Q7F4HBV.js → chunk-YCTGWMCP.js} +3 -3
- package/dist/cli/chunks/{chunk-R7RGOZ3H.js → chunk-YYQVSVBO.js} +2 -2
- package/dist/cli/chunks/{chunk-H6T57HMP.js → chunk-Z6F4GRXY.js} +1 -1
- package/dist/cli/chunks/chunk-ZN7KPIJW.js +2 -0
- package/dist/cli/chunks/{chunk-GB4LEEYS.js → chunk-ZS5BM2EE.js} +2 -2
- package/dist/cli/chunks/{chunk-WMVMFBMH.js → chunk-ZUW3KVML.js} +2 -2
- package/dist/cli/chunks/chunk-ZXJNX5D2.js +2 -0
- package/dist/cli/chunks/{ci-44MZEXKJ.js → ci-FEEIAOQN.js} +2 -2
- package/dist/cli/chunks/{ci-output-GZOZ3VUQ.js → ci-output-2WMUTORB.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-5BOXU65J.js → circuit-breaker-MFEE23XA.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-T5R4BHVO.js → claude-flow-setup-6D655INK.js} +2 -2
- package/dist/cli/chunks/client-LMOHUGOA.js +2 -0
- package/dist/cli/chunks/{cline-installer-LLROFJKC.js → cline-installer-5PIYMPAG.js} +2 -2
- package/dist/cli/chunks/{code-ATTTFE44.js → code-ACS453WG.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-S4DRQYVK.js → code-index-extractor-5SERI6TM.js} +2 -2
- package/dist/cli/chunks/{codex-installer-WRPU4ITG.js → codex-installer-WCUUWHP5.js} +2 -2
- package/dist/cli/chunks/{completions-EVEFMAIP.js → completions-6WFG3FPJ.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-3RXGDVMX.js → complexity-analyzer-IFZEFCB6.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-TLMVH7VM.js → continuedev-installer-RW6FEEND.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-JOYO6JND.js → copilot-installer-UZPE65RL.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-FJJO7V73.js → cost-tracker-2R4FT6TY.js} +2 -2
- package/dist/cli/chunks/{coverage-MBFLUTS3.js → coverage-ZUC5U47P.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-IZB5ZMXO.js +2 -0
- package/dist/cli/chunks/{cursor-installer-RUUOVPGH.js → cursor-installer-7JBZT7JZ.js} +2 -2
- package/dist/cli/chunks/{daemon-LGFCMQVV.js → daemon-YNF54UYB.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-AFCFHXDN.js → dag-attention-scheduler-MS7D2NFM.js} +2 -2
- package/dist/cli/chunks/{detect-CUWUBG5C.js → detect-UHOSHYVB.js} +2 -2
- package/dist/cli/chunks/{domain-handler-WHXJUWWW.js → domain-handler-BVW4AX7O.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-K6EVN3AJ.js → domain-transfer-PA2ENF3D.js} +2 -2
- package/dist/cli/chunks/dream-SAPSS25B.js +2 -0
- package/dist/cli/chunks/esm-node-FTBUMV4L.js +2 -0
- package/dist/cli/chunks/{eval-YZDW7GLA.js → eval-Y3ODM7JU.js} +2 -2
- package/dist/cli/chunks/{fast-paths-M4MXWH5P.js → fast-paths-DYQ5NC4Y.js} +2 -2
- package/dist/cli/chunks/{feature-flags-3YMEIR7B.js → feature-flags-V34UZPHG.js} +2 -2
- package/dist/cli/chunks/{feature-flags-5CRUDVES.js → feature-flags-YMMGYWT3.js} +2 -2
- package/dist/cli/chunks/{file-discovery-YBAUSWQ6.js → file-discovery-75ZHSK4G.js} +2 -2
- package/dist/cli/chunks/{fleet-KZ7U5HH5.js → fleet-DD2CFGJL.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-YPOKBUR3.js → gnn-wrapper-UXM3L5LV.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-47WVNCNY.js → heartbeat-handler-ANHRYXNS.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-4CKQSIHQ.js → heartbeat-scheduler-HYVMXCXT.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-CBDRZLXX.js +2 -0
- package/dist/cli/chunks/hnsw-index-EOJG4VF4.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-SZ6SXZ7G.js → hnsw-legacy-bridge-IFUEUOVF.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-XVNGLWIG.js → hnswlib-node-GYVDPTWU.js} +2 -2
- package/dist/cli/chunks/{hooks-WVVVJ2CC.js → hooks-R3DQNG2F.js} +6 -6
- package/dist/cli/chunks/hybrid-router-MSCQ2XGU.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-EYTJMSNY.js → hypergraph-engine-3TKB5O7T.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-JUCJMSBU.js → hypergraph-handler-4APYID2S.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-C2TXXYPC.js +2 -0
- package/dist/cli/chunks/{init-handler-5COQTBSZ.js → init-handler-E7B2GKH3.js} +6 -6
- package/dist/cli/chunks/init-wizard-IQV7SBMW.js +2 -0
- package/dist/cli/chunks/kernel-NJOPFGK7.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-G54YKSIL.js → kilocode-installer-WY6VTFSA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-ZEKZVKTM.js → kiro-installer-SCNF3JXD.js} +4 -4
- package/dist/cli/chunks/knowledge-graph-EUMGCQPH.js +2 -0
- package/dist/cli/chunks/{learning-JE7PDBQV.js → learning-Y4OZJFBV.js} +3 -3
- package/dist/cli/chunks/{llm-router-RCOTEVVC.js → llm-router-RBKYYHBJ.js} +5 -5
- package/dist/cli/chunks/{load-3Y35Y6FL.js → load-FY64UGHV.js} +2 -2
- package/dist/cli/chunks/load-test-LBYVVG35.js +2 -0
- package/dist/cli/chunks/{mcp-NOHRCC4E.js → mcp-6VMQOWMX.js} +2 -2
- package/dist/cli/chunks/{memory-GC5OPOO6.js → memory-Y5RO4PGM.js} +5 -5
- package/dist/cli/chunks/memory-backend-NQMJKHCQ.js +2 -0
- package/dist/cli/chunks/{memory-handlers-MLQAERRE.js → memory-handlers-CMMVHHPG.js} +2 -2
- package/dist/cli/chunks/multi-model-executor-JO3MNMPZ.js +14 -0
- package/dist/cli/chunks/{opencode-installer-POKAOPXI.js → opencode-installer-WQBTY6JT.js} +2 -2
- package/dist/cli/chunks/{orchestrator-N2T3CYEB.js → orchestrator-4J7OSNSG.js} +6 -6
- package/dist/cli/chunks/{pipeline-KAVKGC5V.js → pipeline-63T6HN72.js} +2 -2
- package/dist/cli/chunks/{platform-DJPEA24D.js → platform-UJMD4EPZ.js} +2 -2
- package/dist/cli/chunks/{plugin-RHZZP3OH.js → plugin-NDOZ63JW.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-6A57VDNI.js → prime-radiant-advanced-wasm-ELGHVIFI.js} +2 -2
- package/dist/cli/chunks/protocol-executor-ZSWPG5SU.js +2 -0
- package/dist/cli/chunks/{protocol-handler-FBR254XL.js → protocol-handler-KYERIMVF.js} +2 -2
- package/dist/cli/chunks/{prove-YZXY34P6.js → prove-ATSSBP4Z.js} +2 -2
- package/dist/cli/chunks/provider-manager-YYMIF23V.js +24 -0
- package/dist/cli/chunks/qe-reasoning-bank-4RLPRCGF.js +2 -0
- package/dist/cli/chunks/{quality-MICFT3VU.js → quality-2AGJSJW6.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-KQ673NYE.js +2 -0
- package/dist/cli/chunks/{real-embeddings-HJCRBDOM.js → real-embeddings-H36GVXMI.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-K5LIUYDR.js → roocode-installer-PMRBAY7O.js} +2 -2
- package/dist/cli/chunks/router-UBNV4H5S.js +2 -0
- package/dist/cli/chunks/routing-feedback-BMMGZ346.js +2 -0
- package/dist/cli/chunks/{routing-handler-2KIQHWUQ.js → routing-handler-Z7VZSDXW.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-DYGX7PI6.js → ruvector-commands-N3FZ3ZEE.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-UTKSIJBG.js → rvf-dual-writer-L5DQHUF3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-KVJLHJO7.js → rvf-migration-adapter-NPGFA3SL.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-CRIV4YVR.js → rvf-migration-coordinator-MCJDNKXG.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-LXBCTTVF.js +2 -0
- package/dist/cli/chunks/safe-db-FFSPBUAK.js +2 -0
- package/dist/cli/chunks/schedule-2MOMNZ6B.js +2 -0
- package/dist/cli/chunks/scheduler-5VGVANFG.js +2 -0
- package/dist/cli/chunks/{security-KSEP56UL.js → security-TX7TXUGI.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-6JWYF7WV.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-HD5QOOJD.js → shared-rvf-dual-writer-6K3ZAG7P.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-LCOAORK7.js +2 -0
- package/dist/cli/chunks/{status-handler-AMKMMUNW.js → status-handler-MIRLQRNN.js} +2 -2
- package/dist/cli/chunks/{structural-health-GUTWSPBY.js → structural-health-CIHASLUE.js} +2 -2
- package/dist/cli/chunks/{sync-OSJF3J4K.js → sync-FGLAP7EK.js} +2 -2
- package/dist/cli/chunks/{task-handler-4V4WMTJE.js → task-handler-7HMPRCHY.js} +2 -2
- package/dist/cli/chunks/{task-handlers-EAORRI7E.js → task-handlers-DQLQCLCT.js} +2 -2
- package/dist/cli/chunks/{test-EGW6L6ZI.js → test-JKDO5ZHU.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-UK2GVD67.js → test-scheduling-2YKZ7PVZ.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-DT2FQWIK.js → token-bootstrap-C7UUPMQN.js} +2 -2
- package/dist/cli/chunks/{token-usage-HQVOD3I3.js → token-usage-2RVIPCY4.js} +2 -2
- package/dist/cli/chunks/{transformers-TDZOMLEQ.js → transformers-UEMAGHQ5.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-XT3A32J7.js → tree-sitter-wasm-parser-MELABICK.js} +2 -2
- package/dist/cli/chunks/{types-QOT5P6RH.js → types-5B4RD7ZV.js} +2 -2
- package/dist/cli/chunks/unified-memory-CZCWZUFP.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-QEOXVSOZ.js +2 -0
- package/dist/cli/chunks/unified-persistence-HGZAYZGP.js +2 -0
- package/dist/cli/chunks/{validate-SXCT3APL.js → validate-CHDG7SC3.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-WGJUWWJ6.js → validate-swarm-LB7GORKE.js} +2 -2
- package/dist/cli/chunks/{vibium-ONK73HYI.js → vibium-ZMC4G2YA.js} +2 -2
- package/dist/cli/chunks/visual-security-ITKF4E4Z.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-Q5TXI2BE.js → web-tree-sitter-THNO6S2V.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-HTJT3VIM.js → windsurf-installer-LRB43BPX.js} +2 -2
- package/dist/cli/chunks/{witness-chain-7TPWQZ2P.js → witness-chain-JC5UBXPM.js} +2 -2
- package/dist/cli/chunks/witness-chain-SYFYXQD3.js +2 -0
- package/dist/cli/chunks/{workflow-LTC4J62A.js → workflow-Q4IYQ6F2.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-GZS2O3KW.js +2 -0
- package/dist/cli/chunks/{wrappers-TWCCXU2M.js → wrappers-WSSLMFSE.js} +2 -2
- package/dist/cli/commands/llm-router.js +3 -3
- package/dist/coordination/consensus/providers/claude-provider.d.ts +3 -3
- package/dist/coordination/consensus/providers/claude-provider.js +6 -3
- package/dist/coordination/task-executor.js +5 -5
- package/dist/domains/chaos-resilience/services/chaos-engineer.js +3 -3
- package/dist/domains/code-intelligence/services/knowledge-graph.js +5 -5
- package/dist/domains/constants.d.ts +3 -3
- package/dist/domains/constants.js +3 -3
- package/dist/domains/contract-testing/services/contract-validator.js +3 -3
- package/dist/domains/coverage-analysis/services/coverage-analyzer.js +5 -5
- package/dist/domains/coverage-analysis/services/gap-detector.js +5 -5
- package/dist/domains/defect-intelligence/services/defect-predictor.js +5 -5
- package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +5 -5
- package/dist/domains/learning-optimization/services/learning-coordinator.js +3 -3
- package/dist/domains/quality-assessment/services/deployment-advisor.js +5 -5
- package/dist/domains/quality-assessment/services/quality-analyzer.js +5 -5
- package/dist/domains/requirements-validation/services/requirements-validator.js +5 -5
- package/dist/domains/security-compliance/services/scanners/sast-scanner.js +5 -5
- package/dist/domains/test-execution/services/test-executor.js +3 -3
- package/dist/domains/test-generation/services/test-generator.js +5 -5
- package/dist/domains/visual-accessibility/services/visual-tester.js +3 -3
- package/dist/init/init-wizard-steps.js +1 -1
- package/dist/init/kiro-installer.js +8 -8
- package/dist/init/phases/12-verification.js +1 -1
- package/dist/integrations/agentic-flow/model-router/types.js +8 -8
- package/dist/mcp/bundle.js +82 -82
- package/dist/mcp/security/sampling-server.js +1 -1
- package/dist/routing/advisor/multi-model-executor.d.ts +6 -2
- package/dist/routing/advisor/multi-model-executor.js +19 -3
- package/dist/routing/security/cyber-pin.d.ts +58 -0
- package/dist/routing/security/cyber-pin.js +75 -0
- package/dist/shared/llm/cost-tracker.js +5 -0
- package/dist/shared/llm/effort-resolver.d.ts +79 -0
- package/dist/shared/llm/effort-resolver.js +128 -0
- package/dist/shared/llm/interfaces.d.ts +11 -1
- package/dist/shared/llm/metrics/cost-metrics.js +1 -1
- package/dist/shared/llm/model-mapping.js +31 -0
- package/dist/shared/llm/model-registry.d.ts +40 -0
- package/dist/shared/llm/model-registry.js +126 -2
- package/dist/shared/llm/provider-manager.js +1 -1
- package/dist/shared/llm/providers/bedrock.js +9 -7
- package/dist/shared/llm/providers/claude.js +31 -4
- package/dist/shared/llm/router/agent-router-config.js +16 -16
- package/dist/shared/llm/router/hybrid-router.js +18 -1
- package/dist/shared/llm/router/routing-rules.js +9 -9
- package/dist/shared/llm/router/types.js +29 -29
- package/dist/shared/llm/translation/message-formatter.js +3 -3
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-EOD4AG2T.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-6REY3BZB.js +0 -2
- package/dist/cli/chunks/base-HFVYEJKR.js +0 -2
- package/dist/cli/chunks/browser-workflow-GPR3IS36.js +0 -2
- package/dist/cli/chunks/chunk-FJZQH4JB.js +0 -2
- package/dist/cli/chunks/chunk-GIWDEW4K.js +0 -2
- package/dist/cli/chunks/chunk-LVCBXFHT.js +0 -2
- package/dist/cli/chunks/chunk-UZX62Z2K.js +0 -2
- package/dist/cli/chunks/chunk-Z7E27V5F.js +0 -2
- package/dist/cli/chunks/client-NGAZ5BMU.js +0 -2
- package/dist/cli/chunks/cross-domain-router-ORAWSROD.js +0 -2
- package/dist/cli/chunks/dream-N72NDTWM.js +0 -2
- package/dist/cli/chunks/esm-node-OUE76NVS.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-DO7CQXCP.js +0 -2
- package/dist/cli/chunks/hnsw-index-B6FEXSZX.js +0 -2
- package/dist/cli/chunks/hybrid-router-236O2EMV.js +0 -2
- package/dist/cli/chunks/impact-analyzer-E2DVJTE7.js +0 -2
- package/dist/cli/chunks/init-wizard-KQCWXEDA.js +0 -2
- package/dist/cli/chunks/kernel-KBING4CP.js +0 -2
- package/dist/cli/chunks/knowledge-graph-AF6OAAJ5.js +0 -2
- package/dist/cli/chunks/load-test-LKIZ376E.js +0 -2
- package/dist/cli/chunks/memory-backend-HHGGHQYM.js +0 -2
- package/dist/cli/chunks/multi-model-executor-YE4JOCN5.js +0 -14
- package/dist/cli/chunks/protocol-executor-RNXGXAZC.js +0 -2
- package/dist/cli/chunks/provider-manager-H7QVBYXM.js +0 -24
- package/dist/cli/chunks/qe-reasoning-bank-ZMDU5MUW.js +0 -2
- package/dist/cli/chunks/queen-coordinator-4XWCCVIY.js +0 -2
- package/dist/cli/chunks/router-JYGSCGGM.js +0 -2
- package/dist/cli/chunks/routing-feedback-DO5FLA62.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-SS6KKXJM.js +0 -2
- package/dist/cli/chunks/safe-db-A66XXHI7.js +0 -2
- package/dist/cli/chunks/schedule-DQRJD5H5.js +0 -2
- package/dist/cli/chunks/scheduler-PLSXEVV7.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-DE2OVTUI.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-R4IDAV5X.js +0 -2
- package/dist/cli/chunks/unified-memory-3MDWRNDW.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-TEJXRLAS.js +0 -2
- package/dist/cli/chunks/unified-persistence-ALHQN2LG.js +0 -2
- package/dist/cli/chunks/visual-security-WFWC5N2E.js +0 -2
- package/dist/cli/chunks/witness-chain-T34QYEFI.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-UIVPDA7M.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{f as p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{f as p}from"./chunk-D22MEX2U.js";import{a as f,c as R}from"./chunk-3AOWTHLS.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-3VG5M7WM.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@xenova/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:s,hierarchicalForward:c,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:A,LinearAttention:f,MoEAttention:h,SonaEngine:_,pipeline:v}=e||{};export{n as a,i as b,a as c,s as d,c as e,l as f,p as g,m as h,u as i,d as j,A as k,f as l,h as m,_ as n,v as o};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as p,o as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{k as p,o as N}from"./chunk-EBQUXPIG.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS witness_chain (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as g}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{a as g}from"./chunk-WQGP5ULD.js";import{b as p,c}from"./chunk-QIE76ERL.js";import{a as x,b as f,c as w}from"./chunk-3AOWTHLS.js";import{f as v}from"./chunk-IQGVQBVS.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as T}from"./chunk-Z7E27V5F.js";import{c as S}from"./chunk-XTGVTVLN.js";import{b as C,d as P}from"./chunk-WEMOVPQS.js";import{a as w,c as $}from"./chunk-LJTRN6ZE.js";import{a as b,d as M}from"./chunk-R7RGOZ3H.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
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.9.13");process.exit(0)}
|
|
2
|
+
import{a as T}from"./chunk-Y2ONHWXI.js";import{c as S}from"./chunk-HHRUXDLT.js";import{b as C,d as P}from"./chunk-VCJP7HQG.js";import{a as w,c as $}from"./chunk-3AOWTHLS.js";import{a as b,d as M}from"./chunk-YYQVSVBO.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
|
|
3
3
|
|
|
4
4
|
> ${c} Generated: ${e.timestamp.toISOString()}
|
|
5
5
|
> Run ID: ${e.runId}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as f,o as P}from"./chunk-I4JO4LD3.js";import{d as p,e as y}from"./chunk-XTGVTVLN.js";import{b as h,d as U}from"./chunk-WEMOVPQS.js";import{a as T,c as C}from"./chunk-LJTRN6ZE.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
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.9.13");process.exit(0)}
|
|
2
|
+
import{k as f,o as P}from"./chunk-EBQUXPIG.js";import{d as p,e as y}from"./chunk-HHRUXDLT.js";import{b as h,d as U}from"./chunk-VCJP7HQG.js";import{a as T,c as C}from"./chunk-3AOWTHLS.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
|
|
3
3
|
${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
|
|
@@ -1 +1 @@
|
|
|
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.9.
|
|
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.9.13");process.exit(0)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
|
|
3
3
|
describe('createUser', () => {
|
|
4
4
|
it('should create user with valid data', async () => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-AOTEEGQA.js";import{b as _,d as T}from"./chunk-VCJP7HQG.js";import{a as k,c as q}from"./chunk-3AOWTHLS.js";import{a as v,b as ee}from"./chunk-CF5EJGOV.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'npx agentic-qe hooks route --task "$PROMPT" --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],f=h,C=[...new Set([...l,...f])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
|
|
3
3
|
# Generated by aqe init
|
|
4
4
|
# See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
|
|
5
5
|
|
|
@@ -276,7 +276,7 @@ aqe init --auto
|
|
|
276
276
|
`).run("aqe_version",JSON.stringify(e),i),s.prepare(`
|
|
277
277
|
INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
|
|
278
278
|
VALUES (?, '_system', ?, ?)
|
|
279
|
-
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-
|
|
279
|
+
`).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-23MIVVHF.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
|
|
280
280
|
Install it with: npm install better-sqlite3
|
|
281
281
|
If you see native compilation errors, ensure build tools are installed:
|
|
282
282
|
- macOS: xcode-select --install
|
|
@@ -302,7 +302,7 @@ Database path: ${r}
|
|
|
302
302
|
Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!y(e))return!1;try{let n=v(e),r=n.prepare(`
|
|
303
303
|
SELECT COUNT(*) as count FROM kv_store
|
|
304
304
|
WHERE namespace = 'code-intelligence:kg'
|
|
305
|
-
`).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-
|
|
305
|
+
`).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-EUMGCQPH.js"),{InMemoryBackend:n}=await import("./memory-backend-NQMJKHCQ.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
|
|
306
306
|
SELECT COUNT(*) as count FROM kv_store
|
|
307
307
|
WHERE namespace LIKE 'code-intelligence:kg%'
|
|
308
308
|
`).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");y(r)||b(r,{recursive:!0});let s=o(r,"hnsw");y(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let f=o(r,"patterns",p);y(f)||b(f,{recursive:!0});let C=o(f,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");y(n)||b(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
|
|
@@ -311,6 +311,6 @@ Ensure the directory is writable and has sufficient disk space.`)}}async functio
|
|
|
311
311
|
|
|
312
312
|
console.log("AQE v3 hooks work via CLI commands (no daemon required)");
|
|
313
313
|
console.log("Use: npx aqe hooks session-start");
|
|
314
|
-
`),e.workers.enabled.length}async function X(t,e){if(!e.skills.install)return 0;let r=await $({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function K(t){let n=await L({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function Y(t,e,n){let s=await N({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function Z(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");y(n)||b(n,{recursive:!0});let r=oe(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function oe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-4" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
|
|
314
|
+
`),e.workers.enabled.length}async function X(t,e){if(!e.skills.install)return 0;let r=await $({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function K(t){let n=await L({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function Y(t,e,n){let s=await N({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function Z(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");y(n)||b(n,{recursive:!0});let r=oe(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function oe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-4.7" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
|
|
315
315
|
`)}var ie=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],A=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=x(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await W(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await G(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await V(n.projectRoot);let f=await B(this.projectRoot);return console.log(` Using existing code intelligence index (${f} entries)`),{status:"existing",entries:f}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await H(this.projectRoot,r,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await M(this.projectRoot,r):!1),c=await this.runStep("MCP Configuration",async()=>await z(this.projectRoot)),m=await this.runStep("CLAUDE.md Generation",async()=>await U(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await J(this.projectRoot,r):0),u=await this.runStep("Skills Installation",async()=>r.skills.install?await X(this.projectRoot,r):0),h=await this.runStep("Agents Installation",async()=>await K(this.projectRoot)),p;if(this.options.withN8n){let l=await this.runStep("N8n Platform Installation",async()=>await Y(this.projectRoot,r,this.options.n8nApiConfig));l&&(p=l)}return await this.runStep("Save Configuration",async()=>await Z(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await F(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:u,agentsInstalled:h,hooksConfigured:d,mcpConfigured:c,claudeMdGenerated:m,workersStarted:a,n8nInstalled:p},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:k(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ie}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:k(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function le(t){return new A(t)}async function xe(t){return await le({projectRoot:t,autoMode:!0}).initialize()}function Re(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
|
|
316
316
|
`)}export{A as a,le as b,xe as c,Re as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{g}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{g}from"./chunk-DY5JRJXV.js";import{b as p,c as d}from"./chunk-QIE76ERL.js";import{b as m,c as f}from"./chunk-3AOWTHLS.js";import{f as h}from"./chunk-IQGVQBVS.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:n=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let r=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,r,i),s=[];if(n){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:r,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(n.success)for(let s of n.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let r=this.getBaseName(i),l=[`${r}.test`,`${r}.spec`,`test_${r}`,`${r}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10);for(let a of c){let o=await this.memory.get(a);o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,n=Math.min(1,e.directImpact.length/10);i+=n*t.directImpact;let r=Math.min(1,e.transitiveImpact.length/20);i+=r*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(r=>this.isCriticalPath(r.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let n=[...e.directImpact,...e.transitiveImpact].filter(r=>r.riskScore>=.7);return n.length>0&&t.push(`${n.length} high-risk files impacted: ${n.slice(0,2).map(r=>this.getFileName(r.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let n=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(n.success){let{nodes:r,edges:l}=n.value;for(let s of r){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let n=[],r=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(r.has(a.path)||a.path===s.file)continue;r.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);n.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(n)}calculateFileRiskScore(e,t,i,n=1){let r=0;return r+=Math.min(.3,t/20),r+=Math.min(.2,i/30),this.isCriticalPath(e)&&(r+=.3),this.isEntryPoint(e)&&(r+=.2),r=r*Math.pow(.8,n-1),Math.min(1,Math.max(0,r))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,n)=>i+n.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let n=t.get(i.file);(!n||i.distance<n.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,n)=>n.riskScore!==i.riskScore?n.riskScore-i.riskScore:i.distance-n.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as F,c as D}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{a as F,c as D}from"./chunk-3AOWTHLS.js";import{d as $}from"./chunk-AZPDX4KS.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-UEMAGHQ5.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as c,d as p}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.13");process.exit(0)}
|
|
2
|
+
import{b as c,d as p}from"./chunk-VCJP7HQG.js";import{a as f}from"./chunk-ERGY45RL.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
|
|
3
3
|
`)}export{S as a,b,x as c,P as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
import{isIP as o}from"net";import{lookup as n}from"dns/promises";var f=[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^0\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/,/^fd[0-9a-f]{2}:/i];function t(r){return f.some(s=>s.test(r))}async function u(r){if(process.env.AQE_HOOKS_SSRF_DISABLED==="true")return{safe:!0};let s;try{s=new URL(r)}catch{return{safe:!1,reason:`Invalid URL: ${r}`}}let e=s.hostname.replace(/^\[|\]$/g,"");if(o(e))return t(e)?{safe:!1,reason:`Private IP blocked: ${e}`}:{safe:!0};try{let a=await n(e);if(t(a.address))return{safe:!1,reason:`DNS resolves to private IP: ${a.address}`}}catch(a){return{safe:!1,reason:`DNS lookup failed for ${e}: ${a.message}`}}return{safe:!0}}export{t as a,u as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as ie,b as ae}from"./chunk-AXJTWYCF.js";import{S as oe,i as j,p as q}from"./chunk-LNHOWUSG.js";import{c as g,e as D,g as $}from"./chunk-FT3BXL44.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,H,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,H=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function w(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=w(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=w(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=w(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>w});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|
|
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.9.13");process.exit(0)}
|
|
2
|
+
import{a as ie,b as ae}from"./chunk-JOCR5TWI.js";import{S as oe,i as j,p as q}from"./chunk-W2YCNX4O.js";import{c as g,e as D,g as $}from"./chunk-ERGY45RL.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,H,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,H=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function w(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=w(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=w(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=w(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>w});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
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.9.13");process.exit(0)}
|
|
2
2
|
import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
|
|
3
3
|
`),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
|