agentic-qe 3.14.5 → 3.14.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +150 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/adapters/ag-ui/event-types.d.ts +1 -1
- package/dist/audit/witness-chain-hash.d.ts +18 -0
- package/dist/audit/witness-chain-hash.js +37 -0
- package/dist/audit/witness-chain-repair.d.ts +71 -0
- package/dist/audit/witness-chain-repair.js +203 -0
- package/dist/audit/witness-chain-verifier.d.ts +152 -0
- package/dist/audit/witness-chain-verifier.js +293 -0
- package/dist/audit/witness-chain.d.ts +10 -43
- package/dist/audit/witness-chain.js +16 -106
- package/dist/audit/witness-findings.js +4 -1
- package/dist/cli/bundle.js +8 -8
- package/dist/cli/chunks/adapter-TVQKH65T.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-AK2W76RG.js +2 -0
- package/dist/cli/chunks/{agent-handler-V6CZ7Q6S.js → agent-handler-MGZCWHIY.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-ZMD6ULC3.js → agent-memory-branch-JZ54MCSP.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-ULGTVVWE.js +2 -0
- package/dist/cli/chunks/{arena-QLSBESC7.js → arena-CUVH3V7H.js} +2 -2
- package/dist/cli/chunks/{arena-4UPAEHFT.js → arena-YSWTKBCL.js} +4 -4
- package/dist/cli/chunks/audit-LVU76QGA.js +4 -0
- package/dist/cli/chunks/base-W42BURDL.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-4DSBPDRH.js → better-sqlite3-DB3LOJQU.js} +2 -2
- package/dist/cli/chunks/{brain-handler-GBY4EZ4P.js → brain-handler-SD63KOQ6.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-XYBVXCNO.js → branch-enumerator-4MNOPUC7.js} +2 -2
- package/dist/cli/chunks/{browser-32F6MREU.js → browser-OLPNTWQE.js} +2 -2
- package/dist/cli/chunks/browser-workflow-HKGHFFFT.js +2 -0
- package/dist/cli/chunks/{chunk-WLXK2KNU.js → chunk-23CX7JNL.js} +2 -2
- package/dist/cli/chunks/{chunk-O3JTQ7N4.js → chunk-25P6JA6V.js} +1 -1
- package/dist/cli/chunks/{chunk-DO6EI5KB.js → chunk-2G63VIJE.js} +1 -1
- package/dist/cli/chunks/{chunk-G3L5L6YQ.js → chunk-2IMSJ7IO.js} +1 -1
- package/dist/cli/chunks/{chunk-RD6TEZ64.js → chunk-36VKMAMN.js} +2 -2
- package/dist/cli/chunks/{chunk-KIP6WZGV.js → chunk-3M7J4U74.js} +3 -3
- package/dist/cli/chunks/chunk-3QJU4Q4R.js +5 -0
- package/dist/cli/chunks/{chunk-2JGEZHWY.js → chunk-4EKV7PHB.js} +2 -2
- package/dist/cli/chunks/chunk-4INST4ZL.js +4 -0
- package/dist/cli/chunks/{chunk-DPBRWP4J.js → chunk-53BXTTRO.js} +3 -3
- package/dist/cli/chunks/chunk-5D7ZFWDS.js +2 -0
- package/dist/cli/chunks/{chunk-XLAUGSW7.js → chunk-5FSLMYAC.js} +2 -2
- package/dist/cli/chunks/chunk-5GFKTJ65.js +4 -0
- package/dist/cli/chunks/{chunk-WOIGKU2N.js → chunk-5U6N4V5M.js} +11 -11
- package/dist/cli/chunks/{chunk-PSPKSUF6.js → chunk-6EGS77BB.js} +1 -1
- package/dist/cli/chunks/{chunk-QIRL6B3C.js → chunk-6PJPQGF4.js} +2 -2
- package/dist/cli/chunks/{chunk-I6X3EGJI.js → chunk-6RD44SCE.js} +1 -1
- package/dist/cli/chunks/{chunk-IGBEJ4UJ.js → chunk-74IOEOMH.js} +2 -2
- package/dist/cli/chunks/{chunk-E3W6XQ57.js → chunk-77QZHIVX.js} +2 -2
- package/dist/cli/chunks/{chunk-R74ZKREV.js → chunk-7EZ2Z2CK.js} +1 -1
- package/dist/cli/chunks/{chunk-UTBYJ4RF.js → chunk-7MIOK72I.js} +18 -35
- package/dist/cli/chunks/{chunk-URVHZPWY.js → chunk-7QYOTUOX.js} +2 -2
- package/dist/cli/chunks/{chunk-K27SU3RE.js → chunk-A2VUCUTT.js} +2 -2
- package/dist/cli/chunks/{chunk-2KJQ2UQE.js → chunk-A3DK3XNZ.js} +1 -1
- package/dist/cli/chunks/{chunk-5D36YHS3.js → chunk-A5MA7A23.js} +4 -4
- package/dist/cli/chunks/{chunk-WJHWH5D2.js → chunk-AEUEMVJK.js} +2 -2
- package/dist/cli/chunks/{chunk-6CR4VQBQ.js → chunk-AJUBT4NP.js} +2 -2
- package/dist/cli/chunks/chunk-B2YGVSOP.js +27 -0
- package/dist/cli/chunks/{chunk-D6OUCB2H.js → chunk-B4I43GE2.js} +2 -2
- package/dist/cli/chunks/{chunk-WK7B4B6Y.js → chunk-BD7FEUN3.js} +2 -2
- package/dist/cli/chunks/{chunk-OEIQTWQP.js → chunk-BE4KALTE.js} +1 -1
- package/dist/cli/chunks/{chunk-JROVR6YS.js → chunk-BEFTQVEW.js} +2 -2
- package/dist/cli/chunks/{chunk-HBCGYMQU.js → chunk-BLG7SH4A.js} +1 -1
- package/dist/cli/chunks/{chunk-2OMLTYQK.js → chunk-C3FXFU2T.js} +1 -1
- package/dist/cli/chunks/{chunk-6A44AOGN.js → chunk-CBONQM5D.js} +2 -2
- package/dist/cli/chunks/{chunk-73EI4C2E.js → chunk-CQNMGK6Y.js} +2 -2
- package/dist/cli/chunks/{chunk-IIAR5S7Q.js → chunk-CVOQ6ESD.js} +2 -2
- package/dist/cli/chunks/{chunk-6TU7FEMD.js → chunk-DOBKEXMJ.js} +1 -1
- package/dist/cli/chunks/{chunk-BHFR2EXL.js → chunk-DYTQHRUS.js} +1 -1
- package/dist/cli/chunks/{chunk-E4AZXCT5.js → chunk-EADSQN5T.js} +1 -1
- package/dist/cli/chunks/{chunk-CYE2TJFV.js → chunk-EGOIIUBD.js} +2 -2
- package/dist/cli/chunks/{chunk-DKUBQQFG.js → chunk-EIGRV3J6.js} +2 -2
- package/dist/cli/chunks/{chunk-RP2ZKPYV.js → chunk-EJ6MMYLK.js} +1 -1
- package/dist/cli/chunks/{chunk-HSVKZ5KI.js → chunk-ENK44A6Q.js} +2 -2
- package/dist/cli/chunks/{chunk-67YV75XP.js → chunk-EYXE2XKP.js} +2 -2
- package/dist/cli/chunks/{chunk-HYEJJJY3.js → chunk-F2OPFVQH.js} +1 -1
- package/dist/cli/chunks/{chunk-XUR2M2WB.js → chunk-FBZC4IGB.js} +2 -2
- package/dist/cli/chunks/{chunk-BXVAVFGU.js → chunk-FSSR6WBE.js} +2 -2
- package/dist/cli/chunks/{chunk-W2XCZU62.js → chunk-FW4DJ4FJ.js} +1 -1
- package/dist/cli/chunks/{chunk-KKHYJF5U.js → chunk-FYPX5WBJ.js} +1 -1
- package/dist/cli/chunks/{chunk-K7NJHFLZ.js → chunk-G367W7XR.js} +3 -3
- package/dist/cli/chunks/{chunk-IUDWEOLX.js → chunk-GLGKQX2V.js} +2 -2
- package/dist/cli/chunks/{chunk-JVQBWYHW.js → chunk-GV4DYPJP.js} +2 -2
- package/dist/cli/chunks/{chunk-GTKCGPJZ.js → chunk-GVVFTFMB.js} +2 -2
- package/dist/cli/chunks/{chunk-AFEDJ3RU.js → chunk-H5RQPO3X.js} +2 -2
- package/dist/cli/chunks/{chunk-4FWTLJEP.js → chunk-HPWWYT67.js} +2 -2
- package/dist/cli/chunks/{chunk-G3W6BMVJ.js → chunk-HXXHMLJ5.js} +1 -1
- package/dist/cli/chunks/{chunk-NU7UTXMP.js → chunk-HYFQUWNB.js} +2 -2
- package/dist/cli/chunks/chunk-HYOPJHHW.js +2 -0
- package/dist/cli/chunks/{chunk-6LKDHEBY.js → chunk-HZY42OVU.js} +2 -2
- package/dist/cli/chunks/{chunk-C3HQL6S4.js → chunk-IAENZ2DR.js} +2 -2
- package/dist/cli/chunks/{chunk-M23ZOZVY.js → chunk-IEJ7ZV3M.js} +1 -1
- package/dist/cli/chunks/{chunk-RIZVC4XY.js → chunk-IWFFO6VT.js} +2 -2
- package/dist/cli/chunks/chunk-J7AQZLIH.js +21 -0
- package/dist/cli/chunks/{chunk-3KDL6QDK.js → chunk-JHJUSSAU.js} +2 -2
- package/dist/cli/chunks/{chunk-DLF5BOJD.js → chunk-JOZ47MV6.js} +1 -1
- package/dist/cli/chunks/{chunk-ELBZON4V.js → chunk-JZT7BU44.js} +2 -2
- package/dist/cli/chunks/{chunk-3DDXWYMO.js → chunk-KD2BLA5Y.js} +1 -1
- package/dist/cli/chunks/{chunk-VD5IO5EO.js → chunk-KUHLTVWC.js} +1 -1
- package/dist/cli/chunks/{chunk-YDFL445W.js → chunk-LU2EDWQK.js} +2 -2
- package/dist/cli/chunks/chunk-LXZMP3VX.js +736 -0
- package/dist/cli/chunks/{chunk-3YUB5HER.js → chunk-LY7MFGBD.js} +196 -187
- package/dist/cli/chunks/chunk-MM56VPNE.js +180 -0
- package/dist/cli/chunks/{chunk-37TUN44F.js → chunk-MNQN7UZX.js} +2 -2
- package/dist/cli/chunks/{chunk-7DETTOPZ.js → chunk-MQZ53OR3.js} +2 -2
- package/dist/cli/chunks/{chunk-BYG36QC5.js → chunk-MT7UNBZ7.js} +2 -2
- package/dist/cli/chunks/{chunk-JES6R5KP.js → chunk-MZB2UV2O.js} +1 -1
- package/dist/cli/chunks/{chunk-QZMUXJHZ.js → chunk-MZMG6CUJ.js} +2 -2
- package/dist/cli/chunks/chunk-N5XOXPHZ.js +4 -0
- package/dist/cli/chunks/{chunk-RD2VGOUH.js → chunk-NBLDBVAW.js} +1 -1
- package/dist/cli/chunks/{chunk-HVU64GP5.js → chunk-ND4QTZOL.js} +2 -2
- package/dist/cli/chunks/{chunk-SQF6HRXR.js → chunk-NHUGHAY6.js} +1 -1
- package/dist/cli/chunks/{chunk-TUSSPKRM.js → chunk-NOHWJOBS.js} +1 -1
- package/dist/cli/chunks/{chunk-NVYBM3R4.js → chunk-O5V7RHVG.js} +2 -2
- package/dist/cli/chunks/{chunk-6VAZAHQG.js → chunk-O6MO5KMR.js} +2 -2
- package/dist/cli/chunks/{chunk-IUHB5GVS.js → chunk-OAZX6WFU.js} +2 -2
- package/dist/cli/chunks/{chunk-LSUILON7.js → chunk-OEPNNLR4.js} +1 -1
- package/dist/cli/chunks/{chunk-IJHCIXJC.js → chunk-OIDWDGLG.js} +2 -2
- package/dist/cli/chunks/{chunk-CPC7FN52.js → chunk-ON2UTP2U.js} +2 -2
- package/dist/cli/chunks/{chunk-UJWAWIRV.js → chunk-ONR2NXXD.js} +7 -7
- package/dist/cli/chunks/{chunk-7VFY7TUR.js → chunk-OXHF3L2T.js} +2 -2
- package/dist/cli/chunks/{chunk-QYOGD2VW.js → chunk-OZGIOKEA.js} +1 -1
- package/dist/cli/chunks/{chunk-WJTSY5MC.js → chunk-P2UPYSDJ.js} +1 -1
- package/dist/cli/chunks/{chunk-52L77RMG.js → chunk-P7XSPP5D.js} +2 -2
- package/dist/cli/chunks/{chunk-M5AEL7IS.js → chunk-PCJQCEBA.js} +2 -2
- package/dist/cli/chunks/chunk-PELENDDQ.js +2 -0
- package/dist/cli/chunks/{chunk-C3Z4VVHP.js → chunk-PYKY22GC.js} +5 -5
- package/dist/cli/chunks/{chunk-AF4XKLXO.js → chunk-Q3NSU24F.js} +2 -2
- package/dist/cli/chunks/chunk-Q6NTEICT.js +2 -0
- package/dist/cli/chunks/chunk-QFETNCNN.js +12 -0
- package/dist/cli/chunks/{chunk-KYA5LARK.js → chunk-QGOWNVVG.js} +1 -1
- package/dist/cli/chunks/{chunk-Y5L3ES4L.js → chunk-QPLSYEWJ.js} +2 -2
- package/dist/cli/chunks/{chunk-F34OAHOM.js → chunk-QQFQDEUE.js} +2 -2
- package/dist/cli/chunks/{chunk-EFV4ADMO.js → chunk-QUORH2MG.js} +55 -79
- package/dist/cli/chunks/{chunk-QWUXCG2L.js → chunk-QVH5Y7AP.js} +1 -1
- package/dist/cli/chunks/{chunk-I2NENQ44.js → chunk-RC2A4JZ5.js} +2 -2
- package/dist/cli/chunks/{chunk-XZSMZHM2.js → chunk-RDGPXENG.js} +2 -2
- package/dist/cli/chunks/{chunk-N7H767TP.js → chunk-RKI3IQKQ.js} +2 -2
- package/dist/cli/chunks/{chunk-LULD4JV2.js → chunk-RKUAWQOF.js} +2 -2
- package/dist/cli/chunks/chunk-RLW25X66.js +2 -0
- package/dist/cli/chunks/{chunk-UKGXWW64.js → chunk-ROVZSZCS.js} +3 -3
- package/dist/cli/chunks/{chunk-EOR2UT72.js → chunk-RT6O2HW2.js} +2 -2
- package/dist/cli/chunks/{chunk-75QJ5HWE.js → chunk-SM2YJ2AL.js} +2 -2
- package/dist/cli/chunks/{chunk-KO4FNAUR.js → chunk-SRPLERER.js} +3 -3
- package/dist/cli/chunks/{chunk-NRE4NAVA.js → chunk-T77GZF4B.js} +1 -1
- package/dist/cli/chunks/{chunk-R6IU3EWP.js → chunk-TFK2AYIN.js} +2 -2
- package/dist/cli/chunks/chunk-TW3SR4TS.js +2 -0
- package/dist/cli/chunks/{chunk-IYTLXUBO.js → chunk-TXSPBLBT.js} +2 -2
- package/dist/cli/chunks/chunk-UA7TDVL7.js +12 -0
- package/dist/cli/chunks/{chunk-WX6RRIGW.js → chunk-UBJG3IHT.js} +2 -2
- package/dist/cli/chunks/{chunk-NQI7FWCS.js → chunk-UFSVUBTR.js} +2 -2
- package/dist/cli/chunks/{chunk-FUNGTIF2.js → chunk-UOI6ULCH.js} +2 -2
- package/dist/cli/chunks/{chunk-HVXJC3OC.js → chunk-UYUJT6QO.js} +2 -2
- package/dist/cli/chunks/{chunk-KEY43ANX.js → chunk-V5AK56DA.js} +2 -2
- package/dist/cli/chunks/{chunk-XFPPERA2.js → chunk-V6RE4YRQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DDCIYOGT.js → chunk-VW6FRMLW.js} +2 -2
- package/dist/cli/chunks/chunk-VXKWNRGA.js +2 -0
- package/dist/cli/chunks/{chunk-CVMNJSCB.js → chunk-VYDVI6FZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7JZJJA7U.js → chunk-WF6UISKW.js} +3 -3
- package/dist/cli/chunks/{chunk-SQKW3B6B.js → chunk-WIH522AP.js} +1 -1
- package/dist/cli/chunks/{chunk-KLTP5IDB.js → chunk-WOV6XI3A.js} +1 -1
- package/dist/cli/chunks/{chunk-VTOVWHEM.js → chunk-X7ADKL7T.js} +2 -2
- package/dist/cli/chunks/{chunk-SX4JLSLV.js → chunk-XBYQ2BS4.js} +2 -2
- package/dist/cli/chunks/{chunk-E4EYPYR3.js → chunk-XL5KIYE3.js} +2 -2
- package/dist/cli/chunks/{chunk-3VIXOHMS.js → chunk-XWYELBZS.js} +1 -1
- package/dist/cli/chunks/{chunk-YQGPQBCX.js → chunk-XYLQZWF6.js} +2 -2
- package/dist/cli/chunks/{chunk-XEZIIQYJ.js → chunk-Y6AKKQIQ.js} +1 -1
- package/dist/cli/chunks/{chunk-BJPL6THQ.js → chunk-YMW57PEL.js} +1 -1
- package/dist/cli/chunks/{chunk-JSZ663MU.js → chunk-YO4ESCB4.js} +1 -1
- package/dist/cli/chunks/{chunk-AMMQOV35.js → chunk-YRHTQZU4.js} +2 -2
- package/dist/cli/chunks/chunk-Z4Q5PCRZ.js +65 -0
- package/dist/cli/chunks/{chunk-RKOUXVZZ.js → chunk-ZELWDJXT.js} +2 -2
- package/dist/cli/chunks/{chunk-QRCIZFNK.js → chunk-ZQZD55MN.js} +2 -2
- package/dist/cli/chunks/{chunk-UMGFMKDW.js → chunk-ZS4XVJGV.js} +2 -2
- package/dist/cli/chunks/{chunk-6ITZZIQX.js → chunk-ZUB5YOCM.js} +2 -2
- package/dist/cli/chunks/chunk-ZUOVNFXK.js +2 -0
- package/dist/cli/chunks/{chunk-RGGK6VZ7.js → chunk-ZWEKAEEV.js} +1 -1
- package/dist/cli/chunks/{ci-RACDAJMR.js → ci-J3TDK5RA.js} +8 -8
- package/dist/cli/chunks/{ci-output-EHRSZBKG.js → ci-output-RLS32FUY.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-GBV7M5XG.js → circuit-breaker-MRCC7WCM.js} +2 -2
- package/dist/cli/chunks/claude-flow-setup-LIZCEKDF.js +2 -0
- package/dist/cli/chunks/client-3BD2DI4N.js +2 -0
- package/dist/cli/chunks/{cline-installer-W4NMXJSG.js → cline-installer-T7H6R2RC.js} +2 -2
- package/dist/cli/chunks/{code-JWXJMYXB.js → code-XMBLI7OF.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-RVI2IFTM.js → code-index-extractor-QS7BYLEX.js} +2 -2
- package/dist/cli/chunks/{codex-installer-3BORJINH.js → codex-installer-6PGT5FM6.js} +6 -6
- package/dist/cli/chunks/{completions-A55NCTAO.js → completions-2A3WRXY2.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-JCXHGGLY.js → complexity-analyzer-23HOOGJ7.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-PUVFMGYW.js → continuedev-installer-4FSF7B3N.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-4DCMYWHB.js → copilot-installer-A5GRQQUU.js} +2 -2
- package/dist/cli/chunks/core-handlers-C3H2ZCS2.js +2 -0
- package/dist/cli/chunks/{cost-tracker-5TV2GGKY.js → cost-tracker-Z4STQ5VB.js} +2 -2
- package/dist/cli/chunks/{coverage-NNWM7TX3.js → coverage-NUPP6KZZ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-JCQ7SWDP.js +2 -0
- package/dist/cli/chunks/{cursor-installer-4NCHGJGK.js → cursor-installer-FVJ7ROPJ.js} +2 -2
- package/dist/cli/chunks/{daemon-QIKCXKWO.js → daemon-7ZZA2MMN.js} +4 -4
- package/dist/cli/chunks/{daemon-T4JO4IXP.js → daemon-D662EX5N.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-RPAAIDAD.js → dag-attention-scheduler-IB4TQ2KA.js} +2 -2
- package/dist/cli/chunks/{detect-SBEEVDSN.js → detect-LGLBZN4I.js} +2 -2
- package/dist/cli/chunks/{dist-node-ZHI6NCSU.js → dist-node-Z3OL42YE.js} +2 -2
- package/dist/cli/chunks/{domain-handler-LBC3GJ7Z.js → domain-handler-L3CLNL7U.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-H6IZ5USZ.js → domain-plugins-GQ3V5X6L.js} +2 -2
- package/dist/cli/chunks/domain-transfer-MFCI76IY.js +2 -0
- package/dist/cli/chunks/dream-FTP33IJB.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-AHTR7CRU.js → embed-and-insert-pattern-UGD6USYH.js} +2 -2
- package/dist/cli/chunks/{eval-DZU2KISM.js → eval-3B7UIYGY.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-5IQCWKSL.js → experience-capture-middleware-3RQ4NYY3.js} +3 -3
- package/dist/cli/chunks/{fast-paths-2KLDUWCY.js → fast-paths-QOSAEPYD.js} +2 -2
- package/dist/cli/chunks/{feature-flags-7AC3XDZA.js → feature-flags-3S5TH6P4.js} +2 -2
- package/dist/cli/chunks/{feature-flags-N6UAEZY4.js → feature-flags-TLF4NKOH.js} +2 -2
- package/dist/cli/chunks/{file-discovery-5SDIW4V2.js → file-discovery-AEVMJRNB.js} +2 -2
- package/dist/cli/chunks/{fleet-ZIQCAZ2Y.js → fleet-E6WTXWFL.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-DUMBZJEV.js → gnn-wrapper-MCKH3AUU.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-6HVM6ZMR.js → heartbeat-handler-U7XENHRR.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-HXBJVJL2.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-TU6WG2ME.js +2 -0
- package/dist/cli/chunks/hnsw-index-MS5KODD7.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-5DRL5FLX.js → hnsw-legacy-bridge-5GW4SAEI.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-GW67GTCL.js → hnswlib-node-7BLZBK5T.js} +2 -2
- package/dist/cli/chunks/{hooks-QHH6FVO4.js → hooks-F3O2SB6H.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-HT45LBHC.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-7XDCCVG2.js → hypergraph-engine-PV4EKXHB.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-QHF7NOU5.js → hypergraph-handler-VOWO5ZTW.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-AP4AGTG5.js +2 -0
- package/dist/cli/chunks/{init-handler-5UIVOM7K.js → init-handler-ENJ5ONJX.js} +16 -14
- package/dist/cli/chunks/init-wizard-I5DFZUQL.js +2 -0
- package/dist/cli/chunks/kernel-MISPSPPA.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-TGGV6K5Q.js → kilocode-installer-HNNJOOPE.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-4XYBHZWW.js → kiro-installer-UZBIQ3IC.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-L26JESGE.js +2 -0
- package/dist/cli/chunks/{learning-STE5W6BS.js → learning-YMLCVFUT.js} +3 -3
- package/dist/cli/chunks/{llm-router-NKF7J3RI.js → llm-router-YWTARCCT.js} +4 -4
- package/dist/cli/chunks/llm-router-service-MWGC43ZA.js +2 -0
- package/dist/cli/chunks/{load-B2T77UJQ.js → load-DKE3F3IP.js} +2 -2
- package/dist/cli/chunks/load-test-H5ISNNM5.js +2 -0
- package/dist/cli/chunks/mcp-5PSGIUCW.js +2 -0
- package/dist/cli/chunks/{memory-WRFZKG56.js → memory-3L3O6JMM.js} +5 -5
- package/dist/cli/chunks/memory-backend-HWDNOBKW.js +2 -0
- package/dist/cli/chunks/memory-handlers-ZFDVQZM5.js +2 -0
- package/dist/cli/chunks/multi-model-executor-AEEO7IA4.js +14 -0
- package/dist/cli/chunks/{opencode-installer-J36EMQU7.js → opencode-installer-ABBO355U.js} +2 -2
- package/dist/cli/chunks/orchestrator-E36Q7MKE.js +393 -0
- package/dist/cli/chunks/pattern-null-store-GQP6ICWK.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-BVMTWI3E.js → pattern-usage-recorder-H4XKSID4.js} +2 -2
- package/dist/cli/chunks/{pipeline-OWAHDUAQ.js → pipeline-BGFEHXIN.js} +2 -2
- package/dist/cli/chunks/{platform-ANGBFWBV.js → platform-GK7ZVDJI.js} +2 -2
- package/dist/cli/chunks/{plugin-OO7ON2YW.js → plugin-CAH2CKI6.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-HFG3BXWU.js → prime-radiant-advanced-wasm-M5EYRONA.js} +2 -2
- package/dist/cli/chunks/{project-root-LNOYVTYY.js → project-root-BSNZC243.js} +2 -2
- package/dist/cli/chunks/protocol-executor-AD5A4DAI.js +2 -0
- package/dist/cli/chunks/{protocol-handler-CE3Q6LY4.js → protocol-handler-JDSSC2SF.js} +2 -2
- package/dist/cli/chunks/{prove-7XPN53PY.js → prove-ANPTOZJE.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-W3Z2PKTR.js +2 -0
- package/dist/cli/chunks/{quality-TT23JRFX.js → quality-SXWGYRQR.js} +2 -2
- package/dist/cli/chunks/{quality-gate-PPPRP255.js → quality-gate-GYNCA4ZY.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-HQRHLIJX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-EYNZIFJE.js → real-embeddings-WSRYAOZM.js} +2 -2
- package/dist/cli/chunks/{ref-validation-QQR64ZXD.js → ref-validation-AZ3LRWEK.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-UIGS7ZJD.js → roocode-installer-2QKGFIEU.js} +2 -2
- package/dist/cli/chunks/router-MTP5LH4H.js +2 -0
- package/dist/cli/chunks/routing-feedback-GWETVB4L.js +2 -0
- package/dist/cli/chunks/{routing-handler-6AENUIRG.js → routing-handler-UYDC5MMD.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5AWMEV34.js → ruvector-commands-QXADPVEY.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-4UE5S7WP.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-PHH3HF4Q.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-NWRJ7C22.js → rvf-migration-coordinator-GD4NBFKT.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-KTLZBUWV.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-ISKRP563.js → rvf-store-integrity-7SXG66IL.js} +2 -2
- package/dist/cli/chunks/safe-db-FWWGAPVE.js +2 -0
- package/dist/cli/chunks/schedule-TPA4V4D5.js +2 -0
- package/dist/cli/chunks/scheduler-5ZTEPNDD.js +2 -0
- package/dist/cli/chunks/{security-325A7FMB.js → security-YKB622PK.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-KMLAV7JK.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-THFDYS2Z.js → shared-rvf-dual-writer-OYY27DFV.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-HPTT624C.js +2 -0
- package/dist/cli/chunks/{standalone-memory-UD4MJ6GZ.js → standalone-memory-2DOABVLC.js} +2 -2
- package/dist/cli/chunks/{status-handler-CPFTN4XL.js → status-handler-EXRKETV7.js} +2 -2
- package/dist/cli/chunks/{structural-health-2MG2IVBL.js → structural-health-2SKK6DU6.js} +2 -2
- package/dist/cli/chunks/sync-DQ2YUNI6.js +2 -0
- package/dist/cli/chunks/{sync-EE4VVKOW.js → sync-UW7SX7GO.js} +2 -2
- package/dist/cli/chunks/{task-handler-7H5OYJG4.js → task-handler-LYQ6WYUY.js} +2 -2
- package/dist/cli/chunks/task-handlers-DIJO232S.js +9 -0
- package/dist/cli/chunks/test-WRHZMUCW.js +33 -0
- package/dist/cli/chunks/{test-scheduling-CHQ4ZLLJ.js → test-scheduling-HI23RXFK.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-23SA6SWZ.js +2 -0
- package/dist/cli/chunks/{token-usage-EBXUJNRB.js → token-usage-M7RRDPXO.js} +2 -2
- package/dist/cli/chunks/{transformers-ZEKS2OJZ.js → transformers-4TC35KKS.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-F4LTKAWD.js +2 -0
- package/dist/cli/chunks/{types-KYAA5VLV.js → types-NBXV6LXQ.js} +2 -2
- package/dist/cli/chunks/unified-memory-OVFEPRPS.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-KKRSCZHR.js +2 -0
- package/dist/cli/chunks/unified-persistence-7GLR4RI3.js +2 -0
- package/dist/cli/chunks/{upgrade-UJBJ5AYM.js → upgrade-4BGOU5RM.js} +2 -2
- package/dist/cli/chunks/{validate-RUV6YMWS.js → validate-EDWAR63H.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-IVEVMGVM.js → validate-swarm-VI72CPR7.js} +2 -2
- package/dist/cli/chunks/visual-security-2FUM5GLI.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-AVWA6HKE.js → web-tree-sitter-Y5XBRQXF.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-DAH7HI2W.js → windsurf-installer-VEX23WAF.js} +2 -2
- package/dist/cli/chunks/witness-chain-3YNL6YGY.js +2 -0
- package/dist/cli/chunks/witness-chain-MH6GA5L6.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-MJZGZRWT.js +2 -0
- package/dist/cli/chunks/witness-chain-verifier-TTJYXTBE.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-JSTBMG43.js → witness-key-manager-EM6YXYOY.js} +2 -2
- package/dist/cli/chunks/{workflow-TWOIA6LZ.js → workflow-2RBDOM7V.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-H6G65YKU.js +2 -0
- package/dist/cli/chunks/wrappers-5OTAVVOV.js +2 -0
- package/dist/cli/commands/audit.d.ts +20 -2
- package/dist/cli/commands/audit.js +158 -16
- package/dist/cli/commands/ci.js +1 -1
- package/dist/cli/commands/claude-flow-setup.js +5 -4
- package/dist/cli/commands/test.js +18 -3
- package/dist/cli/handlers/init-handler.d.ts +2 -0
- package/dist/cli/handlers/init-handler.js +8 -2
- package/dist/cli/index.js +10 -1
- package/dist/coordination/handlers/test-execution-handlers.js +13 -8
- package/dist/coordination/index.d.ts +1 -1
- package/dist/coordination/queen-event-handlers.js +9 -6
- package/dist/coordination/result-saver.js +1 -1
- package/dist/coordination/services/index.d.ts +1 -1
- package/dist/coordination/services/task-audit-logger.d.ts +38 -13
- package/dist/coordination/services/task-audit-logger.js +33 -5
- package/dist/coordination/task-executor.d.ts +5 -0
- package/dist/coordination/task-executor.js +10 -5
- package/dist/domains/test-generation/coordinator.js +6 -5
- package/dist/domains/test-generation/interfaces.d.ts +11 -1
- package/dist/domains/test-generation/services/behavior-example-validation.d.ts +36 -0
- package/dist/domains/test-generation/services/behavior-example-validation.js +89 -0
- package/dist/domains/test-generation/services/behavior-examples.d.ts +8 -0
- package/dist/domains/test-generation/services/behavior-examples.js +65 -0
- package/dist/domains/test-generation/services/test-generator.d.ts +1 -1
- package/dist/domains/test-generation/services/test-generator.js +59 -30
- package/dist/domains/visual-accessibility/services/axe-core-audit.d.ts +0 -15
- package/dist/domains/visual-accessibility/services/axe-core-audit.js +12 -10
- package/dist/init/agents-installer.d.ts +4 -0
- package/dist/init/agents-installer.js +24 -11
- package/dist/init/browser-engine-installer.d.ts +5 -5
- package/dist/init/browser-engine-installer.js +28 -6
- package/dist/init/codex-installer.js +4 -2
- package/dist/init/idempotent-write.d.ts +53 -0
- package/dist/init/idempotent-write.js +160 -0
- package/dist/init/init-wizard.d.ts +2 -0
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/05-learning.js +3 -1
- package/dist/init/phases/07-hooks.js +32 -16
- package/dist/init/phases/08-mcp.js +4 -2
- package/dist/init/phases/09-assets.js +8 -18
- package/dist/init/phases/10-workers.js +7 -5
- package/dist/init/phases/12-verification.js +7 -2
- package/dist/init/phases/phase-interface.d.ts +2 -0
- package/dist/init/project-analyzer.d.ts +9 -0
- package/dist/init/project-analyzer.js +20 -1
- package/dist/init/self-configurator.d.ts +5 -3
- package/dist/init/self-configurator.js +18 -29
- package/dist/init/skills-installer.js +4 -2
- package/dist/init/types.d.ts +6 -0
- package/dist/init/types.js +20 -24
- package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +2 -5
- package/dist/integrations/coherence/coherence-service.js +84 -24
- package/dist/integrations/coherence/vote-tally.d.ts +38 -0
- package/dist/integrations/coherence/vote-tally.js +39 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +23 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +24 -0
- package/dist/integrations/vibium/client.d.ts +1 -0
- package/dist/integrations/vibium/client.js +24 -11
- package/dist/integrations/vibium/runtime.d.ts +14 -0
- package/dist/integrations/vibium/runtime.js +94 -0
- package/dist/kernel/kernel.js +3 -2
- package/dist/kernel/pattern-fts-self-heal.d.ts +63 -0
- package/dist/kernel/pattern-fts-self-heal.js +193 -0
- package/dist/kernel/process-lifecycle.d.ts +60 -0
- package/dist/kernel/process-lifecycle.js +91 -0
- package/dist/kernel/unified-memory-schemas.d.ts +15 -1
- package/dist/kernel/unified-memory-schemas.js +53 -25
- package/dist/kernel/unified-memory.js +31 -34
- package/dist/kernel/unified-persistence.js +12 -6
- package/dist/learning/experience-capture.d.ts +2 -1
- package/dist/learning/experience-capture.js +23 -8
- package/dist/learning/pattern-store.d.ts +12 -1
- package/dist/learning/pattern-store.js +45 -30
- package/dist/learning/qe-patterns.d.ts +12 -0
- package/dist/learning/qe-patterns.js +7 -1
- package/dist/learning/qe-reasoning-bank.d.ts +1 -0
- package/dist/learning/qe-reasoning-bank.js +17 -4
- package/dist/learning/real-qe-reasoning-bank.d.ts +9 -4
- package/dist/learning/real-qe-reasoning-bank.js +28 -4
- package/dist/learning/rvf-pattern-store.js +36 -23
- package/dist/learning/sqlite-persistence.d.ts +8 -1
- package/dist/learning/sqlite-persistence.js +58 -33
- package/dist/logging/console-logger.d.ts +2 -5
- package/dist/logging/console-logger.js +10 -46
- package/dist/logging/index.d.ts +2 -0
- package/dist/logging/index.js +1 -0
- package/dist/logging/redaction.d.ts +27 -0
- package/dist/logging/redaction.js +170 -0
- package/dist/mcp/bundle.js +522 -545
- package/dist/mcp/entry.js +52 -6
- package/dist/mcp/handlers/core-handlers.js +5 -4
- package/dist/mcp/handlers/domain-handler-configs.js +12 -4
- package/dist/mcp/handlers/task-handlers.js +11 -7
- package/dist/mcp/protocol-server.js +20 -4
- package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
- package/dist/mcp/services/reasoning-bank-service.js +5 -1
- package/dist/mcp/tools/base.d.ts +9 -2
- package/dist/mcp/tools/base.js +7 -0
- package/dist/mcp/tools/coherence/consensus.js +51 -2
- package/dist/mcp/tools/planning/goap-plan.d.ts +20 -7
- package/dist/mcp/tools/planning/goap-plan.js +92 -20
- package/dist/mcp/tools/planning/goap-status.d.ts +37 -12
- package/dist/mcp/tools/planning/goap-status.js +52 -23
- package/dist/mcp/tools/planning/world-state.d.ts +101 -0
- package/dist/mcp/tools/planning/world-state.js +274 -0
- package/dist/mcp/tools/test-execution/e2e-execute.js +9 -1
- package/dist/mcp/tools/test-generation/generate.d.ts +6 -1
- package/dist/mcp/tools/test-generation/generate.js +8 -0
- package/dist/mcp/types.d.ts +10 -4
- package/dist/planning/goap-planner.d.ts +60 -4
- package/dist/planning/goap-planner.js +218 -60
- package/dist/planning/index.d.ts +1 -1
- package/dist/planning/index.js +1 -1
- package/dist/planning/plan-executor.d.ts +20 -1
- package/dist/planning/plan-executor.js +209 -100
- package/dist/planning/types.d.ts +16 -0
- package/dist/planning/types.js +17 -0
- package/dist/shared/error-utils.d.ts +15 -0
- package/dist/shared/error-utils.js +21 -0
- package/dist/shared/events/domain-events.d.ts +2 -1
- package/package.json +10 -6
- package/dist/cli/chunks/adapter-IYC62SXA.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-EDNKP3SP.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +0 -2
- package/dist/cli/chunks/audit-CVZQMF55.js +0 -3
- package/dist/cli/chunks/base-P3Z4IKCT.js +0 -2
- package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +0 -2
- package/dist/cli/chunks/chunk-3EZ5DR2R.js +0 -21
- package/dist/cli/chunks/chunk-5WOSWNDN.js +0 -2
- package/dist/cli/chunks/chunk-7CD7PBHY.js +0 -3
- package/dist/cli/chunks/chunk-7X7JYWT4.js +0 -27
- package/dist/cli/chunks/chunk-CZO4BJG5.js +0 -2
- package/dist/cli/chunks/chunk-J27F4NSB.js +0 -2
- package/dist/cli/chunks/chunk-J5UNP6W3.js +0 -2
- package/dist/cli/chunks/chunk-MI5Q55DG.js +0 -65
- package/dist/cli/chunks/chunk-TY5WC3FT.js +0 -12
- package/dist/cli/chunks/chunk-UDHVCKGA.js +0 -5
- package/dist/cli/chunks/chunk-XQSIRBKT.js +0 -180
- package/dist/cli/chunks/chunk-YXP6BKGS.js +0 -730
- package/dist/cli/chunks/chunk-ZBABIZ2D.js +0 -2
- package/dist/cli/chunks/chunk-ZCWERUYB.js +0 -12
- package/dist/cli/chunks/claude-flow-setup-5LVJOFKP.js +0 -2
- package/dist/cli/chunks/client-HUVFA5PF.js +0 -2
- package/dist/cli/chunks/core-handlers-UEXO3VAA.js +0 -2
- package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +0 -2
- package/dist/cli/chunks/domain-transfer-JZA5TMW3.js +0 -2
- package/dist/cli/chunks/dream-HE3OX42F.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +0 -2
- package/dist/cli/chunks/hnsw-index-T2PGO77J.js +0 -2
- package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +0 -2
- package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +0 -2
- package/dist/cli/chunks/init-wizard-XBU674YH.js +0 -2
- package/dist/cli/chunks/kernel-DV5MTNZD.js +0 -2
- package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +0 -2
- package/dist/cli/chunks/llm-router-service-PSMASERT.js +0 -2
- package/dist/cli/chunks/load-test-MRUO2VPF.js +0 -2
- package/dist/cli/chunks/mcp-JGSFCEMH.js +0 -2
- package/dist/cli/chunks/memory-backend-2MPGI6JW.js +0 -2
- package/dist/cli/chunks/memory-handlers-XT4HMITB.js +0 -2
- package/dist/cli/chunks/multi-model-executor-26Q5BSVG.js +0 -14
- package/dist/cli/chunks/orchestrator-D5IFV65I.js +0 -393
- package/dist/cli/chunks/pattern-null-store-TGWUL237.js +0 -2
- package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +0 -2
- package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +0 -2
- package/dist/cli/chunks/router-OZH3QSAU.js +0 -2
- package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +0 -2
- package/dist/cli/chunks/safe-db-3OYEPVEH.js +0 -2
- package/dist/cli/chunks/schedule-AG4C2EIQ.js +0 -2
- package/dist/cli/chunks/scheduler-SQS2CZFZ.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-NFL6QSZ6.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +0 -2
- package/dist/cli/chunks/sync-MBTW5XBF.js +0 -2
- package/dist/cli/chunks/task-handlers-NH4GJHCJ.js +0 -9
- package/dist/cli/chunks/test-MPHGT4T6.js +0 -33
- package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-J6ZMAK37.js +0 -2
- package/dist/cli/chunks/unified-memory-DDWMC435.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +0 -2
- package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +0 -2
- package/dist/cli/chunks/vibium-HOGMFJ2Z.js +0 -2
- package/dist/cli/chunks/visual-security-25SMBIYT.js +0 -2
- package/dist/cli/chunks/witness-chain-PJOQPFUX.js +0 -2
- package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +0 -2
- package/dist/cli/chunks/wrappers-UR7BLXKV.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{a as x}from"./chunk-TW3SR4TS.js";import{e as f}from"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-YO4ESCB4.js";x();import{createRequire as w}from"module";var S=f.create("agent-booster-wasm"),t={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},l={ExactReplace:0,FuzzyReplace:1,InsertAfter:2,InsertBefore:3,Append:4},v={0:"JavaScript",1:"TypeScript",2:"Python",3:"Rust",4:"Go",5:"Java",6:"C",7:"Cpp"},a=null,u=null,p=null;async function g(){if(a)return!0;if(p)return!1;try{if(a=w(import.meta.url)("./agent_booster_wasm.js"),!a)throw new Error("WASM module loaded but is null");return u=new a.AgentBoosterWasm,!0}catch(e){return p=e,console.warn("[AgentBoosterWASM] Failed to load WASM module:",e),!1}}function A(e){return{".js":t.JavaScript,".mjs":t.JavaScript,".cjs":t.JavaScript,".jsx":t.JavaScript,".ts":t.TypeScript,".tsx":t.TypeScript,".mts":t.TypeScript,".cts":t.TypeScript,".py":t.Python,".rs":t.Rust,".go":t.Go,".java":t.Java,".c":t.C,".h":t.C,".cpp":t.Cpp,".cc":t.Cpp,".cxx":t.Cpp,".hpp":t.Cpp}[e.toLowerCase()]??t.JavaScript}var M=[{name:"var-to-const",detect:(e,r)=>e.includes("var ")&&r.includes("const "),apply:(e,r)=>e.replace(/\bvar\s+/g,"const ")},{name:"var-to-let",detect:(e,r)=>e.includes("var ")&&r.includes("let "),apply:(e,r)=>e.replace(/\bvar\s+/g,"let ")},{name:"add-types-function",detect:(e,r)=>e.includes("function")&&!e.includes(":")&&r.includes(":"),apply:(e,r)=>r},{name:"async-wrapper",detect:(e,r)=>!e.includes("async")&&r.includes("async")&&r.includes("await"),apply:(e,r)=>r},{name:"try-catch-wrapper",detect:(e,r)=>!e.includes("try {")&&r.includes("try {"),apply:(e,r)=>r},{name:"null-check",detect:(e,r)=>!e.includes("if (!")&&!e.includes("if (!")&&(r.includes("if (!")||r.includes("?.")),apply:(e,r)=>r},{name:"test-assertion",detect:(e,r)=>e.includes("test(")&&!e.includes("expect(")&&r.includes("expect("),apply:(e,r)=>r}];function y(e,r){for(let n of M)if(n.detect(e,r))try{return{success:!0,code:n.apply(e,r),pattern:n.name}}catch(s){S.debug("Pattern transform failed, trying next",{pattern:n.name,error:s instanceof Error?s.message:String(s)});continue}return{success:!1,code:r}}async function b(e,r,n,s={}){let o=performance.now(),{confidenceThreshold:T=.5,allowFallback:d=!0}=s;if(!e.trim())return{success:!0,mergedCode:r,confidence:1,strategy:l.Append,syntaxValid:!0,source:"fallback",latencyMs:performance.now()-o};if(await g()&&u&&a)try{let c=a.WasmLanguage[v[n]],i=u.apply_edit(e,r,c);return{success:!0,mergedCode:i.merged_code,confidence:i.confidence,strategy:i.strategy,syntaxValid:i.syntax_valid,source:"wasm",latencyMs:performance.now()-o}}catch(c){let i=c;if(d){let m=y(e,r);if(m.success)return{success:!0,mergedCode:m.code,confidence:.7,strategy:l.FuzzyReplace,syntaxValid:!0,source:"pattern",latencyMs:performance.now()-o}}return{success:!1,mergedCode:r,confidence:0,strategy:l.Append,syntaxValid:!1,source:"fallback",latencyMs:performance.now()-o,error:i.message}}if(d){let c=y(e,r);return{success:c.success,mergedCode:c.code,confidence:c.success?.7:0,strategy:l.FuzzyReplace,syntaxValid:!0,source:"pattern",latencyMs:performance.now()-o}}return{success:!1,mergedCode:r,confidence:0,strategy:l.Append,syntaxValid:!1,source:"fallback",latencyMs:performance.now()-o,error:p?.message??"WASM not available"}}async function W(e,r={}){return Promise.all(e.map(({original:n,edit:s,language:o})=>b(n,s,o,r)))}async function C(){return g()}async function L(){return await g()&&a?a.AgentBoosterWasm.version():"unavailable"}async function R(){if(await g(),u&&a)try{u.apply_edit("function x() {}","function x() {}",a.WasmLanguage.JavaScript)}catch(e){console.debug("[AgentBoosterWASM] Warmup error:",e instanceof Error?e.message:e)}}var _={transform:b,batchTransform:W,isWasmAvailable:C,getVersion:L,warmup:R,Language:t,MergeStrategy:l,languageFromExtension:A};export{t as Language,l as MergeStrategy,W as batchTransform,_ as default,L as getVersion,C as isWasmAvailable,A as languageFromExtension,b as transform,R as warmup};
|
|
@@ -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.14.
|
|
2
|
-
import{b 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.14.7");process.exit(0)}
|
|
2
|
+
import{b as p}from"./chunk-7QYOTUOX.js";import{a as g}from"./chunk-7EZ2Z2CK.js";import"./chunk-OIDWDGLG.js";import"./chunk-YO4ESCB4.js";import s from"chalk";var l=class{name="agent";description="Manage QE agents";cleanupAndExit;ensureInitialized;constructor(n,t){this.cleanupAndExit=n,this.ensureInitialized=t}register(n,t){let a=n.command("agent").description(this.description);a.command("list").description("List all agents").option("-d, --domain <domain>","Filter by domain").option("-s, --status <status>","Filter by status").action(async e=>{await this.executeList(e,t)}),a.command("spawn <domain>").description("Spawn an agent in a domain").option("-t, --type <type>","Agent type","worker").option("-c, --capabilities <caps>","Comma-separated capabilities","general").option("--no-progress","Disable progress indicator").action(async(e,o)=>{await this.executeSpawn(e,o,t)})}async executeList(n,t){if(await this.ensureInitialized())try{let a=n.domain?t.queen.getAgentsByDomain(n.domain):t.queen.listAllAgents();if(n.status&&(a=a.filter(e=>e.status===n.status)),console.log(s.blue(`
|
|
3
3
|
Agents (${a.length})
|
|
4
4
|
`)),a.length===0)console.log(s.gray(" No agents found"));else{let e=new Map;for(let i of a)e.has(i.domain)||e.set(i.domain,[]),e.get(i.domain).push(i);let o=Array.from(e.entries());for(let[i,m]of o){console.log(s.cyan(` ${i}:`));for(let r of m)console.log(` ${r.id}`),console.log(` Type: ${r.type}`),console.log(` Status: ${g(r.status)}`),r.startedAt&&console.log(s.gray(` Started: ${r.startedAt.toISOString()}`));console.log("")}}}catch(a){console.error(s.red(`
|
|
5
5
|
Failed to list agents:`),a),await this.cleanupAndExit(1)}}async executeSpawn(n,t,a){if(await this.ensureInitialized())try{let e=t.capabilities.split(",");console.log(s.blue(`
|
|
@@ -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.14.
|
|
2
|
-
import"./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.14.7");process.exit(0)}
|
|
2
|
+
import"./chunk-YO4ESCB4.js";import{existsSync as i,mkdirSync as d,unlinkSync as s,readdirSync as p,statSync as f}from"fs";import{join as o,basename as l}from"path";var v={branchDir:".agentic-qe/branches",defaultStrategy:"child-wins",orphanMaxAgeMs:36e5},g=class{config;parentAdapter;activeBranches=new Map;witnessChain=null;constructor(t,e){this.parentAdapter=t,this.config={...v,...e}}setWitnessChain(t){this.witnessChain=t}createBranch(t){if(this.activeBranches.has(t))throw new Error(`Branch already exists for agent ${t}`);i(this.config.branchDir)||d(this.config.branchDir,{recursive:!0});let e=o(this.config.branchDir,`${t}.rvf`),r=this.parentAdapter.path(),n=this.parentAdapter.derive(e),a={agentId:t,childPath:e,parentPath:r,childAdapter:n,createdAt:Date.now(),ingestLog:[]};return this.activeBranches.set(t,a),a}recordIngest(t,e){let r=this.activeBranches.get(t);if(r)for(let n of e)r.ingestLog.push({id:n.id,vector:n.vector})}async mergeBranch(t,e){let r=e??this.config.defaultStrategy,n=performance.now(),a=0;if(r==="child-wins"&&t.ingestLog.length>0)try{a=this.parentAdapter.ingest(t.ingestLog).accepted}catch(c){console.warn(`[AgentMemoryBranch] Merge replay failed for ${t.agentId}:`,c)}return this.witnessChain?.append("BRANCH_MERGE",{agentId:t.agentId,strategy:r,vectorsMerged:a,branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId),{vectorsMerged:a,strategy:r,durationMs:performance.now()-n}}discardBranch(t){this.witnessChain?.append("BRANCH_DISCARD",{agentId:t.agentId,action:"discard",branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId)}getBranch(t){return this.activeBranches.get(t)}getActiveBranches(){return Array.from(this.activeBranches.values())}listBranchFiles(){return i(this.config.branchDir)?p(this.config.branchDir).filter(e=>e.endsWith(".rvf")).map(e=>{let r=o(this.config.branchDir,e),n=f(r);return{agentId:l(e,".rvf"),path:r,sizeBytes:n.size,modifiedAt:n.mtime}}):[]}cleanupOrphans(t){let e=t??this.config.orphanMaxAgeMs,r=Date.now(),n=0;for(let a of this.listBranchFiles())if(r-a.modifiedAt.getTime()>e&&!this.activeBranches.has(a.agentId))try{s(a.path);let h=`${a.path}.idmap.json`;i(h)&&s(h),n++}catch{}return n}cleanupBranchFile(t){try{t.childAdapter.close()}catch{}try{i(t.childPath)&&s(t.childPath);let e=`${t.childPath}.idmap.json`;i(e)&&s(e)}catch{}}};export{g as AgentMemoryBranch};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f}from"./chunk-UA7TDVL7.js";import"./chunk-3QJU4Q4R.js";import"./chunk-ONR2NXXD.js";import"./chunk-EJ6MMYLK.js";import"./chunk-Z4Q5PCRZ.js";import"./chunk-HZY42OVU.js";import"./chunk-HYOPJHHW.js";import"./chunk-YMW57PEL.js";import"./chunk-P2UPYSDJ.js";import"./chunk-B2YGVSOP.js";import"./chunk-MT7UNBZ7.js";import"./chunk-Q6NTEICT.js";import"./chunk-XBYQ2BS4.js";import"./chunk-BLG7SH4A.js";import"./chunk-AJUBT4NP.js";import"./chunk-36VKMAMN.js";import"./chunk-4INST4ZL.js";import"./chunk-7MIOK72I.js";import"./chunk-3M7J4U74.js";import"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import"./chunk-IAENZ2DR.js";import"./chunk-QVH5Y7AP.js";import"./chunk-Y6AKKQIQ.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import"./chunk-FW4DJ4FJ.js";import"./chunk-ND4QTZOL.js";import"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import"./chunk-YO4ESCB4.js";export{b as AQELearningEngine,a as DEFAULT_ENGINE_CONFIG,c as DEFAULT_META_LEARNING_CONFIG,d as MetaLearningEngine,e as createAQELearningEngine,f as createDefaultLearningEngine};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.
|
|
2
|
-
import"./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.14.7");process.exit(0)}
|
|
2
|
+
import"./chunk-YO4ESCB4.js";import*as K from"fs";import*as M from"path";function G(t){let r=t>>>0;return function(){r|=0,r=r+1831565813|0;let n=Math.imul(r^r>>>15,1|r);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function w(t,r){return Math.floor(t()*r)}var z=[["===","!=="],["!==","==="],["<=","<"],[">=",">"],["&&","||"],["||","&&"],["<","<="],[">",">="],["+","-"],["*","+"]];function H(t){let r=new Array(t.length).fill(!1),n=0,e="code";for(;n<t.length;){let s=t[n],i=t[n+1];e==="code"?(s==="'"?e="single":s==='"'?e="double":s==="`"?e="template":s==="/"&&i==="/"?e="line-comment":s==="/"&&i==="*"&&(e="block-comment"),e!=="code"&&(r[n]=!0)):(r[n]=!0,e==="single"&&s==="'"&&t[n-1]!=="\\"||e==="double"&&s==='"'&&t[n-1]!=="\\"||e==="template"&&s==="`"&&t[n-1]!=="\\"||e==="line-comment"&&s===`
|
|
3
3
|
`?e="code":e==="block-comment"&&s==="*"&&i==="/"&&(r[n+1]=!0,n++,e="code")),n++}return r}function E(t,r){let n=1;for(let e=0;e<r;e++)t[e]===`
|
|
4
4
|
`&&n++;return n}function A(t,r){let n=H(t),e=new Array(t.length).fill(!1),s=[];for(let[i,c]of z){let a=t.indexOf(i);for(;a!==-1;){let u=a+i.length,y=e.slice(a,u).some(Boolean),h=n.slice(a,u).some(Boolean),v=i===">"&&t[a-1]==="=",S=(i==="<"||i===">")&&(t[u]==="="||t[a-1]==="<"||t[a-1]===">");if(!y&&!h&&!v&&!S){for(let d=a;d<u;d++)e[d]=!0;s.push({id:`${r}:${E(t,a)}:${a}:${i}->${c}`,index:a,from:i,to:c,line:E(t,a)})}a=t.indexOf(i,a+1)}}return s.sort((i,c)=>i.index-c.index)}function W(t,r){return t.slice(0,r.index)+r.to+t.slice(r.index+r.from.length)}import*as m from"fs";import*as f from"path";import*as L from"os";import{spawnSync as J}from"child_process";function I(t){let r=f.resolve(t),n=f.join(r,"src"),e=f.join(r,"tests");if(!m.existsSync(n)||!m.existsSync(e))throw new Error(`not an arena fixture (expected src/ and tests/): ${r}`);let s=m.readdirSync(n).filter(c=>c.endsWith(".mjs")).sort().map(c=>f.join("src",c)),i={};for(let c of m.readdirSync(e).filter(a=>a.endsWith(".test.mjs")).sort())i[c.replace(".test.mjs","")]=f.join("tests",c);if(s.length===0||Object.keys(i).length===0)throw new Error(`fixture has no src/*.mjs or tests/*.test.mjs: ${r}`);return{root:r,sourceFiles:s,testGroups:i}}function T(t,r){let n=m.mkdtempSync(f.join(r,"arena-ws-"));m.mkdirSync(f.join(n,"src"),{recursive:!0}),m.mkdirSync(f.join(n,"tests"),{recursive:!0});for(let e of t.layout.sourceFiles){let s=t.mutatedFile&&t.mutatedFile.relPath===e?t.mutatedFile.content:m.readFileSync(f.join(t.layout.root,e),"utf8");m.writeFileSync(f.join(n,e),s)}for(let e of t.groups){let s=t.layout.testGroups[e];m.copyFileSync(f.join(t.layout.root,s),f.join(n,s))}return n}function $(t,r={}){let n=["--test"];r.coverage&&n.push("--experimental-test-coverage");let e=m.readdirSync(f.join(t,"tests")).filter(u=>u.endsWith(".test.mjs")).sort().map(u=>f.join("tests",u));n.push(...e);let s=process.hrtime.bigint(),i=J(process.execPath,n,{cwd:t,timeout:r.timeoutMs??12e4,encoding:"utf8"}),c=Number(process.hrtime.bigint()-s)/1e6,a=null;if(r.coverage){let u=/all files\s*\|\s*([\d.]+)/.exec(i.stdout??"");a=u?Number(u[1]):null}return{ok:i.status===0,durationMs:Math.round(c),coveragePct:a}}function N(){return m.mkdtempSync(f.join(L.tmpdir(),"qe-arena-"))}function B(t){m.rmSync(t,{recursive:!0,force:!0})}var k={kill:.6,coverage:.3,runtimePenalty:.1};function Q(t,r,n){let e=[...t].sort(),s=new Set([e.join("+")]),i=[{id:"s1",name:`all(${e.join("+")})`,groups:e}],c=0;for(;i.length<r&&c++<200;){let a=e.filter(()=>n()<.5);if(a.length===0)continue;let u=a.join("+");s.has(u)||(s.add(u),i.push({id:`s${i.length+1}`,name:u,groups:a}))}return i}function C(t,r,n){let e=r===null?0:r/100,s=k.kill*t+k.coverage*e-k.runtimePenalty*n;return Math.round(s*1e4)/1e4}function D(t,r,n,e){let s=T({layout:t,groups:r.groups},e),i=$(s,{coverage:!0});if(!i.ok)return{baselinePassed:!1,killed:0,total:0,coveragePct:i.coveragePct,runtimeMs:i.durationMs};let c=0,a=0;for(let u of n)for(let y of u.mutants){a++;let h=T({layout:t,groups:r.groups,mutatedFile:{relPath:u.relPath,content:W(u.source,y)}},e);$(h).ok||c++}return{baselinePassed:!0,killed:c,total:a,coveragePct:i.coveragePct,runtimeMs:i.durationMs}}function rt(t){let r=t.seed??42,n=t.log??(()=>{}),e=G(r),s=I(t.target),i=N();try{let c=t.maxMutants??24,a=s.sourceFiles.map(l=>{let o=K.readFileSync(M.join(s.root,l),"utf8");return{relPath:l,source:o,mutants:A(o,l)}}),u=a.flatMap(l=>l.mutants.map(o=>({file:l.relPath,m:o})));if(u.length>c){let l=new Set;for(;l.size<c;)l.add(u[w(e,u.length)].m.id);for(let o of a)o.mutants=o.mutants.filter(p=>l.has(p.id));u=a.flatMap(o=>o.mutants.map(p=>({file:o.relPath,m:p})))}n(`mutants: ${u.length} (of ${a.reduce((l,o)=>l+A(o.source,o.relPath).length,0)} enumerated)`);let y=Q(Object.keys(s.testGroups),t.strategies??4,e),h={},v=y.map(l=>{n(`evaluating ${l.id} [${l.name}] ...`);let o=D(s,l,a,i);return h[l.id]=o.runtimeMs,{s:l,e:o}}),S=Object.keys(s.testGroups).length,d=v.map(({s:l,e:o})=>{let p=o.total>0?Math.round(o.killed/o.total*1e4)/1e4:0,g=Math.round(l.groups.length/S*1e4)/1e4;return{...l,baselinePassed:o.baselinePassed,mutantsKilled:o.killed,mutantsTotal:o.total,killRate:p,coveragePct:o.coveragePct,suiteCostRatio:g,fitness:o.baselinePassed?C(p,o.coveragePct,g):0}}),P=[...d].sort((l,o)=>o.fitness-l.fitness||l.id.localeCompare(o.id)).map(l=>l.id),U=d.map(l=>d.map(o=>l.fitness>o.fitness?1:l.fitness<o.fitness?-1:0)),j=[];if(t.evolveSteps&&t.evolveSteps>0){let l=Object.keys(s.testGroups).sort(),o=d.find(g=>g.id===P[0]).groups,p=d.find(g=>g.id===P[0]).fitness;for(let g=1;g<=t.evolveSteps;g++){let R=l[w(e,l.length)],b=o.includes(R)?o.filter(q=>q!==R):[...o,R].sort();if(b.length===0){j.push({step:g,groups:b,fitness:0,accepted:!1});continue}let x=D(s,{id:`evo${g}`,name:b.join("+"),groups:b},a,i),_=x.total>0?x.killed/x.total:0,F=x.baselinePassed?C(_,x.coveragePct,b.length/l.length):0,O=F>p;j.push({step:g,groups:b,fitness:F,accepted:O}),O&&(o=b,p=F)}}return{contract:"arena-result@1",seed:r,target:M.relative(process.cwd(),s.root)||".",weights:{...k},mutantsTotal:u.length,strategies:d,ranking:P,competitiveArray:U,evolution:j,informational:{runtimesMs:h}}}finally{B(i)}}export{Q as buildStrategies,rt as runArena};
|
|
@@ -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.14.
|
|
2
|
-
import{a as c,
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{a as c,e as f}from"./chunk-ZUOVNFXK.js";import"./chunk-YO4ESCB4.js";f();import{Command as $}from"commander";import r from"chalk";function x(v,g,p){let m=new $("arena").description("Competitive test-strategy tournaments (ADR-104)").addHelpText("after",`
|
|
3
3
|
Examples:
|
|
4
4
|
# Run a 4-strategy tournament against the demo fixture (reproducible under --seed)
|
|
5
5
|
aqe arena run --strategies 4 --target fixtures/arena-demo --seed 42
|
|
@@ -9,10 +9,10 @@ Examples:
|
|
|
9
9
|
|
|
10
10
|
# List persisted runs
|
|
11
11
|
aqe arena list
|
|
12
|
-
`);return m.command("run").description("Run a seeded strategy tournament against an arena fixture").requiredOption("--target <dir>","Arena fixture directory (src/*.mjs + tests/*.test.mjs)").option("--strategies <n>","Number of strategies","4").option("--seed <n>","RNG seed (same seed = same tournament)","42").option("--max-mutants <n>","Mutant sample cap","24").option("--evolve <steps>","Hill-climb steps from the winner","0").option("--json","Output the full arena-result@1 envelope as JSON").action(async a=>{try{let{runArena:i}=await import("./arena-
|
|
12
|
+
`);return m.command("run").description("Run a seeded strategy tournament against an arena fixture").requiredOption("--target <dir>","Arena fixture directory (src/*.mjs + tests/*.test.mjs)").option("--strategies <n>","Number of strategies","4").option("--seed <n>","RNG seed (same seed = same tournament)","42").option("--max-mutants <n>","Mutant sample cap","24").option("--evolve <steps>","Hill-climb steps from the winner","0").option("--json","Output the full arena-result@1 envelope as JSON").action(async a=>{try{let{runArena:i}=await import("./arena-CUVH3V7H.js"),t=i({target:a.target,strategies:parseInt(a.strategies,10),seed:parseInt(a.seed,10),maxMutants:parseInt(a.maxMutants,10),evolveSteps:parseInt(a.evolve,10),log:a.json?()=>{}:e=>console.error(r.dim(` ${e}`))});try{let{getUnifiedMemory:e}=await import("./unified-memory-OVFEPRPS.js"),s=e();s.isInitialized()||await s.initialize(),s.getDatabase().prepare("INSERT OR REPLACE INTO kv_store (namespace, key, value) VALUES ('arena', ?, ?)").run(`run:${t.seed}:${t.target}`,JSON.stringify(t))}catch(e){console.error(r.dim(` note: run not persisted (${c(e)})`))}if(a.json){console.log(JSON.stringify(t,null,2));return}let d=new Map(t.strategies.map(e=>[e.id,e]));console.log(r.blue(`
|
|
13
13
|
Arena: ${t.target} \xB7 seed ${t.seed} \xB7 ${t.mutantsTotal} mutants
|
|
14
14
|
`)),console.log(" rank id kill-rate coverage cost fitness groups"),t.ranking.forEach((e,s)=>{let n=d.get(e),u=n.coveragePct===null?" n/a":`${n.coveragePct.toFixed(2)}%`.padStart(7);console.log(` ${String(s+1).padEnd(5)}${n.id.padEnd(5)}${(n.killRate*100).toFixed(1).padStart(6)}% ${u} ${n.suiteCostRatio.toFixed(2).padEnd(6)}${n.fitness.toFixed(4).padEnd(9)}${n.name}`+(n.baselinePassed?"":r.red(" [baseline FAILED]")))}),console.log(`
|
|
15
15
|
competitive array (row beats column = 1):`);let o=t.strategies.map(e=>e.id);if(console.log(` ${o.map(e=>e.padEnd(4)).join("")}`),t.competitiveArray.forEach((e,s)=>{console.log(` ${o[s].padEnd(4)}${e.map(n=>String(n).padStart(2).padEnd(4)).join("")}`)}),t.evolution.length>0){console.log(`
|
|
16
16
|
evolution:`);for(let e of t.evolution)console.log(` step ${e.step}: [${e.groups.join("+")}] fitness ${e.fitness.toFixed(4)} ${e.accepted?r.green("accepted"):"rejected"}`)}let l=d.get(t.ranking[0]);console.log(r.green(`
|
|
17
17
|
winner: ${l.id} [${l.name}] \u2014 kill ${(l.killRate*100).toFixed(1)}%, fitness ${l.fitness.toFixed(4)}
|
|
18
|
-
`))}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m.command("list").description("List persisted arena runs").option("--json","Output as JSON").action(async a=>{if(await p())try{let{getUnifiedMemory:i}=await import("./unified-memory-
|
|
18
|
+
`))}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m.command("list").description("List persisted arena runs").option("--json","Output as JSON").action(async a=>{if(await p())try{let{getUnifiedMemory:i}=await import("./unified-memory-OVFEPRPS.js"),t=i();t.isInitialized()||await t.initialize();let d=t.getDatabase().prepare("SELECT key, value FROM kv_store WHERE namespace = 'arena' ORDER BY key").all();if(a.json){console.log(JSON.stringify(d.map(o=>({key:o.key,result:JSON.parse(o.value)})),null,2));return}if(d.length===0){console.log(r.yellow(" no persisted arena runs"));return}for(let o of d){let l=JSON.parse(o.value),e=l.strategies.find(s=>s.id===l.ranking[0]);console.log(` ${r.green(o.key)} \u2014 winner ${e?.id} [${e?.name}] fitness ${e?.fitness}`)}}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m}export{x as createArenaCommand};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{d as g,e as y,f as k,g as w}from"./chunk-GVVFTFMB.js";import{s as x}from"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import{b as l}from"./chunk-IAENZ2DR.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import"./chunk-ND4QTZOL.js";import{p as F,q as j}from"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import{f as v}from"./chunk-YO4ESCB4.js";import{Command as E}from"commander";import s from"chalk";x();import{existsSync as f}from"node:fs";import p from"node:path";function b(e,a,n){let t=[];t.push(s.bold("Witness Chain Audit Verification")),t.push("");let r=a?s.green("ENABLED"):s.yellow("DISABLED");t.push(` Feature Flag: ${r}`),t.push(` Chain Length: ${e.length} receipts`);let o=n?.status==="forked"?s.yellow("FORKED (no tampering detected)"):e.valid?s.green(n?.status==="valid-with-forks"?"VALID (forks re-anchored)":"VALID"):s.red(n?.status==="tampered"?"BROKEN (tampering detected)":"BROKEN");t.push(` Integrity: ${o}`),e.length>0&&t.push(` Last Hash: ${e.lastHash.slice(0,16)}...`);let i=n?.forks?.length??0;if(i>0){let d=n?.acknowledgedForks?.length??0;t.push(` Forks: ${i} accidental (pre-3.14.5 concurrent writes, #753), ${d} re-anchored`)}if(n?.status==="forked")t.push(""),t.push(s.yellow(` ${e.message}`));else if(!e.valid&&e.brokenAt>=0){t.push("");let d=n?.status==="tampered"&&n.tamperedAt!==void 0?n.tamperedAt:e.brokenAt;t.push(s.red(` Break detected at index ${d}${n?.tamperReason?` (${n.tamperReason})`:""}`)),t.push(s.red(` ${e.message}`))}else e.valid&&i>0&&(t.push(""),t.push(s.green(` ${e.message}`)));return t.push(""),t.join(`
|
|
3
|
+
`)}function O(){try{let e=l(),a=p.join(e,".agentic-qe","memory.db");if(!f(a))return null;let n=(j(),v(F)),t=new n(a),r=g(t),o=k(r);return t.close(),o}catch{return null}}async function P(e){let a=w(),t=(O()??y()).verifyChain(),r={featureEnabled:a,chainLength:t.length,integrity:t.valid,brokenAt:t.brokenAt,lastHash:t.lastHash,message:t.message};return e.format==="json"?console.log(JSON.stringify(r,null,2)):console.log(b(t,a)),r}async function L(e){let{WitnessChain:a,hashWith:n,serializeEntry:t}=await import("./witness-chain-MH6GA5L6.js"),{dbPath:r,keyDir:o}=R(),i;if(!f(r))i={featureEnabled:!0,chainLength:0,integrity:!0,brokenAt:-1,lastHash:"",message:`No database found at ${r} \u2014 nothing to verify`};else{let{default:d}=await import("./better-sqlite3-DB3LOJQU.js"),u=new d(r,{readonly:!0});try{let m=new a(u,await A(o)??void 0);await m.initialize();let c=m.verify({includeArchive:!0,checkSignatures:!1}),{tableExists:C}=await import("./witness-chain-verifier-TTJYXTBE.js"),h=C(u,"witness_chain")?u.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get():void 0,$=h?n(h.hash_algo||"sha256",t(h)):"";i={featureEnabled:!0,chainLength:c.entriesChecked,integrity:c.valid,brokenAt:c.brokenAt??-1,lastHash:$,message:V(c),status:c.status,tampered:c.tampered,...c.tamperedAt!==void 0?{tamperedAt:c.tamperedAt}:{},...c.tamperReason?{tamperReason:c.tamperReason}:{},forks:c.forks,acknowledgedForks:c.acknowledgedForks}}finally{u.close()}}return e.format==="json"?console.log(JSON.stringify(i,null,2)):console.log(b({valid:i.integrity,length:i.chainLength,brokenAt:i.brokenAt,lastHash:i.lastHash,message:i.message},i.featureEnabled,i)),i}function R(){let e=l();return{dbPath:p.join(e,".agentic-qe","memory.db"),keyDir:p.join(e,".agentic-qe","witness-keys")}}async function A(e){if(!f(e))return null;let{WitnessKeyManager:a}=await import("./witness-key-manager-EM6YXYOY.js");return new a({keyDir:e,autoGenerate:!1})}function V(e){let a=e.entriesChecked,n=e.forks.length,t=n-e.acknowledgedForks.length;switch(e.status){case"valid":return`Audit chain verified: ${a} entries checked, ${e.signatureFailures??0} signature failures`;case"valid-with-forks":return`Audit chain verified: ${a} entries checked; ${n} accidental fork(s) from pre-3.14.5 concurrent writes are re-anchored by CHAIN_REANCHOR, no tampering detected`;case"forked":return`${t} accidental fork(s) (pre-3.14.5 concurrent writes, #753), no tampering detected \u2014 ${a} entries checked, first fork at id=${e.brokenAt}. Run \`aqe audit repair --chain audit\` to back up the store and re-anchor.`;default:return`Audit chain BROKEN: tampering detected at id=${e.tamperedAt} (${e.tamperReason}); ${a} entries checked`+(n>0?`, ${n} accidental fork(s) found before it`:"")}}function W(e){return e.action==="refused"?!0:e.action==="reanchored"&&!(e.after?.status==="valid"||e.after?.status==="valid-with-forks")}async function D(e){let{repairWitnessChainForks:a}=await import("./witness-chain-repair-MJZGZRWT.js"),{dbPath:n,keyDir:t}=R(),r=e.dryRun===!0,o;if(f(n)){let{openDatabase:i}=await import("./safe-db-FWWGAPVE.js"),d=i(n,{readonly:r,fileMustExist:!0});try{let u=r?await A(t):(await import("./witness-key-manager-EM6YXYOY.js")).getDefaultWitnessKeyManager();o=await a(d,{dbPath:n,dryRun:r,keyManager:u})}finally{d.close()}}else{let i={status:"valid",entriesChecked:0,forks:0,unacknowledgedForks:0};o={action:"none",dryRun:r,message:`No database found at ${n} \u2014 nothing to repair`,before:i,rowsBefore:{live:0,archive:0},rowsAfter:{live:0,archive:0},forksAcknowledged:[]}}return e.format==="json"?console.log(JSON.stringify(o,null,2)):console.log(S(o)),o}function S(e){let a=e.action==="refused"?s.red:e.action==="reanchored"?s.green:s.yellow,n=[s.bold("Witness Chain Audit Repair"),"",` Action: ${a(e.action.toUpperCase())}${e.dryRun?" (dry run)":""}`,` Before: ${e.before.status}, ${e.before.forks} fork(s), ${e.before.unacknowledgedForks} unacknowledged`,` Rows: live ${e.rowsBefore.live} -> ${e.rowsAfter.live}, archive ${e.rowsBefore.archive} -> ${e.rowsAfter.archive}`];return e.after&&n.push(` After: ${e.after.status}`),e.backupPath&&n.push(` Backup: ${e.backupPath}`),n.push("",` ${a(e.message)}`,""),n.join(`
|
|
4
|
+
`)}function q(e,a,n){let t=new E("audit").description("Witness chain audit trail management");return t.command("verify").description("Verify witness chain integrity").option("-F, --format <format>","Output format (json|text)","text").option("-C, --chain <chain>","Which chain to verify: governance (29 decision receipts) or audit (full QE audit trail)","governance").action(async r=>{try{let o=r.format,i=r.chain==="audit"?await L({format:o}):await P({format:o});await a(i.integrity?0:1)}catch(o){console.error("Failed to verify witness chain:",o),await a(1)}}),t.command("repair").description("Re-anchor accidental pre-3.14.5 forks in the audit chain (#753); backs up first, refuses on tampering").option("-C, --chain <chain>",'Chain to repair (only "audit" is supported)',"audit").option("--dry-run","Report what would be done without writing anything",!1).option("-F, --format <format>","Output format (json|text)","text").action(async r=>{try{if(r.chain!=="audit"){console.error(`aqe audit repair supports only --chain audit (got "${r.chain}")`),await a(1);return}let o=await D({format:r.format,dryRun:r.dryRun===!0});await a(W(o)?1:0)}catch(o){console.error("Failed to repair witness chain:",o),await a(1)}}),t}export{q as createAuditCommand,b as formatVerificationText,D as handleAuditChainRepair,L as handleAuditChainVerify,P as handleAuditVerify};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-LU2EDWQK.js";import"./chunk-RKUAWQOF.js";import"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import"./chunk-IAENZ2DR.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import"./chunk-FW4DJ4FJ.js";import"./chunk-OXHF3L2T.js";import"./chunk-ND4QTZOL.js";import"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import"./chunk-YO4ESCB4.js";export{l as MCPToolBase,k as defaultToolLogger,j as getKernel,i as getLLMRouter,e as getMemoryBackend,g as getSharedLLMRouter,c as getSharedMemoryBackend,a as isMemoryOnlyMode,b as registerRvfResetFn,h as resetSharedLLMRouter,d as resetSharedMemoryBackend,f as setSharedLLMRouter};
|
|
@@ -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.14.
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q 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.14.7");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p}from"./chunk-JZT7BU44.js";import"./chunk-YO4ESCB4.js";p();export{i as DotProductAttention,h as FlashAttention,k as HyperbolicAttention,l as LinearAttention,m as MoEAttention,j as MultiHeadAttention,b as RuvectorLayer,n as SonaEngine,c as TensorCompress,a as default,d as differentiableSearch,f as getCompressionLevel,e as hierarchicalForward,g as init,o as pipeline};
|
|
@@ -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.14.
|
|
2
|
-
import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}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.14.7");process.exit(0)}
|
|
2
|
+
import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-IWFFO6VT.js";import{c as Ee}from"./chunk-B2YGVSOP.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-XBYQ2BS4.js";import{b as ve}from"./chunk-36VKMAMN.js";import{a as Se,d as ae,e as _e}from"./chunk-4INST4ZL.js";import"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import{b as k,d as oe}from"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import"./chunk-IAENZ2DR.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import{a as F,b as nn}from"./chunk-ND4QTZOL.js";import"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import"./chunk-YO4ESCB4.js";import $ from"path";import o from"chalk";nn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.prepare(`
|
|
3
3
|
INSERT INTO witness_chain
|
|
4
4
|
(prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
|
|
5
5
|
VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
|
|
@@ -79,7 +79,7 @@ Examples:
|
|
|
79
79
|
aqe brain diff ./brain-a ./brain-b --verbose
|
|
80
80
|
aqe brain search -i ./brain-export --query oauth --domain test-generation
|
|
81
81
|
aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
|
|
82
|
-
`}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-
|
|
82
|
+
`}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-OVFEPRPS.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
|
|
83
83
|
Brain Diff
|
|
84
84
|
`)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+en(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
|
|
85
85
|
Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
|
|
@@ -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.14.
|
|
2
|
-
import"./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.14.7");process.exit(0)}
|
|
2
|
+
import"./chunk-YO4ESCB4.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
|
|
3
3
|
`),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
|
|
4
4
|
`).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
|
|
5
5
|
`)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.
|
|
2
|
-
import{a 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.14.7");process.exit(0)}
|
|
2
|
+
import{a as p}from"./chunk-FYPX5WBJ.js";import"./chunk-YO4ESCB4.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
|
|
3
3
|
${i.errors.join(`
|
|
4
4
|
`)}`);return this.cache.set(r,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}async list(){try{return(await k(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>y(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(r){if(r.code==="ENOENT")return[];throw r}}async validate(r){let e=[],n=[];if(r.name||e.push("Workflow must have a name"),r.version||e.push("Workflow must have a version"),r.description||n.push("Workflow should have a description"),Array.isArray(r.variables)?r.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(r.steps))e.push("Workflow must have a steps array");else if(r.steps.length===0)e.push("Workflow must have at least one step");else{r.steps.forEach((t,s)=>{t.name||e.push(`Step at index ${s} must have a name`),t.action||e.push(`Step ${t.name||s} must have an action`),(!t.config||typeof t.config!="object")&&e.push(`Step ${t.name||s} must have a config object`),t.assertions&&Array.isArray(t.assertions)&&t.assertions.forEach((f,u)=>{f.condition||e.push(`Assertion ${u} in step ${t.name||s} must have a condition`),f.message||n.push(`Assertion ${u} in step ${t.name||s} should have a message`)})});let o=r.steps.map(t=>t.name),i=o.filter((t,s)=>o.indexOf(t)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(r,e){let n=await this.load(r),o=n.variables.filter(t=>t.required&&!(t.name in e)).map(t=>t.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(t=>{t.name in e?i[t.name]=e[t.name]:"default"in t&&(i[t.name]=t.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:r}}}async getMetadata(r){try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}clearCache(){this.cache.clear()}async reload(r){return this.cache.delete(r),this.load(r)}},x=new l;function w(a,r){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),t=r;for(let s of i)if(t&&typeof t=="object"&&s in t)t=t[s];else return e;return t!=null?String(t):e})}function T(a,r){let e={...r.variables,result:r.results.get("__last_result__")},n=w(a,e);return p(n,e,!1)}var g=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],A={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},h={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function _(a){return h[a]}function P(a){return g.includes(a)}function L(){return g.map(a=>{let r=Object.entries(h).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:A[a],category:r}})}export{h as WORKFLOW_CATEGORIES,A as WORKFLOW_DESCRIPTIONS,g as WORKFLOW_TEMPLATES,l as WorkflowLoader,x as defaultWorkflowLoader,T as evaluateCondition,L as getAllWorkflowTemplates,_ as getWorkflowsByCategory,w as interpolateVariables,P as isValidWorkflowTemplate};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{a}from"./chunk-77QZHIVX.js";import"./chunk-LU2EDWQK.js";import"./chunk-RKUAWQOF.js";import"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import"./chunk-IAENZ2DR.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import"./chunk-FW4DJ4FJ.js";import"./chunk-OXHF3L2T.js";import"./chunk-ND4QTZOL.js";import"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import"./chunk-YO4ESCB4.js";export{a as BrowserWorkflowTool};
|
|
@@ -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.14.
|
|
2
|
-
import{c as U,f as W,g as G}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
|
|
2
|
+
import{c as U,f as W,g as G}from"./chunk-G367W7XR.js";import{b as F}from"./chunk-FSSR6WBE.js";import{o as j,q as V}from"./chunk-BEFTQVEW.js";import{a as T,e as N}from"./chunk-ZUOVNFXK.js";import{b as D,c as $,d as Y}from"./chunk-RDGPXENG.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
|
|
3
3
|
Recommendations: Implement proper ${r[0]} attributes for better accessibility.
|
|
4
4
|
Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
|
|
5
5
|
Context: ${s.description||r.description}
|
|
@@ -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.14.
|
|
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.14.7");process.exit(0)}
|
|
2
2
|
async function o(n){await n.loadAll();let a=new Map;for(let i of n.getLoaded())a.set(i,await n.load(i));return a}export{o as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.
|
|
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.14.7");process.exit(0)}
|
|
2
2
|
import{writeFileSync as d,readFileSync as m}from"node:fs";import{resolve as f,dirname as u,join as g}from"node:path";import{mkdirSync as h}from"node:fs";import{fileURLToPath as v}from"node:url";function y(){try{let e=typeof __dirname<"u"?__dirname:u(v(import.meta.url));for(let n=0;n<5;n++){let t=g(e,"package.json");try{let o=JSON.parse(m(t,"utf-8"));if(o.version)return o.version}catch{}e=u(e)}}catch{}return"unknown"}function l(e){return e.status??e.evidence?.completeness??"unverified"}var R=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],T=["-o, --output <path>","Write output to file instead of stdout"];function w(e,n,t){if(n){let o=f(n);h(u(o),{recursive:!0}),d(o,e,"utf-8"),t&&console.log(t),console.log(`Output written to: ${o}`)}else console.log(e)}function $(e){return JSON.stringify(e,null,2)}var S="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function F(e){let n=l(e),t=s=>{switch(s.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},o=new Map,r=[];for(let s of e.vulnerabilities){let a=s.ruleId||`AQE/${s.type.replace(/\s+/g,"-").toLowerCase()}`;o.has(a)||o.set(a,{id:a,name:s.type,shortDescription:s.type,...s.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${s.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:a,level:t(s.severity),message:{text:s.message},locations:[{physicalLocation:{artifactLocation:{uri:s.file,uriBaseId:"%SRCROOT%"},region:{startLine:s.line,startColumn:1}}}],...s.cweId?{taxa:[{id:s.cweId,toolComponent:{name:"CWE"}}]}:{}})}let i={$schema:S,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:y(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(o.values()).map(s=>({id:s.id,name:s.name,shortDescription:{text:s.shortDescription},...s.helpUri?{helpUri:s.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,properties:{securityScan:{status:n,target:e.target,scanType:e.scanType,coverage:e.evidence?e.coverage:void 0,evidence:e.evidence,discovery:e.discovery,checks:e.checks}},invocations:[{executionSuccessful:n==="complete",...n==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${n}; findings do not establish complete coverage.`}}]}}]}]};return JSON.stringify(i,null,2)}function c(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function A(e){let n=e.tests||[],t=e.passed+e.failed+e.skipped,o=(e.duration/1e3).toFixed(3),r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`;if(r+=`<testsuites tests="${t}" failures="${e.failed}" errors="0" time="${o}">
|
|
4
4
|
`,r+=` <testsuite name="aqe-test-run" tests="${t}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${o}" id="${c(e.runId)}">
|
|
@@ -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.14.
|
|
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.14.7");process.exit(0)}
|
|
2
2
|
var u="quality-assessment";var o=["coverage","testsPassing","criticalBugs","codeSmells","securityVulnerabilities","technicalDebt","duplications"],d={coverage:{direction:"min",value:80,severity:"high"},testsPassing:{direction:"min",value:95,severity:"critical"},criticalBugs:{direction:"max",value:0,severity:"critical"},codeSmells:{direction:"max",value:20,severity:"medium"},securityVulnerabilities:{direction:"max",value:0,severity:"critical"},technicalDebt:{direction:"max",value:5,severity:"medium"},duplications:{direction:"max",value:5,severity:"low"}};function c(a){return`quality-evidence:${a}:latest`}function l(a,t,e){if(typeof a!="string")throw new Error("Measured quality evidence is malformed: measuredAt is required.");let r=Date.parse(a);if(!Number.isFinite(r))throw new Error("Measured quality evidence is malformed: measuredAt is invalid.");if(r>t+6e4)throw new Error("Measured quality evidence is malformed: measuredAt is in the future.");if(t-r>e)throw new Error("Measured quality evidence is stale. Run the relevant quality analyzers again.");return r}function m(a,t,e,r){if(!a||typeof a!="object")throw new Error(`No measured quality evidence found for ${t}.`);let i=a;if(i.schemaVersion!==1||i.metric!==t||!Number.isFinite(i.value)||i.value<0||typeof i.source!="string"||i.source.trim().length===0)throw new Error(`Measured quality evidence for ${t} is malformed or incomplete.`);l(i.measuredAt,e,r)}async function v(a,t,e){let r=Date.now();if(l(e.measuredAt,r,Number.POSITIVE_INFINITY),e.source.trim().length===0)throw new Error("Quality evidence source is required.");for(let i of o){let n=t[i];if(n===void 0)continue;if(!Number.isFinite(n)||n<0)throw new Error(`Quality evidence value for ${i} must be a non-negative finite number.`);let s={schemaVersion:1,metric:i,value:n,measuredAt:e.measuredAt,source:e.source};await a.set(c(i),s,{namespace:u,persist:!0})}}async function y(a,t={}){let e=t.now??Date.now(),r=t.maxAgeMs??864e5,i={};for(let n of o){let s=await a.get(c(n),{namespace:u});m(s,n,e,r),i[n]=s.value}return i}function E(a){let t=o.map(e=>{let r=d[e],i=a[e];return{name:e,value:i,threshold:r.value,direction:r.direction,severity:r.severity,passed:r.direction==="min"?i>=r.value:i<=r.value}});return{passed:t.every(e=>e.passed),checks:t,recommendations:t.filter(e=>!e.passed).map(e=>`${e.name} failed its measured ${e.direction} threshold.`)}}export{d as a,v as b,y as c,E as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.
|
|
2
|
-
import{b as k,c 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.14.7");process.exit(0)}
|
|
2
|
+
import{b as k,c as p}from"./chunk-IAENZ2DR.js";p();import{generateKeyPairSync as g,createPrivateKey as v,createPublicKey as I,sign as m,verify as D,createHash as b}from"crypto";import{existsSync as d,mkdirSync as P,writeFileSync as y,readFileSync as o,readdirSync as w}from"fs";import{join as n}from"path";var f=class{keys=new Map;activeKeyId=null;keyDir;constructor(e={}){this.keyDir=e.keyDir??null,this.keyDir&&this.loadFromDisk(),e.autoGenerate!==!1&&this.keys.size===0&&this.generateKeyPair()}generateKeyPair(){let{publicKey:e,privateKey:i}=g("ed25519"),r=e.export({type:"spki",format:"der"}),t=b("sha256").update(r).digest("hex").slice(0,16),s={keyId:t,publicKey:e,privateKey:i,createdAt:new Date().toISOString(),retired:!1};return this.keys.set(t,s),this.activeKeyId=t,this.keyDir&&(this.saveKeyPairToDisk(s),this.saveActiveKeyId()),{keyId:t,publicKey:r}}sign(e,i){let r=i??this.activeKeyId;if(!r)throw new Error("No active key available for signing");let t=this.keys.get(r);if(!t)throw new Error(`Key not found: ${r}`);return{signature:m(null,e,t.privateKey),keyId:r}}verify(e,i,r){let t=this.keys.get(r);if(!t)return!1;try{return D(null,e,t.publicKey,i)}catch{return!1}}rotateKey(){let e=this.activeKeyId;if(!e)throw new Error("No active key to rotate");let i=this.keys.get(e);i&&(i.retired=!0,this.keyDir&&this.saveKeyPairToDisk(i));let{keyId:r}=this.generateKeyPair();return{oldKeyId:e,newKeyId:r}}getActiveKeyId(){if(!this.activeKeyId)throw new Error("No active key");return this.activeKeyId}hasKey(e){return this.keys.has(e)}getKeyCount(){return this.keys.size}saveKeyPairToDisk(e){if(!this.keyDir)return;d(this.keyDir)||P(this.keyDir,{recursive:!0});let i=n(this.keyDir,e.keyId);y(`${i}.pub.pem`,e.publicKey.export({type:"spki",format:"pem"}),"utf-8"),y(`${i}.key.pem`,e.privateKey.export({type:"pkcs8",format:"pem"}),{encoding:"utf-8",mode:384}),y(`${i}.meta.json`,JSON.stringify({keyId:e.keyId,createdAt:e.createdAt,retired:e.retired}),"utf-8")}saveActiveKeyId(){!this.keyDir||!this.activeKeyId||y(n(this.keyDir,"active-key-id"),this.activeKeyId,"utf-8")}loadFromDisk(){if(!this.keyDir||!d(this.keyDir))return;let i=w(this.keyDir).filter(t=>t.endsWith(".meta.json"));for(let t of i)try{let s=JSON.parse(o(n(this.keyDir,t),"utf-8")),a=n(this.keyDir,s.keyId),l=o(`${a}.pub.pem`,"utf-8"),K=o(`${a}.key.pem`,"utf-8"),h={keyId:s.keyId,publicKey:I(l),privateKey:v(K),createdAt:s.createdAt,retired:s.retired};this.keys.set(s.keyId,h)}catch{}let r=n(this.keyDir,"active-key-id");if(d(r)){let t=o(r,"utf-8").trim();this.keys.has(t)&&(this.activeKeyId=t)}if(!this.activeKeyId){let t=[...this.keys.values()].filter(s=>!s.retired).sort((s,a)=>a.createdAt.localeCompare(s.createdAt));t.length>0&&(this.activeKeyId=t[0].keyId)}}},c=null;function F(){if(!c){let u=n(k(),".agentic-qe","witness-keys");c=new f({keyDir:u})}return c}function O(){c=null}export{f as a,F as b,O as c};
|
|
@@ -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.14.
|
|
2
|
-
import{b as z,c as pe}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.14.7");process.exit(0)}
|
|
2
|
+
import{b as z,c as pe}from"./chunk-IAENZ2DR.js";import{a as F,e as le}from"./chunk-ZUOVNFXK.js";import{b as G,d as k}from"./chunk-HYFQUWNB.js";k();le();k();import*as C from"node:http";import*as _ from"node:https";import{createHash as ce}from"node:crypto";import{URL as X}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},me="AQE embedder endpoint identity canary v1",ue="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function fe(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},R=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=fe(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new _.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new C.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([me]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ce("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return G(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ue,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=C.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?_.request:C.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,M=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);M(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as K,resolve as ge}from"node:path";import{existsSync as he,mkdirSync as Ee}from"node:fs";import{createRequire as be}from"node:module";var ye=be(import.meta.url);function we(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:ge(z(),t):K(z(),".agentic-qe","memory.db")}var Q="_system",Y="embedder_identity:",x=null,U=!1;function Z(){if(x)return x;if(U)return null;try{let t=ye("better-sqlite3"),e=we(),n=K(e,"..");he(n)||Ee(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS kv_store (
|
|
4
4
|
key TEXT NOT NULL,
|
|
5
5
|
namespace TEXT NOT NULL,
|
|
@@ -10,4 +10,4 @@ import{b as z,c as pe}from"./chunk-C3HQL6S4.js";import{a as F,c as le}from"./chu
|
|
|
10
10
|
);
|
|
11
11
|
CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
|
|
12
12
|
`),x=r,r}catch{return U=!0,null}}function ee(t){let e=Z();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Q,Y+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function te(t){let e=Z();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Y+t.endpoint,Q,JSON.stringify(n))}function ne(){if(x)try{x.close()}catch{}x=null,U=!1}k();import{createHash as re}from"node:crypto";import{existsSync as ve,readFileSync as Ae,renameSync as Te,writeFileSync as xe}from"node:fs";var ie="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Se(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function oe(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return re("sha256").update(e).digest("hex").slice(0,16)}function B(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=re("sha256").update("aqe:embedding-space:v1\0").update(Se(t)).digest("hex");return{...t,spaceId:e}}function Be(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}function Ce(t){return`${t}.space.json`}function Ve(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=Ce(t);if(ve(r)){let s;try{s=JSON.parse(Ae(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;xe(i,`${JSON.stringify(a)}
|
|
13
|
-
`,{encoding:"utf8",mode:384}),Te(i,r)}var V=null,f=null,N=null,O=!1,P="",v=null,p=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,se=36e5;function L(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function ae(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(O)throw new Error(`Transformer initialization previously failed: ${P}`);if(N)return N;let e={...H,...t};return N=(async()=>{try{if(e.endpoint){let l=J(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new R({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),A=B({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=ee(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),te(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Ne(v);return}let n;try{n=await import("./transformers-
|
|
13
|
+
`,{encoding:"utf8",mode:384}),Te(i,r)}var V=null,f=null,N=null,O=!1,P="",v=null,p=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,se=36e5;function L(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function ae(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(O)throw new Error(`Transformer initialization previously failed: ${P}`);if(N)return N;let e={...H,...t};return N=(async()=>{try{if(e.endpoint){let l=J(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new R({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),A=B({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=ee(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),te(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Ne(v);return}let n;try{n=await import("./transformers-4TC35KKS.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ie,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=B({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:oe(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw O=!0,P=F(n),new Error(`Failed to initialize transformer model: ${P}`)}})(),N}function Ne(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Xe(t,e={}){let n={...H,...e};if(ae(t))return new Array(D()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<se)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Je(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)ae(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(L(t[o]));l&&Date.now()-l.timestamp<se?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),M=await f(y,{pooling:"mean",normalize:!0}),h=M.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(M.data.slice(u,u+d)),S=b+g,de=a[S];if(i[de]=E,n.enableCache){if(c.size>=n.maxCacheSize){let j=c.keys().next().value;j&&c.delete(j)}c.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ke(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function Qe(){return{size:c.size,hitRate:0}}function Ye(){return!O&&f!==null}function D(){return 384}function Ze(){V=null,f=null,N=null,O=!1,P="",c.clear(),v&&v.close(),v=null,p=null,A=null,ne()}function et(){return v!==null}function tt(){return p}function nt(){return A}async function rt(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{ie as a,Be as b,Ve as c,H as d,Xe as e,Je as f,Ke as g,Qe as h,Ye as i,D as j,Ze as k,et as l,tt as m,nt as n,rt as o};
|
|
@@ -0,0 +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.14.7");process.exit(0)}
|
|
2
|
+
import{a as v,b as I,e as O}from"./chunk-ZUOVNFXK.js";var x={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},V={enabled:!0,laneConfig:x,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},p={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},b=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends b{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var k=class extends b{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},G={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};O();var H=4*1024*1024,j=32*1024*1024;function J(d){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`;function*c(){i.clear(),n.clear(),r=0;let s=e.values().next().value?.embedding.length,o=Array.from(e.entries()).map(([g,y])=>{if(y.embedding.length!==s)throw new RangeError("Cohomology graphs require matching embedding dimensions");return{id:a(g),label:g,section:Array.from(y.embedding),weight:1}}),u=0,m=t.map(g=>{let y=e.get(g.source),C=e.get(g.target);if(!y||!C)throw new Error(`Cohomology edge references an unknown node: ${g.source} -> ${g.target}`);let D=y.embedding.length,N=D*D;if(N>H)throw new RangeError(`Cohomology restriction map exceeds ${H} cells`);if(u+=N,u>j)throw new RangeError(`Cohomology graph exceeds ${j} restriction-map cells`);return{...g,dimension:D,cells:N}}),f=[],F=0,P=new Map;for(let g of m){F+g.cells>H&&(yield{nodes:o,edges:f},f=[],F=0,P.clear());let y=P.get(g.dimension);if(!y){y=Array(g.cells).fill(0);for(let C=0;C<g.dimension;C++)y[C*g.dimension+C]=1;P.set(g.dimension,y)}f.push({source:i.get(g.source),target:i.get(g.target),weight:g.weight,restriction_map:y,source_dim:g.dimension,target_dim:g.dimension}),F+=g.cells}(f.length>0||m.length===0)&&(yield{nodes:o,edges:f})}return{add_node(s,o){e.set(s,{embedding:o}),a(s)},add_edge(s,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},remove_edge(s,o){let u=t.findIndex(m=>m.source===s&&m.target===o);u>=0&&t.splice(u,1)},sheaf_laplacian_energy(){let s=0;for(let o of c())s+=d.consistencyEnergy(o);return s},detect_contradictions(s){let o=[];for(let u of c()){let m=d.detectObstructions(u);for(let f of m??[])f.magnitude>s&&o.push({node1:l(f.source_node),node2:l(f.target_node),severity:f.magnitude,distance:f.magnitude})}return o.sort((u,m)=>m.distance-u.distance)},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var w=class{constructor(e,t=p){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=J(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:Math.max(0,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)}};O();function Z(d){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let o=i.get(s);return o===void 0&&(o=r++,i.set(s,o),n.set(o,s)),o},l=s=>n.get(s)??`unknown-${s}`,c=()=>({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,o,u){t.push({source:s,target:o,weight:u}),a(s),a(o)},remove_node(s){e.delete(s);for(let o=t.length-1;o>=0;o--)(t[o].source===s||t[o].target===s)&&t.splice(o,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=c(),o=d.algebraicConnectivity(s);return Number.isFinite(o)&&o>=0?o: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=c(),o=d.algebraicConnectivity(s),u=Number.isFinite(o)&&o>=0?o:0;return Math.max(0,Math.min(1,1-u))}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 o=c(),u=d.predictMinCut(o);return u?.vertices?u.vertices.slice(0,s).map(m=>l(m)):Array.from(e).slice(0,s)}catch(o){return console.warn("[SpectralAdapter] predictMinCut failed:",o),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var E=class{constructor(e,t=p){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=Z(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:v(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:v(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:v(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 c of e.agents)this.addNode(c.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,l={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}),l}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,l=e.beliefs??[],c=t.beliefs??[];return l.length>0&&c.length>0&&(a=this.computeBeliefOverlap(l,c)),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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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 ee(d){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 d.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(d.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return d.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var A=class{constructor(e,t=p){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=ee(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[m,f]of Object.entries(i.confounders))this.addConfounder(m,f);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),l=this.getConfounders(),c=this.determineRelationshipType(r,a,l.length>0),s=this.computeConfidence(i.sampleSize,r,a),o=Date.now()-n,u={isCausal:c==="causal",effectStrength:r,relationshipType:c,confidence:s,confounders:l,explanation:this.generateExplanation(e,t,c,r,l),durationMs:o,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:u.isCausal,relationshipType:c,effectStrength:r,durationMs:o}),u}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 te(d){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 l=n[a],c=n[a+1];if(!t.some(o=>o.source===l&&o.target===c))return!1}let r=i();return d.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 T=class{constructor(e,t=p){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=te(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),l=Date.now()-t,c={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:l,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:c.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:l}),c}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 ie(d){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},l={formula:r.formula};return d.typeCheck(a,l)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return d.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 R=class{constructor(e,t=p){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=ie(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 ne}from"crypto";var S=class{constructor(e,t=p){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=ne("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()}`,l={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,l),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:l.chainPosition}),l}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,l={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}),l}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")}};function $(d){let e=new Map;for(let r of d){let a=String(r.verdict);e.set(a,(e.get(a)??0)+1)}let t=[...e.entries()].map(([r,a])=>({verdict:r,count:a})).sort((r,a)=>a.count-r.count||r.verdict.localeCompare(a.verdict)),i=t[0]??{verdict:"",count:0},n=d.length;return{total:n,counts:t,topVerdict:i.verdict,topCount:i.count,majorityRatio:n>0?i.count/n:0,isUnanimous:t.length===1}}function L(d){return`${d.topCount} of ${d.total} votes '${d.topVerdict}'`}function U(d){return d.counts.map(({verdict:e,count:t})=>`${t} '${e}'`).join(" / ")}var Y=.6,ce=3;function Q(d){return d.isUnanimous&&d.total>=ce}function _(d){return d.isUnanimous?L(d):`${L(d)}; ${U(d)}`}var W=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...V,...t},this.logger=i||p}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 w(this.wasmLoader,this.logger),this.spectralAdapter=new E(this.wasmLoader,this.logger),this.causalAdapter=new A(this.wasmLoader,this.logger),this.categoryAdapter=new T(this.wasmLoader,this.logger),this.homotopyAdapter=new R(this.wasmLoader,this.logger),this.witnessAdapter=new S(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 b("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",I(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 l of e)this.cohomologyAdapter.addNode(l);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 o=s+1;o<e.length;o++){let u=this.euclideanDistance(e[s].embedding,e[o].embedding);i+=u,n++,u>1.5&&r.push({nodeIds:[e[s].id,e[o].id],severity:u>2?"critical":"high",description:`High distance (${u.toFixed(2)}) between nodes`,confidence:Math.min(1,u/2)})}let a=n>0?i/n:0,l=this.computeLane(a),c=Date.now()-t;return this.updateStats(a,c,r.length,l,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:l,contradictions:r,recommendations:this.generateRecommendations(a,l,r),durationMs:c,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:v(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((l,c)=>l+c.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((l,c)=>l+c.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(l=>l.health<.5||l.successRate<.5).map(l=>l.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 o of e)this.spectralAdapter.addNode(o.agentId);let i=0;for(let o=0;o<e.length;o++)for(let u=o+1;u<e.length;u++)e[o].verdict===e[u].verdict&&(this.spectralAdapter.addEdge(e[o].agentId,e[u].agentId,Math.min(e[o].confidence,e[u].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(),a=$(e);if(a.isUnanimous&&e.every(o=>o.confidence>0)&&!(r>0))return this.logger.warn("Spectral engine returned a zero Fiedler value for a connected agreement graph, using fallback",{fiedlerValue:r,voteCount:e.length}),this.verifyConsensusWithFallback(e,t);let l=n<.3&&r>.1,c=Q(a),s;return l?c?s=`Consensus verified (${_(a)}), but unanimous agreement may indicate false consensus. Consider adding diversity.`:s=`Consensus verified (${_(a)}).`:s=`No verified consensus (${_(a)}): agreement-graph Fiedler value ${r.toFixed(3)}, collapse risk ${n.toFixed(2)}. Spawn independent reviewer.`,{isValid:l,confidence:1-n,isFalseConsensus:c,fiedlerValue:r,collapseRisk:n,recommendation:s,durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:v(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=$(e),{majorityRatio:n}=i,r=e.reduce((s,o)=>s+o.confidence,0)/e.length,a=n>Y,l=Q(i),c;return a?l?c=`Unanimous consensus (${L(i)}) may indicate false consensus. Consider adding diversity.`:i.isUnanimous?c=`Unanimous consensus achieved (${L(i)}).`:c=`Majority consensus achieved (${_(i)}).`:c=`No clear majority: ${U(i)} across ${i.total} votes (needs more than ${Math.round(Y*100)}% agreeing). Consider spawning additional agents.`,{isValid:a,confidence:n*r,isFalseConsensus:l,fiedlerValue:n,collapseRisk:1-n,recommendation:c,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(l=>r.add(l));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 l=0;l<e.length;l++)i+=e[l]*t[l],n+=e[l]*e[l],r+=t[l]*t[l];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((o,u)=>o+u,0)/i,r=t.reduce((o,u)=>o+u,0)/i,a=0,l=0,c=0;for(let o=0;o<i;o++){let u=e[o]-n,m=t[o]-r;a+=u*m,l+=u*u,c+=m*m}let s=Math.sqrt(l*c);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 ue(d,e,t){let i=new W(d,e,t);return await i.initialize(),i}O();import{createRequire as K}from"node:module";import{fileURLToPath as he}from"node:url";import{dirname as q,join as M}from"node:path";import{readFileSync as ge,existsSync as X}from"node:fs";var B=[1e3,2e3,4e3],z=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={...G,...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=I(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=K(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return M(q(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(X(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(),l=await this.attemptLoad(),c=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(c*100)/100}),l}catch(a){if(n=I(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let l=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:l,previousError:n}),await this.sleep(l)}}throw new k(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=K(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-M5EYRONA.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${v(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 M(q(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),M(q(he(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),M(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(X(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
|
|
3
|
+
${i.join(`
|
|
4
|
+
`)}
|
|
5
|
+
Ensure prime-radiant-advanced-wasm is installed.`);let r=ge(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,B.length-1),i=B[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<B.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}},me=new z;var pe={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...x}};export{$ as a,U as b,ue as c,me as d};
|