agentic-qe 3.10.5 → 3.10.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/v3/qe-accessibility-auditor.md +8 -0
- package/.claude/agents/v3/qe-bdd-generator.md +8 -0
- package/.claude/agents/v3/qe-chaos-engineer.md +8 -0
- package/.claude/agents/v3/qe-code-complexity.md +8 -0
- package/.claude/agents/v3/qe-code-intelligence.md +8 -0
- package/.claude/agents/v3/qe-contract-validator.md +8 -0
- package/.claude/agents/v3/qe-coverage-specialist.md +8 -0
- package/.claude/agents/v3/qe-defect-predictor.md +8 -0
- package/.claude/agents/v3/qe-dependency-mapper.md +8 -0
- package/.claude/agents/v3/qe-deployment-advisor.md +8 -0
- package/.claude/agents/v3/qe-devils-advocate.md +8 -0
- package/.claude/agents/v3/qe-flaky-hunter.md +8 -0
- package/.claude/agents/v3/qe-fleet-commander.md +8 -0
- package/.claude/agents/v3/qe-gap-detector.md +8 -0
- package/.claude/agents/v3/qe-graphql-tester.md +8 -0
- package/.claude/agents/v3/qe-impact-analyzer.md +8 -0
- package/.claude/agents/v3/qe-integration-tester.md +8 -0
- package/.claude/agents/v3/qe-kg-builder.md +8 -0
- package/.claude/agents/v3/qe-learning-coordinator.md +8 -0
- package/.claude/agents/v3/qe-load-tester.md +8 -0
- package/.claude/agents/v3/qe-message-broker-tester.md +8 -0
- package/.claude/agents/v3/qe-metrics-optimizer.md +8 -0
- package/.claude/agents/v3/qe-middleware-validator.md +8 -0
- package/.claude/agents/v3/qe-mutation-tester.md +8 -0
- package/.claude/agents/v3/qe-odata-contract-tester.md +8 -0
- package/.claude/agents/v3/qe-parallel-executor.md +8 -0
- package/.claude/agents/v3/qe-pattern-learner.md +8 -0
- package/.claude/agents/v3/qe-pentest-validator.md +8 -0
- package/.claude/agents/v3/qe-performance-tester.md +8 -0
- package/.claude/agents/v3/qe-product-factors-assessor.md +8 -0
- package/.claude/agents/v3/qe-property-tester.md +8 -0
- package/.claude/agents/v3/qe-quality-criteria-recommender.md +8 -0
- package/.claude/agents/v3/qe-quality-gate.md +8 -0
- package/.claude/agents/v3/qe-qx-partner.md +8 -0
- package/.claude/agents/v3/qe-regression-analyzer.md +8 -0
- package/.claude/agents/v3/qe-requirements-validator.md +8 -0
- package/.claude/agents/v3/qe-responsive-tester.md +8 -0
- package/.claude/agents/v3/qe-retry-handler.md +8 -0
- package/.claude/agents/v3/qe-risk-assessor.md +8 -0
- package/.claude/agents/v3/qe-root-cause-analyzer.md +8 -0
- package/.claude/agents/v3/qe-sap-idoc-tester.md +8 -0
- package/.claude/agents/v3/qe-sap-rfc-tester.md +8 -0
- package/.claude/agents/v3/qe-security-auditor.md +8 -0
- package/.claude/agents/v3/qe-security-scanner.md +8 -0
- package/.claude/agents/v3/qe-soap-tester.md +8 -0
- package/.claude/agents/v3/qe-sod-analyzer.md +8 -0
- package/.claude/agents/v3/qe-tdd-specialist.md +8 -0
- package/.claude/agents/v3/qe-test-architect.md +8 -0
- package/.claude/agents/v3/qe-test-idea-rewriter.md +8 -0
- package/.claude/agents/v3/qe-transfer-specialist.md +8 -0
- package/.claude/agents/v3/qe-visual-tester.md +8 -0
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +9012 -8934
- package/assets/agents/v3/qe-accessibility-auditor.md +8 -0
- package/assets/agents/v3/qe-bdd-generator.md +8 -0
- package/assets/agents/v3/qe-chaos-engineer.md +8 -0
- package/assets/agents/v3/qe-code-complexity.md +8 -0
- package/assets/agents/v3/qe-code-intelligence.md +8 -0
- package/assets/agents/v3/qe-contract-validator.md +8 -0
- package/assets/agents/v3/qe-coverage-specialist.md +8 -0
- package/assets/agents/v3/qe-defect-predictor.md +8 -0
- package/assets/agents/v3/qe-dependency-mapper.md +8 -0
- package/assets/agents/v3/qe-deployment-advisor.md +8 -0
- package/assets/agents/v3/qe-devils-advocate.md +8 -0
- package/assets/agents/v3/qe-flaky-hunter.md +8 -0
- package/assets/agents/v3/qe-fleet-commander.md +8 -0
- package/assets/agents/v3/qe-gap-detector.md +8 -0
- package/assets/agents/v3/qe-graphql-tester.md +8 -0
- package/assets/agents/v3/qe-impact-analyzer.md +8 -0
- package/assets/agents/v3/qe-integration-tester.md +8 -0
- package/assets/agents/v3/qe-kg-builder.md +8 -0
- package/assets/agents/v3/qe-learning-coordinator.md +8 -0
- package/assets/agents/v3/qe-load-tester.md +8 -0
- package/assets/agents/v3/qe-message-broker-tester.md +8 -0
- package/assets/agents/v3/qe-metrics-optimizer.md +8 -0
- package/assets/agents/v3/qe-middleware-validator.md +8 -0
- package/assets/agents/v3/qe-mutation-tester.md +8 -0
- package/assets/agents/v3/qe-odata-contract-tester.md +8 -0
- package/assets/agents/v3/qe-parallel-executor.md +8 -0
- package/assets/agents/v3/qe-pattern-learner.md +8 -0
- package/assets/agents/v3/qe-pentest-validator.md +8 -0
- package/assets/agents/v3/qe-performance-tester.md +8 -0
- package/assets/agents/v3/qe-product-factors-assessor.md +8 -0
- package/assets/agents/v3/qe-property-tester.md +8 -0
- package/assets/agents/v3/qe-quality-criteria-recommender.md +8 -0
- package/assets/agents/v3/qe-quality-gate.md +8 -0
- package/assets/agents/v3/qe-qx-partner.md +8 -0
- package/assets/agents/v3/qe-regression-analyzer.md +8 -0
- package/assets/agents/v3/qe-requirements-validator.md +8 -0
- package/assets/agents/v3/qe-responsive-tester.md +8 -0
- package/assets/agents/v3/qe-retry-handler.md +8 -0
- package/assets/agents/v3/qe-risk-assessor.md +8 -0
- package/assets/agents/v3/qe-root-cause-analyzer.md +8 -0
- package/assets/agents/v3/qe-sap-idoc-tester.md +8 -0
- package/assets/agents/v3/qe-sap-rfc-tester.md +8 -0
- package/assets/agents/v3/qe-security-auditor.md +8 -0
- package/assets/agents/v3/qe-security-scanner.md +8 -0
- package/assets/agents/v3/qe-soap-tester.md +8 -0
- package/assets/agents/v3/qe-sod-analyzer.md +8 -0
- package/assets/agents/v3/qe-tdd-specialist.md +8 -0
- package/assets/agents/v3/qe-test-architect.md +8 -0
- package/assets/agents/v3/qe-test-idea-rewriter.md +8 -0
- package/assets/agents/v3/qe-transfer-specialist.md +8 -0
- package/assets/agents/v3/qe-visual-tester.md +8 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-AMIHQ243.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-3BC5LIEB.js → agent-booster-wasm-J5CITTTV.js} +2 -2
- package/dist/cli/chunks/{agent-handler-QLXWVZZF.js → agent-handler-HMN4ZBZ6.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-3U5PDYW7.js → agent-memory-branch-SCAKN4DU.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-LRG2UG6P.js +2 -0
- package/dist/cli/chunks/{arena-BMJQK4RD.js → arena-CJOLCHZW.js} +4 -4
- package/dist/cli/chunks/{arena-XENAGV4I.js → arena-FVBTSGKS.js} +2 -2
- package/dist/cli/chunks/audit-SOF6L5RY.js +3 -0
- package/dist/cli/chunks/base-WDL3FANJ.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-P6HSEFLW.js → better-sqlite3-5G7LRX7Q.js} +2 -2
- package/dist/cli/chunks/{brain-handler-PHSWG5PR.js → brain-handler-D2ZQQI2J.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-LNSYT34I.js → branch-enumerator-QQXOCGOR.js} +2 -2
- package/dist/cli/chunks/{browser-M5BVQMBI.js → browser-XASHKIEN.js} +2 -2
- package/dist/cli/chunks/browser-workflow-W7S4IKWD.js +2 -0
- package/dist/cli/chunks/{chunk-DN65ILSI.js → chunk-2CZQA3NN.js} +2 -2
- package/dist/cli/chunks/{chunk-VKWDMOR4.js → chunk-2I5RXDNO.js} +2 -2
- package/dist/cli/chunks/{chunk-5D7GLMT3.js → chunk-2IC2I525.js} +1 -1
- package/dist/cli/chunks/{chunk-RFVZMNYX.js → chunk-2RQSFRON.js} +2 -2
- package/dist/cli/chunks/{chunk-VESYE5YO.js → chunk-2UI5LQ7C.js} +3 -3
- package/dist/cli/chunks/{chunk-54IPDQIZ.js → chunk-3XUPDWMA.js} +8 -8
- package/dist/cli/chunks/chunk-434VUSZP.js +2 -0
- package/dist/cli/chunks/{chunk-FLYFNNSN.js → chunk-4B22URZJ.js} +3 -3
- package/dist/cli/chunks/{chunk-PGNQR2VM.js → chunk-4N4TU7ST.js} +1 -1
- package/dist/cli/chunks/{chunk-N2TJXGHG.js → chunk-4XEUJH2M.js} +1 -1
- package/dist/cli/chunks/{chunk-Q6BKJZTG.js → chunk-5QTUGFFP.js} +2 -2
- package/dist/cli/chunks/{chunk-A7HGS7FW.js → chunk-5V4IFRG5.js} +2 -2
- package/dist/cli/chunks/{chunk-G5UIGH4C.js → chunk-5VTRPOYL.js} +3 -3
- package/dist/cli/chunks/{chunk-HKJ3LG3N.js → chunk-6DHJPKAH.js} +2 -2
- package/dist/cli/chunks/{chunk-G4GX6YKX.js → chunk-6RFPELCD.js} +2 -2
- package/dist/cli/chunks/{chunk-JY7T2AQQ.js → chunk-6ZLVQTQ5.js} +4 -4
- package/dist/cli/chunks/{chunk-DJQYZ4RZ.js → chunk-7BPYFDWY.js} +1 -1
- package/dist/cli/chunks/{chunk-KIMJPTHD.js → chunk-7NXVVIJZ.js} +2 -2
- package/dist/cli/chunks/{chunk-DIJ74M7V.js → chunk-7OK5H6ML.js} +1 -1
- package/dist/cli/chunks/{chunk-MGCW5FWH.js → chunk-7RTI5WT4.js} +2 -2
- package/dist/cli/chunks/{chunk-OATHXZYW.js → chunk-7SFCZ3AE.js} +1 -1
- package/dist/cli/chunks/{chunk-RCAIOTIF.js → chunk-A2DCROAN.js} +2 -2
- package/dist/cli/chunks/{chunk-DWLGFYXV.js → chunk-AJ2VDNPB.js} +3 -3
- package/dist/cli/chunks/chunk-AQPFTDGS.js +14 -0
- package/dist/cli/chunks/{chunk-ZTC64OJE.js → chunk-B3H2TTYT.js} +2 -2
- package/dist/cli/chunks/{chunk-7DU35D4M.js → chunk-BHD6THT5.js} +1 -1
- package/dist/cli/chunks/{chunk-TMD6IC6D.js → chunk-BXOGLZGU.js} +2 -2
- package/dist/cli/chunks/{chunk-MIMJVKJJ.js → chunk-C75ODWRP.js} +3 -3
- package/dist/cli/chunks/{chunk-CUAM34RQ.js → chunk-CH7KUYGO.js} +3 -3
- package/dist/cli/chunks/{chunk-MEN3UW7W.js → chunk-CSM4LXTH.js} +1 -1
- package/dist/cli/chunks/{chunk-VWN66V7U.js → chunk-DAUQIXHW.js} +2 -2
- package/dist/cli/chunks/{chunk-D4WDJ4ZF.js → chunk-DF4Z7TKZ.js} +2 -2
- package/dist/cli/chunks/{chunk-56RA6YPN.js → chunk-DFBVWMX3.js} +2 -2
- package/dist/cli/chunks/{chunk-UTORITJT.js → chunk-EDPVATNH.js} +2 -2
- package/dist/cli/chunks/{chunk-RR55MLD4.js → chunk-EJWAKPZD.js} +1 -1
- package/dist/cli/chunks/{chunk-2RLRPKCG.js → chunk-ELC6JIXL.js} +2 -2
- package/dist/cli/chunks/{chunk-K5KKZWED.js → chunk-ELTN4F4R.js} +2 -2
- package/dist/cli/chunks/{chunk-G6FP3S3G.js → chunk-ESZDW6G7.js} +2 -2
- package/dist/cli/chunks/{chunk-MWPFUBXS.js → chunk-EYKID5HA.js} +1 -1
- package/dist/cli/chunks/{chunk-VC256KH2.js → chunk-F72A356B.js} +2 -2
- package/dist/cli/chunks/{chunk-VB7DZVCI.js → chunk-GWHDPEBT.js} +1 -1
- package/dist/cli/chunks/{chunk-4K7T6AKM.js → chunk-GXNNKM7F.js} +1 -1
- package/dist/cli/chunks/{chunk-WFZUKXV5.js → chunk-H4Q36ILL.js} +2 -2
- package/dist/cli/chunks/{chunk-2UQWVF4P.js → chunk-H6UPZFI6.js} +2 -2
- package/dist/cli/chunks/{chunk-QAW6RVAR.js → chunk-H73FLSBV.js} +10 -10
- package/dist/cli/chunks/{chunk-24A7KD3D.js → chunk-HDEFCRHI.js} +1 -1
- package/dist/cli/chunks/{chunk-ZUBJBAUD.js → chunk-HFU3LTQX.js} +2 -2
- package/dist/cli/chunks/{chunk-IOE6LDPF.js → chunk-HMHQOEU7.js} +2 -2
- package/dist/cli/chunks/{chunk-CS3UB2OL.js → chunk-HWKFBRMX.js} +1 -1
- package/dist/cli/chunks/{chunk-DBR4TQPK.js → chunk-HZGOVRZ6.js} +2 -2
- package/dist/cli/chunks/{chunk-3JWV4GE6.js → chunk-I7ADT6AZ.js} +2 -2
- package/dist/cli/chunks/{chunk-D3Q4443B.js → chunk-IB3QQDC4.js} +1 -1
- package/dist/cli/chunks/{chunk-J533CJUN.js → chunk-J2SMTP2L.js} +3 -3
- package/dist/cli/chunks/{chunk-S7FGTHFE.js → chunk-J3WUBGLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-IT7CEHAJ.js → chunk-JADBRSQN.js} +2 -2
- package/dist/cli/chunks/{chunk-BSRCL6RU.js → chunk-JP2YXWJD.js} +2 -2
- package/dist/cli/chunks/chunk-JPL53G4V.js +20 -0
- package/dist/cli/chunks/{chunk-IUKERFLT.js → chunk-JX7HZMW5.js} +1 -1
- package/dist/cli/chunks/{chunk-FE3FGMNB.js → chunk-JXCIRWLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-IRS4HKAR.js → chunk-K32AUACO.js} +1 -1
- package/dist/cli/chunks/{chunk-A3BDPU5F.js → chunk-KQOJYO5Z.js} +4 -4
- package/dist/cli/chunks/{chunk-IIFCTJOF.js → chunk-KVMY2ABO.js} +2 -2
- package/dist/cli/chunks/{chunk-WFZ4DRIC.js → chunk-L2IMTNZF.js} +2 -2
- package/dist/cli/chunks/{chunk-HHEHGERJ.js → chunk-LAGNWKAD.js} +2 -2
- package/dist/cli/chunks/{chunk-RZ7D5SHS.js → chunk-LEDF3LGZ.js} +1 -1
- package/dist/cli/chunks/{chunk-YZFNPTGN.js → chunk-LHA4OQ7G.js} +2 -2
- package/dist/cli/chunks/{chunk-GTVXVYKE.js → chunk-LHZOIXJ6.js} +2 -2
- package/dist/cli/chunks/{chunk-TISBFSDJ.js → chunk-LOQMQEKN.js} +1 -1
- package/dist/cli/chunks/{chunk-GMU7P5O3.js → chunk-LWUIK5DH.js} +2 -2
- package/dist/cli/chunks/{chunk-MFQIJ3HV.js → chunk-M3APJ7VS.js} +2 -2
- package/dist/cli/chunks/{chunk-CTG3GJIM.js → chunk-M4OYZMXE.js} +2 -2
- package/dist/cli/chunks/{chunk-AVQD7KEN.js → chunk-MCMVRPNG.js} +2 -2
- package/dist/cli/chunks/{chunk-YZD4VIE5.js → chunk-MJLDZSFB.js} +1 -1
- package/dist/cli/chunks/{chunk-PPM5D7LH.js → chunk-MQN3HYFX.js} +1 -1
- package/dist/cli/chunks/{chunk-RONMVGCT.js → chunk-MSJGDIRP.js} +2 -2
- package/dist/cli/chunks/{chunk-UOIT5JZ6.js → chunk-NEIJP6TG.js} +2 -2
- package/dist/cli/chunks/{chunk-3KGUP2SD.js → chunk-NHC635LL.js} +2 -2
- package/dist/cli/chunks/{chunk-SK6YRNXI.js → chunk-NKEGEQ3J.js} +2 -2
- package/dist/cli/chunks/{chunk-66LOFIBP.js → chunk-NN35QH6X.js} +2 -2
- package/dist/cli/chunks/{chunk-GKG6IQP6.js → chunk-NUCJS3Z7.js} +3 -3
- package/dist/cli/chunks/{chunk-IWRORKD7.js → chunk-O2H5WYFK.js} +2 -2
- package/dist/cli/chunks/{chunk-S73KENCH.js → chunk-O4MNYX4X.js} +2 -2
- package/dist/cli/chunks/{chunk-B4F5EPNR.js → chunk-OBLAWVXM.js} +1 -1
- package/dist/cli/chunks/{chunk-MRXKIXVV.js → chunk-OU4HRUVV.js} +2 -2
- package/dist/cli/chunks/{chunk-HNYSBE5J.js → chunk-P7EOYGR2.js} +2 -2
- package/dist/cli/chunks/{chunk-3BGGNHHZ.js → chunk-PFSBUTDA.js} +1 -1
- package/dist/cli/chunks/{chunk-FPWA73N6.js → chunk-PIIBVLFC.js} +2 -2
- package/dist/cli/chunks/{chunk-BB7MEGXD.js → chunk-PIJ5XOMM.js} +2 -2
- package/dist/cli/chunks/{chunk-O5OOUMBB.js → chunk-Q4LYWIEX.js} +2 -2
- package/dist/cli/chunks/{chunk-RFNEEDPQ.js → chunk-Q5432RIH.js} +2 -2
- package/dist/cli/chunks/{chunk-D7NKRCIL.js → chunk-QJXZ4SU7.js} +2 -2
- package/dist/cli/chunks/{chunk-6SAU7GXO.js → chunk-QNIL3D6E.js} +1 -1
- package/dist/cli/chunks/{chunk-W7KGHW4T.js → chunk-QUQA4NNZ.js} +2 -2
- package/dist/cli/chunks/{chunk-FNJZBIR3.js → chunk-QZSNYXYC.js} +2 -2
- package/dist/cli/chunks/{chunk-R573V37S.js → chunk-RA7HEY5G.js} +17 -17
- package/dist/cli/chunks/{chunk-253TDTPH.js → chunk-RBZWUWUG.js} +1 -1
- package/dist/cli/chunks/{chunk-HRORJ352.js → chunk-RH3I4Q23.js} +2 -2
- package/dist/cli/chunks/{chunk-CUY2EUSQ.js → chunk-ROXH622K.js} +2 -2
- package/dist/cli/chunks/{chunk-NGSA53GC.js → chunk-RTAGNKCV.js} +2 -2
- package/dist/cli/chunks/{chunk-ZS4BGJJV.js → chunk-RTFFD263.js} +1 -1
- package/dist/cli/chunks/{chunk-ZG3DSWUA.js → chunk-S574AFAT.js} +1 -1
- package/dist/cli/chunks/{chunk-GDUGW6FZ.js → chunk-SA5FTDRS.js} +2 -2
- package/dist/cli/chunks/{chunk-NKW7VOZV.js → chunk-SHVTMMJB.js} +1 -1
- package/dist/cli/chunks/{chunk-QTDZS4U6.js → chunk-SUGQZCNI.js} +2 -2
- package/dist/cli/chunks/{chunk-TMTLWSSA.js → chunk-T6CUKJHS.js} +1 -1
- package/dist/cli/chunks/{chunk-HPKYIK7R.js → chunk-T6SCQVWH.js} +2 -2
- package/dist/cli/chunks/{chunk-75MP7JMV.js → chunk-TFA5UETW.js} +1 -1
- package/dist/cli/chunks/{chunk-JPOEI7CJ.js → chunk-TFJDJVPC.js} +2 -2
- package/dist/cli/chunks/chunk-TNVOINYC.js +12 -0
- package/dist/cli/chunks/{chunk-MJRYHHOG.js → chunk-TUFU3BAK.js} +2 -2
- package/dist/cli/chunks/{chunk-X4B3R3ZZ.js → chunk-TWH3ZL6B.js} +2 -2
- package/dist/cli/chunks/{chunk-RUQV3BTV.js → chunk-ULEVKOWQ.js} +1 -1
- package/dist/cli/chunks/{chunk-AMBIOEMO.js → chunk-ULV5K4V5.js} +1 -1
- package/dist/cli/chunks/{chunk-S7HQOGVD.js → chunk-UNDPB5SS.js} +1 -1
- package/dist/cli/chunks/{chunk-YEO2Z3UX.js → chunk-UQYDFT6I.js} +2 -2
- package/dist/cli/chunks/{chunk-ZCYKWEAM.js → chunk-USPBUR6P.js} +2 -2
- package/dist/cli/chunks/{chunk-IVKSZNMI.js → chunk-UVWOIF6P.js} +1 -1
- package/dist/cli/chunks/{chunk-PYBVFG6T.js → chunk-UWDC3TZP.js} +2 -2
- package/dist/cli/chunks/{chunk-2Z7HIT5I.js → chunk-VFFIMJWT.js} +1 -1
- package/dist/cli/chunks/{chunk-7JZCEQFR.js → chunk-VQM2TC2V.js} +1 -1
- package/dist/cli/chunks/{chunk-4Z7XH4JE.js → chunk-WNAFMYND.js} +2 -2
- package/dist/cli/chunks/{chunk-AZCKTAUI.js → chunk-X3YWLJGT.js} +2 -2
- package/dist/cli/chunks/{chunk-SXQIH2QA.js → chunk-X5R6SUWM.js} +2 -2
- package/dist/cli/chunks/{chunk-4FTO3TPH.js → chunk-XKRJQIGP.js} +2 -2
- package/dist/cli/chunks/{chunk-XI6ZZMX7.js → chunk-XLFYVBOD.js} +1 -1
- package/dist/cli/chunks/chunk-XOGBTPJI.js +65 -0
- package/dist/cli/chunks/{chunk-ZT7JSFGT.js → chunk-XOYTW6LI.js} +2 -2
- package/dist/cli/chunks/{chunk-RLU7764Y.js → chunk-Z3RPA3RD.js} +2 -2
- package/dist/cli/chunks/{chunk-OJNG6ZXG.js → chunk-ZBSEXVEI.js} +2 -2
- package/dist/cli/chunks/{chunk-3WOQY6UL.js → chunk-ZMCMSDXR.js} +2 -2
- package/dist/cli/chunks/{chunk-FW3C4LWU.js → chunk-ZY4G7O7Y.js} +2 -2
- package/dist/cli/chunks/{ci-M2BSQBLL.js → ci-COQUVZH6.js} +2 -2
- package/dist/cli/chunks/{ci-output-Z4TMK6GZ.js → ci-output-KVUHUEOT.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-E3G4GGWB.js → circuit-breaker-O4JNXAYH.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-MASRQU54.js → claude-flow-setup-J65U34NA.js} +2 -2
- package/dist/cli/chunks/client-VJNNIAMG.js +2 -0
- package/dist/cli/chunks/{cline-installer-P3BWAKQA.js → cline-installer-ZTG234Z2.js} +2 -2
- package/dist/cli/chunks/{code-7HY5HQAV.js → code-5GWPY4IX.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-MBVKLOEU.js → code-index-extractor-TWNKG4VS.js} +2 -2
- package/dist/cli/chunks/{codex-installer-WZ6QO2PH.js → codex-installer-4TM4BLAE.js} +2 -2
- package/dist/cli/chunks/{completions-TOJC2UFP.js → completions-BBNHQXMV.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-QYVDIAAW.js → complexity-analyzer-2SCI2VGH.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-J72CV7P4.js → continuedev-installer-CTIORASU.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-ACDA3GEA.js → copilot-installer-4R2V4IYB.js} +2 -2
- package/dist/cli/chunks/core-handlers-MV5CAR7O.js +2 -0
- package/dist/cli/chunks/{cost-tracker-BAYQJELE.js → cost-tracker-KDBYQBKG.js} +2 -2
- package/dist/cli/chunks/{coverage-QD3XJV6W.js → coverage-QQJQVDPZ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-ULY4NIML.js +2 -0
- package/dist/cli/chunks/{cursor-installer-SPGZ4TQM.js → cursor-installer-5WEZCESZ.js} +2 -2
- package/dist/cli/chunks/{daemon-3EVOL2UH.js → daemon-M4DKHEEA.js} +3 -3
- package/dist/cli/chunks/{daemon-N4JKD5SO.js → daemon-Y7H3ZUXQ.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-3BVLL3L5.js → dag-attention-scheduler-SD2UIADT.js} +2 -2
- package/dist/cli/chunks/{detect-SWACKB45.js → detect-WONWUXFH.js} +2 -2
- package/dist/cli/chunks/{dist-node-LU4E7PI6.js → dist-node-Q5GQN2R6.js} +2 -2
- package/dist/cli/chunks/{domain-handler-5AKKAC43.js → domain-handler-EMXE2XQW.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-LB6H7RPX.js → domain-transfer-QATUJJRP.js} +2 -2
- package/dist/cli/chunks/dream-PIGWXWE4.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-7RBA5NDK.js → embed-and-insert-pattern-AAFHLBEJ.js} +2 -2
- package/dist/cli/chunks/{eval-ZZFPRENX.js → eval-73BDNLSK.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-HRO3EGIW.js → experience-capture-middleware-YPAPVSYY.js} +3 -3
- package/dist/cli/chunks/{fast-paths-IRRNQBTY.js → fast-paths-33ZKMNYY.js} +2 -2
- package/dist/cli/chunks/{feature-flags-R5N5IWI2.js → feature-flags-F3DVW4ST.js} +2 -2
- package/dist/cli/chunks/{feature-flags-W54ABAUA.js → feature-flags-QKO5YYDU.js} +2 -2
- package/dist/cli/chunks/{file-discovery-6CIDLVID.js → file-discovery-YYVZLRYD.js} +2 -2
- package/dist/cli/chunks/{fleet-YTFN64WE.js → fleet-EJX6BXLR.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-RXMPLMV2.js → gnn-wrapper-TBNLYPTM.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-HQQWEEQQ.js → heartbeat-handler-HPRTS6SI.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-5BBLZP6R.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-FMEBL5T4.js +2 -0
- package/dist/cli/chunks/hnsw-index-K2R24V4Z.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-GPZIKYFD.js → hnsw-legacy-bridge-Z6V6TOF5.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-6AGIBSVE.js → hnswlib-node-LFVNGGCL.js} +2 -2
- package/dist/cli/chunks/{hooks-AYLAGFOK.js → hooks-GG2Z3BDB.js} +10 -10
- package/dist/cli/chunks/hybrid-router-LVF6N345.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-56FMXI3T.js → hypergraph-engine-X4Q2TTET.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-APEVT5IE.js → hypergraph-handler-6BZWV5PL.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-CCVVMGWE.js +2 -0
- package/dist/cli/chunks/{init-handler-5DWF4REQ.js → init-handler-EKUS7U6L.js} +6 -6
- package/dist/cli/chunks/init-wizard-KDPMO4G3.js +2 -0
- package/dist/cli/chunks/kernel-PBYNK5VA.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-XKAUA5VA.js → kilocode-installer-BWAVVSQG.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-NI2KIYJE.js → kiro-installer-UADO53E5.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-C7LVHHLN.js +2 -0
- package/dist/cli/chunks/{learning-ZIUMUNXZ.js → learning-HMUTCYQM.js} +3 -3
- package/dist/cli/chunks/{llm-router-IL52EF2V.js → llm-router-453TBDUY.js} +4 -4
- package/dist/cli/chunks/llm-router-service-LMTRJCPP.js +2 -0
- package/dist/cli/chunks/{load-B5LFYD6O.js → load-DBBSNP6T.js} +2 -2
- package/dist/cli/chunks/load-test-FHMZXTXD.js +2 -0
- package/dist/cli/chunks/{mcp-K6GZLWBC.js → mcp-PK3SAKRF.js} +2 -2
- package/dist/cli/chunks/{memory-NCQRVSN6.js → memory-63NHVBXS.js} +5 -5
- package/dist/cli/chunks/memory-backend-UZHPCQTB.js +2 -0
- package/dist/cli/chunks/memory-handlers-YIKKORRY.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-R4LBSJWK.js → multi-model-executor-HUGRXJ6D.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-I6CBR3PV.js → opencode-installer-A6IXNF26.js} +2 -2
- package/dist/cli/chunks/{orchestrator-5FXUCES6.js → orchestrator-KDFYDNE3.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-5PS4JN6V.js +2 -0
- package/dist/cli/chunks/{pipeline-GDKCTXJH.js → pipeline-HSPRKEYE.js} +2 -2
- package/dist/cli/chunks/{platform-ZFY3F4T3.js → platform-X74IBN2H.js} +2 -2
- package/dist/cli/chunks/{plugin-HQMEN3OS.js → plugin-KDJZ7VFD.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-LSJGF4CV.js → prime-radiant-advanced-wasm-2YZGKQE7.js} +2 -2
- package/dist/cli/chunks/protocol-executor-2GTGIOFD.js +2 -0
- package/dist/cli/chunks/{protocol-handler-BMDNIGPP.js → protocol-handler-I2SDHC7B.js} +2 -2
- package/dist/cli/chunks/{prove-ABVGAG4Z.js → prove-JQJDNIZH.js} +2 -2
- package/dist/cli/chunks/provider-manager-VH6YTBB3.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-47JSO76G.js +2 -0
- package/dist/cli/chunks/{quality-ENJXPNP5.js → quality-2P7KHVY3.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-C7EDY7IS.js +2 -0
- package/dist/cli/chunks/{real-embeddings-W3GNAEJO.js → real-embeddings-L7NMMNDO.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-4FJNQ7PU.js → roocode-installer-LA4QN5AG.js} +2 -2
- package/dist/cli/chunks/router-7DVH66WB.js +2 -0
- package/dist/cli/chunks/routing-feedback-4I2MF235.js +2 -0
- package/dist/cli/chunks/{routing-handler-GFS5FA4F.js → routing-handler-B5CDEZF3.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-GBMYNJKN.js → ruvector-commands-SOVCRLJ6.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-STUAQT6U.js → rvf-dual-writer-M6WI2KFB.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-LO6DBNJH.js → rvf-migration-adapter-YDMZGPMA.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-I5AD4VJ2.js → rvf-migration-coordinator-TFGQ5EO4.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-UN3ESMMW.js +2 -0
- package/dist/cli/chunks/safe-db-Y2ZXKWBK.js +2 -0
- package/dist/cli/chunks/schedule-PG2NVRGA.js +2 -0
- package/dist/cli/chunks/scheduler-CNH6WWU2.js +2 -0
- package/dist/cli/chunks/{security-X3WCA5K5.js → security-R3IXQXDA.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-Z4FSPWNP.js → shared-rvf-adapter-GZX7LSQZ.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-QOPOIRIC.js → shared-rvf-dual-writer-YT7SJX7K.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-WWT4DRRP.js +2 -0
- package/dist/cli/chunks/{status-handler-B2B5QBVK.js → status-handler-7PZSPBHJ.js} +2 -2
- package/dist/cli/chunks/{structural-health-KT47LBVH.js → structural-health-UMJS6IVR.js} +2 -2
- package/dist/cli/chunks/sync-HA5SLSBA.js +2 -0
- package/dist/cli/chunks/{sync-VWD6OOUR.js → sync-UIREA3UG.js} +2 -2
- package/dist/cli/chunks/{task-handler-X5JT5YBF.js → task-handler-NV4HGMEG.js} +2 -2
- package/dist/cli/chunks/{task-handlers-IW4GQDW4.js → task-handlers-RXYWWOSU.js} +3 -3
- package/dist/cli/chunks/{test-MBZSUASD.js → test-2Y6OXGEU.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-E5KHKRZS.js → test-scheduling-N55VFOYT.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-FW3ZVMRP.js +2 -0
- package/dist/cli/chunks/{token-usage-ECJSPOQB.js → token-usage-YXKOB3U6.js} +2 -2
- package/dist/cli/chunks/{transformers-UZJAQ7OZ.js → transformers-GBRSFAVA.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-H6BU2E5R.js → tree-sitter-wasm-parser-FJHMEHJS.js} +2 -2
- package/dist/cli/chunks/{types-PM7NT3MH.js → types-NVMRVSBH.js} +2 -2
- package/dist/cli/chunks/unified-memory-PXEJKKMN.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-M7OI5WUU.js +2 -0
- package/dist/cli/chunks/unified-persistence-WR4VDTAF.js +2 -0
- package/dist/cli/chunks/{upgrade-FS2XYC2P.js → upgrade-L2OTYHD3.js} +2 -2
- package/dist/cli/chunks/{validate-4Y2BNN3A.js → validate-3NWRQYTP.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-Z7QXZSUE.js → validate-swarm-MDURRWXK.js} +2 -2
- package/dist/cli/chunks/{vibium-VZ6L3O2G.js → vibium-SZX7RB4H.js} +2 -2
- package/dist/cli/chunks/visual-security-CKSZZHKG.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-H7P37W5U.js → web-tree-sitter-LGQT7JRD.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-IB2VHSZS.js → windsurf-installer-EYYGHPPX.js} +2 -2
- package/dist/cli/chunks/witness-chain-IOQX3XFG.js +2 -0
- package/dist/cli/chunks/{witness-chain-C4DISYJN.js → witness-chain-YYYA2CU3.js} +2 -2
- package/dist/cli/chunks/{workflow-IGM7KVIO.js → workflow-UD45FQAH.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-Z2ZJRWIN.js +2 -0
- package/dist/cli/chunks/wrappers-JXD3KNSR.js +2 -0
- package/dist/kernel/unified-memory-schemas.d.ts +3 -2
- package/dist/kernel/unified-memory-schemas.js +3 -2
- package/dist/kernel/unified-memory.js +3 -1
- package/dist/learning/aqe-learning-engine.js +32 -0
- package/dist/learning/experience-capture.d.ts +8 -0
- package/dist/learning/experience-capture.js +30 -0
- package/dist/learning/pattern-null-store.d.ts +32 -0
- package/dist/learning/pattern-null-store.js +77 -0
- package/dist/learning/pattern-store.d.ts +10 -0
- package/dist/learning/pattern-store.js +23 -0
- package/dist/mcp/bundle.js +377 -347
- package/dist/mcp/handlers/validation-pipeline-handler.d.ts +19 -0
- package/dist/mcp/handlers/validation-pipeline-handler.js +10 -0
- package/dist/migrations/20260611_add_pattern_nulls_table.d.ts +26 -0
- package/dist/migrations/20260611_add_pattern_nulls_table.js +63 -0
- package/dist/validation/pipeline.d.ts +25 -0
- package/dist/validation/pipeline.js +28 -5
- package/dist/validation/steps/requirements.js +5 -0
- package/package.json +2 -1
- package/dist/cli/chunks/adapter-XZVL3DHO.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-YIL25K6W.js +0 -2
- package/dist/cli/chunks/audit-WPIRUJNZ.js +0 -3
- package/dist/cli/chunks/base-YCYV23Q3.js +0 -2
- package/dist/cli/chunks/browser-workflow-ALCOCRA2.js +0 -2
- package/dist/cli/chunks/chunk-EIL7FQC4.js +0 -65
- package/dist/cli/chunks/chunk-RLZDXQNM.js +0 -2
- package/dist/cli/chunks/chunk-W5C7R2LS.js +0 -12
- package/dist/cli/chunks/client-RPB6RYVY.js +0 -2
- package/dist/cli/chunks/core-handlers-QFJT5NX6.js +0 -2
- package/dist/cli/chunks/cross-domain-router-5GJ7WZKX.js +0 -2
- package/dist/cli/chunks/dream-C6VNLTON.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-4SBO27BG.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-W7G6VNXW.js +0 -2
- package/dist/cli/chunks/hnsw-index-LENA5QML.js +0 -2
- package/dist/cli/chunks/hybrid-router-IXHIC45P.js +0 -2
- package/dist/cli/chunks/impact-analyzer-DKGVMYU6.js +0 -2
- package/dist/cli/chunks/init-wizard-BBY3LY3F.js +0 -2
- package/dist/cli/chunks/kernel-7CUW7G62.js +0 -2
- package/dist/cli/chunks/knowledge-graph-Q5CP47IP.js +0 -2
- package/dist/cli/chunks/llm-router-service-MTXCX7TO.js +0 -2
- package/dist/cli/chunks/load-test-YBWXASBO.js +0 -2
- package/dist/cli/chunks/memory-backend-52LANEA3.js +0 -2
- package/dist/cli/chunks/memory-handlers-KFW3HYAP.js +0 -2
- package/dist/cli/chunks/protocol-executor-TRYUS77M.js +0 -2
- package/dist/cli/chunks/provider-manager-6XQQN7FX.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-3IUPE4DJ.js +0 -2
- package/dist/cli/chunks/queen-coordinator-VWPH4XPX.js +0 -2
- package/dist/cli/chunks/router-OIB6ODHA.js +0 -2
- package/dist/cli/chunks/routing-feedback-EKYPCZYG.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-7RXP2Q4Q.js +0 -2
- package/dist/cli/chunks/safe-db-MNKFEPBX.js +0 -2
- package/dist/cli/chunks/schedule-AJXABVXX.js +0 -2
- package/dist/cli/chunks/scheduler-LDWYHIAW.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-A6GKDMOJ.js +0 -2
- package/dist/cli/chunks/sync-CKID22IW.js +0 -2
- package/dist/cli/chunks/token-bootstrap-TIDPJ5IG.js +0 -2
- package/dist/cli/chunks/unified-memory-27QJHABO.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-76VUXR4H.js +0 -2
- package/dist/cli/chunks/unified-persistence-QRCGDEXH.js +0 -2
- package/dist/cli/chunks/visual-security-KB27O7BE.js +0 -2
- package/dist/cli/chunks/witness-chain-EYPXHRDV.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-6AQZ3USU.js +0 -2
- package/dist/cli/chunks/wrappers-PQXC263L.js +0 -2
|
@@ -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.10.
|
|
2
|
-
import{a as p,b as A,c as L}from"./chunk-S73KENCH.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-LSJGF4CV.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
|
|
2
|
+
import{a as p,b as A,c as L}from"./chunk-O4MNYX4X.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-2YZGKQE7.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
|
|
3
3
|
${i.join(`
|
|
4
4
|
`)}
|
|
5
5
|
Ensure prime-radiant-advanced-wasm is installed.`);let r=X(n);if(e.initSync&&typeof e.initSync=="function")e.initSync({module:r});else throw new Error("WASM module does not export initSync function")}emit(e,t){let i=this.eventListeners.get(e);if(i){let n=Array.from(i);for(let r=0;r<n.length;r++)try{n[r](t)}catch{}}}sleep(e){return new Promise(t=>setTimeout(t,e))}enterDegradedMode(e){this.state="degraded",this.fallbackState.mode="fallback",this.fallbackState.consecutiveFailures++,this.fallbackState.totalActivations++,this.degradedModeStartTime||(this.degradedModeStartTime=new Date);let t=Math.min(this.fallbackState.consecutiveFailures-1,W.length-1),i=W[t],n=new Date(Date.now()+i);this.fallbackState.nextRetryAt=n,console.warn(`[WasmLoader] WASM load failed, entering degraded mode. Retry ${this.fallbackState.consecutiveFailures}/3 in ${i}ms. Error: ${e.message}`),this.emit("degraded_mode",{reason:"WASM load failed after retries",retryCount:this.fallbackState.consecutiveFailures,lastError:e.message,activatedAt:this.degradedModeStartTime,nextRetryAt:n}),this.fallbackState.consecutiveFailures<W.length&&this.scheduleBackgroundRetry(i)}scheduleBackgroundRetry(e){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.fallbackState.mode="recovering",this.attemptBackgroundRecovery()},e)}async attemptBackgroundRecovery(){this.state="unloaded",this.loadPromise=null;try{await this.getEngines()}catch{}}emitRecoveryEvent(){if(!this.degradedModeStartTime)return;let e=Date.now()-this.degradedModeStartTime.getTime();console.info(`[WasmLoader] WASM recovered after ${e}ms in degraded mode. Retry count: ${this.fallbackState.consecutiveFailures}`),this.emit("recovered",{degradedDurationMs:e,retryCount:this.fallbackState.consecutiveFailures,version:this.version}),this.degradedModeStartTime=null}},J=new k;var Z={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...R}};export{Q as a,J as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{d as be}from"./chunk-DN65ILSI.js";import{b as D,d as ye}from"./chunk-56RA6YPN.js";import{a as Le}from"./chunk-RLZDXQNM.js";import{c as fe,d as ge,e as Pe}from"./chunk-VC256KH2.js";import{b as P,c as L}from"./chunk-IRS4HKAR.js";import{a as G,b as A,c as J}from"./chunk-S73KENCH.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
|
|
2
|
+
import{d as be}from"./chunk-2CZQA3NN.js";import{a as Le}from"./chunk-434VUSZP.js";import{c as fe,d as ge,e as Pe}from"./chunk-F72A356B.js";import{b as D,d as ye}from"./chunk-DFBVWMX3.js";import{b as P,c as L}from"./chunk-K32AUACO.js";import{a as G,b as A,c as J}from"./chunk-O4MNYX4X.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
|
|
3
3
|
`),t=[],s=[],n="",i=0,o=0,r=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
|
|
4
4
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
|
|
5
5
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
|
|
@@ -20,7 +20,7 @@ import{d as be}from"./chunk-DN65ILSI.js";import{b as D,d as ye}from"./chunk-56RA
|
|
|
20
20
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
|
|
21
21
|
`),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
|
|
22
22
|
`);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
|
|
23
|
-
`);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-H6BU2E5R.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
|
|
23
|
+
`);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-FJHMEHJS.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
|
|
24
24
|
1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
|
|
25
25
|
2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
|
|
26
26
|
3. Architectural boundaries (layers, modules, domains)
|
|
@@ -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.10.
|
|
2
|
-
import{a as
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
|
|
2
|
+
import{a as D,b as _,c as $,d as I}from"./chunk-JX7HZMW5.js";import{a as X}from"./chunk-XOGBTPJI.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-DAUQIXHW.js";import{b as C,f as G,i as U}from"./chunk-LEDF3LGZ.js";import{g as R}from"./chunk-6RFPELCD.js";import{e as H}from"./chunk-Q5432RIH.js";import{i as j,m as de}from"./chunk-RA7HEY5G.js";import{a as z}from"./chunk-434VUSZP.js";import{c as T}from"./chunk-F72A356B.js";import{b as k,c as A}from"./chunk-K32AUACO.js";import{a as h,b as V,c as W}from"./chunk-O4MNYX4X.js";import{S as pe,b as B}from"./chunk-Q4LYWIEX.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
|
|
3
3
|
describe('{{methodName}}', () => {
|
|
4
4
|
it('should {{expectedBehavior}}', {{async}} () => {
|
|
5
5
|
// Arrange
|
|
@@ -317,4 +317,4 @@ On promotion:
|
|
|
317
317
|
AND agent_id = 'aqe-hook-router'
|
|
318
318
|
AND state_key = ?
|
|
319
319
|
AND action_key = ?
|
|
320
|
-
`);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-
|
|
320
|
+
`);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-L7NMMNDO.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-L7NMMNDO.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
|
|
2
2
|
var t=["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock","onnx"];var e={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},r=[{provider:"claude",models:["claude-sonnet-4-6","claude-haiku-4-5-20251001"],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-4o","gpt-4o-mini"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-4","openai/gpt-4o"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["llama3.1","mistral"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],o={id:"default-fallback-chain",entries:r,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},n={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",fallbackChain:o,fallbackBehavior:e,providers:{claude:{enabled:!0,defaultModel:"claude-sonnet-4-6"},openai:{enabled:!0,defaultModel:"gpt-4o"},ollama:{enabled:!0,defaultModel:"llama3.1"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-4"},gemini:{enabled:!1,defaultModel:"gemini-pro"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},a=[{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:64e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];export{t as a,n as b,a 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.10.
|
|
2
|
-
import{b as y,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.10.6");process.exit(0)}
|
|
2
|
+
import{b as y,d as p}from"./chunk-ULEVKOWQ.js";import{i as h}from"./chunk-BHD6THT5.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F as f};
|