agentic-qe 3.11.5 → 3.12.1
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/helpers/.helpers-version +1 -0
- package/.claude/helpers/auto-memory-hook.mjs +35 -3
- package/.claude/helpers/brain-checkpoint.cjs +16 -1
- package/.claude/helpers/helpers.manifest.json +12 -0
- package/.claude/helpers/hook-handler.cjs +26 -5
- package/.claude/helpers/intelligence.cjs +14 -1
- package/.claude/hooks/aqe-hook.cjs +14 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +87 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/adapters/a2a/auth/routes.js +59 -28
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-X4UEC6UJ.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-CSTBLNYZ.js → agent-booster-wasm-P4VYM5KK.js} +2 -2
- package/dist/cli/chunks/{agent-handler-M4W4GTXN.js → agent-handler-PBQ7L2TO.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-VGXFYLSQ.js → agent-memory-branch-UPWO3X6V.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-5FG7JCY7.js +2 -0
- package/dist/cli/chunks/{arena-IQBRGWAG.js → arena-LEUTILZ7.js} +2 -2
- package/dist/cli/chunks/{arena-FKSD3LLM.js → arena-QYTP3FG6.js} +4 -4
- package/dist/cli/chunks/{audit-7NSGRR4Z.js → audit-TB6M2YLK.js} +3 -3
- package/dist/cli/chunks/base-CWPMFSZG.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-E6NSZPP2.js → better-sqlite3-IPKCAVLS.js} +2 -2
- package/dist/cli/chunks/{brain-handler-M6A3UB66.js → brain-handler-JF3OK35F.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-2JGKY4BB.js → branch-enumerator-WEIP3DXB.js} +2 -2
- package/dist/cli/chunks/{browser-J43WQPJL.js → browser-HY6VLXHZ.js} +2 -2
- package/dist/cli/chunks/browser-workflow-A77OFBVY.js +2 -0
- package/dist/cli/chunks/{chunk-7BCRULCP.js → chunk-2PQ7YADF.js} +2 -2
- package/dist/cli/chunks/{chunk-XKQY2Z3Q.js → chunk-3I3Z4C5X.js} +1 -1
- package/dist/cli/chunks/{chunk-MCHEUSY4.js → chunk-3W2FZXFD.js} +1 -1
- package/dist/cli/chunks/{chunk-WMZ2QGGS.js → chunk-42GFB7VX.js} +2 -2
- package/dist/cli/chunks/{chunk-UBI2EOS3.js → chunk-42PYEEYQ.js} +1 -1
- package/dist/cli/chunks/{chunk-HJWT4KME.js → chunk-45QNHMTP.js} +1 -1
- package/dist/cli/chunks/{chunk-AGJOGUP5.js → chunk-4KI72C2E.js} +1 -1
- package/dist/cli/chunks/{chunk-5WMU7XCF.js → chunk-4LKQZW2H.js} +1 -1
- package/dist/cli/chunks/{chunk-SUL3I6QZ.js → chunk-4U5MJX2H.js} +2 -2
- package/dist/cli/chunks/{chunk-DFRRWOEX.js → chunk-55MQ2SFP.js} +2 -2
- package/dist/cli/chunks/{chunk-KP3R2M2G.js → chunk-5H5A74U2.js} +1 -1
- package/dist/cli/chunks/{chunk-YBPLJRVT.js → chunk-5HMGDB7B.js} +2 -2
- package/dist/cli/chunks/{chunk-YZSTZUGJ.js → chunk-6432JORM.js} +1 -1
- package/dist/cli/chunks/{chunk-CDJP6COA.js → chunk-6BCVKCG5.js} +2 -2
- package/dist/cli/chunks/{chunk-TBT3OFRW.js → chunk-6ONUCDVL.js} +2 -2
- package/dist/cli/chunks/{chunk-3LY7OCSO.js → chunk-6RX5QZMU.js} +1 -1
- package/dist/cli/chunks/chunk-74VIADSJ.js +2 -0
- package/dist/cli/chunks/{chunk-K4I7UIU5.js → chunk-75AVUS5U.js} +1 -1
- package/dist/cli/chunks/{chunk-KVVJVMDM.js → chunk-774X6OJY.js} +2 -2
- package/dist/cli/chunks/chunk-7KHIOWBN.js +2 -0
- package/dist/cli/chunks/{chunk-62OTU2AP.js → chunk-7KK6XSYK.js} +2 -2
- package/dist/cli/chunks/{chunk-RFLHPLET.js → chunk-7N2SCRWJ.js} +1 -1
- package/dist/cli/chunks/{chunk-OS2HHJTM.js → chunk-AGWKCY42.js} +2 -2
- package/dist/cli/chunks/chunk-BAHXVVX3.js +4 -0
- package/dist/cli/chunks/{chunk-6T65OKUM.js → chunk-BALFQQB7.js} +2 -2
- package/dist/cli/chunks/{chunk-I3ANRYQ6.js → chunk-BBNQDHGF.js} +2 -2
- package/dist/cli/chunks/{chunk-LOE2JETO.js → chunk-BCBITOMT.js} +2 -2
- package/dist/cli/chunks/{chunk-FII3WCCY.js → chunk-BKKJEKNT.js} +2 -2
- package/dist/cli/chunks/{chunk-TTJJ4DQE.js → chunk-BLU7OLQZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AL5VJJN4.js → chunk-BNMV5DCM.js} +1 -1
- package/dist/cli/chunks/{chunk-4XJ2A3HY.js → chunk-BPM7NEHS.js} +4 -4
- package/dist/cli/chunks/{chunk-3V36WMIO.js → chunk-BWNMAXV7.js} +1 -1
- package/dist/cli/chunks/{chunk-EDOGRFAG.js → chunk-BXIJY6SB.js} +1 -1
- package/dist/cli/chunks/{chunk-ZXEWTZFR.js → chunk-C2K4LQI5.js} +1 -1
- package/dist/cli/chunks/{chunk-3WR35GFF.js → chunk-C7HGYLNF.js} +2 -2
- package/dist/cli/chunks/{chunk-7YSBATSN.js → chunk-CDVKFAYP.js} +2 -2
- package/dist/cli/chunks/{chunk-JBKZ5TUM.js → chunk-CJTXZI37.js} +2 -2
- package/dist/cli/chunks/{chunk-VMWRMINE.js → chunk-CP4GSICY.js} +1 -1
- package/dist/cli/chunks/{chunk-2XPMATEK.js → chunk-CXUHD2O5.js} +2 -2
- package/dist/cli/chunks/{chunk-W7TYKPLY.js → chunk-CYYT6YEV.js} +2 -2
- package/dist/cli/chunks/{chunk-SO6G4IX3.js → chunk-D72N5V2S.js} +2 -2
- package/dist/cli/chunks/{chunk-4LODYRNV.js → chunk-DQ3J7ZT6.js} +2 -2
- package/dist/cli/chunks/{chunk-PVDXNQPL.js → chunk-DSNFOX22.js} +2 -2
- package/dist/cli/chunks/{chunk-LPR2R3AN.js → chunk-EOBZJDJR.js} +3 -3
- package/dist/cli/chunks/{chunk-6R3YOAKO.js → chunk-FBYFDD7L.js} +2 -2
- package/dist/cli/chunks/{chunk-ZPP57WQU.js → chunk-FFSS3Y6W.js} +2 -2
- package/dist/cli/chunks/chunk-FNMEVLSN.js +2 -0
- package/dist/cli/chunks/{chunk-7KXPNNMR.js → chunk-GASACVTU.js} +2 -2
- package/dist/cli/chunks/{chunk-ABU64UWB.js → chunk-GGF5FZWS.js} +1 -1
- package/dist/cli/chunks/{chunk-M6FW56MV.js → chunk-GLO53MUQ.js} +2 -2
- package/dist/cli/chunks/{chunk-52U5BFZP.js → chunk-GW3M7GQH.js} +2 -2
- package/dist/cli/chunks/chunk-GXMNCW2M.js +2 -0
- package/dist/cli/chunks/{chunk-D45QLJEL.js → chunk-HDI3FD4G.js} +1 -1
- package/dist/cli/chunks/{chunk-26WEI3P4.js → chunk-HGKSU4QV.js} +2 -2
- package/dist/cli/chunks/{chunk-B2VBDMDI.js → chunk-HHMTQQUE.js} +2 -2
- package/dist/cli/chunks/{chunk-4Y3LGBKJ.js → chunk-HZGFER4N.js} +3 -3
- package/dist/cli/chunks/{chunk-AXKWV5NF.js → chunk-I4BZLVFE.js} +3 -3
- package/dist/cli/chunks/{chunk-JDSHUECG.js → chunk-IC6SOVGO.js} +2 -2
- package/dist/cli/chunks/{chunk-YFCULQBP.js → chunk-IE6FDICX.js} +2 -2
- package/dist/cli/chunks/{chunk-FGD6HINU.js → chunk-IHWWZOHP.js} +1 -1
- package/dist/cli/chunks/{chunk-HC6KTVFR.js → chunk-J4IAMQZI.js} +2 -2
- package/dist/cli/chunks/{chunk-VMFAANWX.js → chunk-J6ZCULWG.js} +2 -2
- package/dist/cli/chunks/{chunk-YGVDP6X7.js → chunk-JDZIBSMY.js} +1 -1
- package/dist/cli/chunks/{chunk-WPSK237F.js → chunk-JIM4VSLF.js} +3 -3
- package/dist/cli/chunks/{chunk-EK3HPH6A.js → chunk-JRHRC2MP.js} +1 -1
- package/dist/cli/chunks/{chunk-3JF5A72M.js → chunk-JRNDFC23.js} +2 -2
- package/dist/cli/chunks/chunk-JWZNWVLG.js +153 -0
- package/dist/cli/chunks/{chunk-Q5TR6ETB.js → chunk-KQV5644J.js} +3 -3
- package/dist/cli/chunks/{chunk-4RTWPR3X.js → chunk-LAJHHR3Q.js} +1 -1
- package/dist/cli/chunks/{chunk-AOXJFDH5.js → chunk-LF5XOYR7.js} +10 -10
- package/dist/cli/chunks/{chunk-I3NWKPXJ.js → chunk-LRWBOJ5Y.js} +2 -2
- package/dist/cli/chunks/{chunk-354367AP.js → chunk-LZ6TJ7XL.js} +2 -2
- package/dist/cli/chunks/{chunk-4QOI5JS7.js → chunk-M5P5WNXA.js} +1 -1
- package/dist/cli/chunks/{chunk-SE3JFUKP.js → chunk-MCUILJ33.js} +1 -1
- package/dist/cli/chunks/{chunk-ZG5UAEEO.js → chunk-MIAY35K6.js} +2 -2
- package/dist/cli/chunks/{chunk-6Q57K4YD.js → chunk-N3PSRG6F.js} +2 -2
- package/dist/cli/chunks/{chunk-FMNXHVIN.js → chunk-NEXJUTHF.js} +2 -2
- package/dist/cli/chunks/{chunk-RJN2RM76.js → chunk-NHRBKOYD.js} +2 -2
- package/dist/cli/chunks/{chunk-BJLA2IX7.js → chunk-NK2Z6FGF.js} +2 -2
- package/dist/cli/chunks/{chunk-Y25PO65W.js → chunk-NOCPO55P.js} +2 -2
- package/dist/cli/chunks/{chunk-XT4TDLOB.js → chunk-NTMN2ZJY.js} +2 -2
- package/dist/cli/chunks/{chunk-7DTMENY6.js → chunk-NVXSM7UO.js} +2 -2
- package/dist/cli/chunks/{chunk-CKOF27L7.js → chunk-O65OPAZH.js} +2 -2
- package/dist/cli/chunks/{chunk-OGNTCZKK.js → chunk-OEXSBR72.js} +1 -1
- package/dist/cli/chunks/{chunk-Y6DWJKHU.js → chunk-OJORNYN3.js} +3 -3
- package/dist/cli/chunks/{chunk-DPL762HU.js → chunk-ONSNNY6J.js} +1 -1
- package/dist/cli/chunks/{chunk-IBDQWKI3.js → chunk-OXVAGR64.js} +2 -2
- package/dist/cli/chunks/{chunk-C5C4W572.js → chunk-P7G5LGUE.js} +2 -2
- package/dist/cli/chunks/{chunk-XLT3FYS7.js → chunk-PDS5P5QD.js} +2 -2
- package/dist/cli/chunks/{chunk-IU5RSN6M.js → chunk-PQ4NSXZM.js} +2 -2
- package/dist/cli/chunks/{chunk-4MHN7JWC.js → chunk-PRA73XZY.js} +12 -12
- package/dist/cli/chunks/{chunk-2XQHG56O.js → chunk-PZ3Q34OT.js} +2 -2
- package/dist/cli/chunks/{chunk-EEKG35K5.js → chunk-PZZDAECU.js} +3 -3
- package/dist/cli/chunks/{chunk-J6PFPY7V.js → chunk-QJXUK54J.js} +2 -2
- package/dist/cli/chunks/{chunk-7P6X4BFO.js → chunk-QOAI6ETC.js} +3 -3
- package/dist/cli/chunks/{chunk-53YOYZW5.js → chunk-QORWBION.js} +2 -2
- package/dist/cli/chunks/{chunk-OS62Y77J.js → chunk-QXZOUETY.js} +2 -2
- package/dist/cli/chunks/{chunk-G2ZIJZJ7.js → chunk-QZBPXJ5C.js} +2 -2
- package/dist/cli/chunks/{chunk-WHHQIL4F.js → chunk-R4A6PY5D.js} +2 -2
- package/dist/cli/chunks/{chunk-ZLBY25MB.js → chunk-R7XEACKR.js} +1 -1
- package/dist/cli/chunks/{chunk-K4C25BWV.js → chunk-RAS7WRN5.js} +2 -2
- package/dist/cli/chunks/{chunk-MHMQ6MCT.js → chunk-REJGZP27.js} +2 -2
- package/dist/cli/chunks/{chunk-PW72M2FE.js → chunk-RIASOMB2.js} +2 -2
- package/dist/cli/chunks/{chunk-TEIWJ3GJ.js → chunk-RJ7TU2MP.js} +1 -1
- package/dist/cli/chunks/{chunk-W72FJA2H.js → chunk-S42RFOZJ.js} +2 -2
- package/dist/cli/chunks/chunk-SFQFBLWQ.js +2 -0
- package/dist/cli/chunks/{chunk-O7J54OHN.js → chunk-SHKOPOPD.js} +1 -1
- package/dist/cli/chunks/{chunk-QKK7VBVB.js → chunk-TGIKKD43.js} +2 -2
- package/dist/cli/chunks/chunk-TMPRR3FZ.js +2 -0
- package/dist/cli/chunks/{chunk-GW6XWMX2.js → chunk-U55X2ZUM.js} +2 -2
- package/dist/cli/chunks/{chunk-C4EZNOWK.js → chunk-U5ITD7ZD.js} +1 -1
- package/dist/cli/chunks/{chunk-RKXZLTWR.js → chunk-UBPJQKYS.js} +2 -2
- package/dist/cli/chunks/{chunk-DVW66FPU.js → chunk-UBWSYDO5.js} +1 -1
- package/dist/cli/chunks/chunk-UEC53US3.js +316 -0
- package/dist/cli/chunks/{chunk-UBY322ED.js → chunk-UGPBL7LX.js} +2 -2
- package/dist/cli/chunks/{chunk-MMEXHZUC.js → chunk-UKF4V7LE.js} +5 -5
- package/dist/cli/chunks/{chunk-FIPKIIMS.js → chunk-UR655D4K.js} +2 -2
- package/dist/cli/chunks/{chunk-GODAWJMZ.js → chunk-USTUWUCE.js} +2 -2
- package/dist/cli/chunks/{chunk-FGSIID5C.js → chunk-UZXDYT6O.js} +2 -2
- package/dist/cli/chunks/{chunk-JATLFS6A.js → chunk-VFRWLSQO.js} +1 -1
- package/dist/cli/chunks/{chunk-AF6P5RWY.js → chunk-VHJCQBD2.js} +2 -2
- package/dist/cli/chunks/{chunk-J5XDKVI7.js → chunk-VTFYY4SH.js} +2 -2
- package/dist/cli/chunks/{chunk-BTLUWH4R.js → chunk-W52R3G22.js} +2 -2
- package/dist/cli/chunks/{chunk-AOQYORVA.js → chunk-WBDV4V3H.js} +2 -2
- package/dist/cli/chunks/{chunk-3I4TCMOJ.js → chunk-WPEGG6DX.js} +1 -1
- package/dist/cli/chunks/{chunk-KQVIWE3W.js → chunk-WPG5LXR7.js} +2 -2
- package/dist/cli/chunks/{chunk-DLBVADWQ.js → chunk-X2CEX4KC.js} +42 -42
- package/dist/cli/chunks/{chunk-MTBGOWJA.js → chunk-X2K3BTI4.js} +2 -2
- package/dist/cli/chunks/{chunk-NCSXLMDL.js → chunk-XDRAU3W6.js} +2 -2
- package/dist/cli/chunks/{chunk-URP75DL4.js → chunk-XJTGLG7G.js} +1 -1
- package/dist/cli/chunks/{chunk-TRNBQFFG.js → chunk-XS6BIOPQ.js} +2 -2
- package/dist/cli/chunks/{chunk-MEIU7457.js → chunk-XTAXSKPC.js} +2 -2
- package/dist/cli/chunks/{chunk-VN2HHBZN.js → chunk-XYV6YUWS.js} +2 -2
- package/dist/cli/chunks/{chunk-UORTQXJ2.js → chunk-YGB3MT3R.js} +1 -1
- package/dist/cli/chunks/{chunk-37ZUF5NX.js → chunk-YNXQMJGJ.js} +1 -1
- package/dist/cli/chunks/{chunk-BLPWJQTY.js → chunk-ZCDGLNJ7.js} +2 -2
- package/dist/cli/chunks/{chunk-62UM7Q5N.js → chunk-ZNITDSWL.js} +1 -1
- package/dist/cli/chunks/{ci-CBNVLOOQ.js → ci-IU5HVUL5.js} +2 -2
- package/dist/cli/chunks/{ci-output-I4HY2FYJ.js → ci-output-CLI4A43F.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-5VRBKGWL.js → circuit-breaker-ZR5OFMW7.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-XPJPKHIO.js → claude-flow-setup-UBMA6ZHJ.js} +2 -2
- package/dist/cli/chunks/client-KKCFGD7R.js +2 -0
- package/dist/cli/chunks/{cline-installer-OFRDUUWZ.js → cline-installer-EWYELOBI.js} +2 -2
- package/dist/cli/chunks/{code-QIZQVB3E.js → code-YSPF4MXN.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-LMUUWEX4.js → code-index-extractor-WW5OKSTN.js} +2 -2
- package/dist/cli/chunks/{codex-installer-N2MKIZ2S.js → codex-installer-GLADK5PY.js} +2 -2
- package/dist/cli/chunks/{completions-Y36S3C5J.js → completions-2KTWZ3AK.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-73YS3WUD.js → complexity-analyzer-KMX4OWKB.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-SAOTP6J3.js → continuedev-installer-4FHU4OEJ.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-A4HXF6HE.js → copilot-installer-AKR4WE7B.js} +2 -2
- package/dist/cli/chunks/core-handlers-KRSSJEO5.js +2 -0
- package/dist/cli/chunks/{cost-tracker-P26XUVZS.js → cost-tracker-BUJ6WEWY.js} +2 -2
- package/dist/cli/chunks/{coverage-HVNHSMVJ.js → coverage-OB6HVQS4.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-27QGWU27.js +2 -0
- package/dist/cli/chunks/{cursor-installer-46BQFTYZ.js → cursor-installer-3AOE4O3Q.js} +2 -2
- package/dist/cli/chunks/{daemon-Y54O3FLT.js → daemon-4RAL5URG.js} +3 -3
- package/dist/cli/chunks/{daemon-YE7K2AZF.js → daemon-JGSPLYGO.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-ETA7YY52.js → dag-attention-scheduler-DSBTHIMH.js} +2 -2
- package/dist/cli/chunks/{detect-5WLQ2J3E.js → detect-6CVW2VUQ.js} +2 -2
- package/dist/cli/chunks/{dist-node-45WW6I7J.js → dist-node-EWPKBTYA.js} +2 -2
- package/dist/cli/chunks/{domain-handler-J7DQV74M.js → domain-handler-HLVIJU25.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-GD2EGQVR.js → domain-transfer-7Y3BR3YU.js} +2 -2
- package/dist/cli/chunks/dream-M6K47Q4H.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-JELNEA2D.js → embed-and-insert-pattern-ZMJ3263X.js} +2 -2
- package/dist/cli/chunks/{eval-A4PA5G2U.js → eval-73XW2WJD.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-MLHTYWTA.js → experience-capture-middleware-OGJ3JOSQ.js} +3 -3
- package/dist/cli/chunks/{fast-paths-QYDTITRV.js → fast-paths-5XCY3Y6U.js} +2 -2
- package/dist/cli/chunks/{feature-flags-H4MSY26Z.js → feature-flags-R5V2FRJR.js} +2 -2
- package/dist/cli/chunks/{feature-flags-MQYYRHIK.js → feature-flags-VULQI6KY.js} +2 -2
- package/dist/cli/chunks/{file-discovery-RMFVJNGL.js → file-discovery-HW33C3HC.js} +2 -2
- package/dist/cli/chunks/{fleet-7KZQOTAC.js → fleet-NH3XR5OY.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-NMZFTGVH.js → gnn-wrapper-L3XMLPTG.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-7BQDK7MG.js → heartbeat-handler-TIQFBT4D.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-URXBF5RW.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-WWAGM6HK.js +2 -0
- package/dist/cli/chunks/hnsw-index-UFV2HSZE.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-TPPGBPKF.js → hnsw-legacy-bridge-YL2SUIPA.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-2KR4LQRU.js → hnswlib-node-62RTSHAY.js} +2 -2
- package/dist/cli/chunks/{hooks-CYZIUYSH.js → hooks-UR2ZF54G.js} +10 -10
- package/dist/cli/chunks/hybrid-router-3U6Q6OTL.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-WC6DMTYQ.js → hypergraph-engine-NX45AOPY.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-GTGA3TXJ.js → hypergraph-handler-LUM4YI4K.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-EUEX6ZRO.js +2 -0
- package/dist/cli/chunks/{init-handler-N3Z72JNI.js → init-handler-YTKKNTVV.js} +6 -6
- package/dist/cli/chunks/init-wizard-POKY2LRY.js +2 -0
- package/dist/cli/chunks/kernel-HPAONLZY.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-FUX4V6II.js → kilocode-installer-ZW7DVH7T.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-ZSNZT7ZR.js → kiro-installer-IA7INW4N.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-2WCUFG63.js +2 -0
- package/dist/cli/chunks/{learning-UQY64COU.js → learning-4AZ5PGTT.js} +3 -3
- package/dist/cli/chunks/{llm-router-CMHGGX6N.js → llm-router-WQ4E3AOP.js} +4 -4
- package/dist/cli/chunks/llm-router-service-D5VMG6SD.js +2 -0
- package/dist/cli/chunks/{load-E6WH4QN2.js → load-4FAH7CZO.js} +2 -2
- package/dist/cli/chunks/load-test-DHG26REU.js +2 -0
- package/dist/cli/chunks/{mcp-UM5VTW6N.js → mcp-KLLHI6DG.js} +2 -2
- package/dist/cli/chunks/{memory-7Q3XDUE5.js → memory-Q5HLIUC6.js} +5 -5
- package/dist/cli/chunks/memory-backend-GLWQ4DAL.js +2 -0
- package/dist/cli/chunks/memory-handlers-P72I4VV4.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-LZENWVRR.js → multi-model-executor-ABI73AFV.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-O2JAIPLF.js → opencode-installer-KRPQ6JOJ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-DKZWXDRI.js → orchestrator-SUPEONRG.js} +18 -18
- package/dist/cli/chunks/pattern-null-store-Y2YFTE3V.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-CLUL4M55.js → pattern-usage-recorder-R4GKK6RZ.js} +2 -2
- package/dist/cli/chunks/{pipeline-2VDLTR5J.js → pipeline-LCUETNGD.js} +2 -2
- package/dist/cli/chunks/{platform-4N4Q5XYX.js → platform-WJDIB4X3.js} +2 -2
- package/dist/cli/chunks/{plugin-GY5AU5CS.js → plugin-2X5NY2RF.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-TQ4DKDZS.js → prime-radiant-advanced-wasm-3T665QC6.js} +2 -2
- package/dist/cli/chunks/protocol-executor-HNT67NN5.js +2 -0
- package/dist/cli/chunks/{protocol-handler-T3LZ3WRG.js → protocol-handler-JTXRF7GU.js} +2 -2
- package/dist/cli/chunks/{prove-OV7S5J4W.js → prove-BFPWWPOC.js} +2 -2
- package/dist/cli/chunks/provider-manager-5YGPZIEZ.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-Z5UGOA3F.js +2 -0
- package/dist/cli/chunks/{quality-AXD4NLQA.js → quality-F7UZU4RN.js} +2 -2
- package/dist/cli/chunks/quality-gate-R5L4UZIX.js +7 -0
- package/dist/cli/chunks/queen-coordinator-P5LU5NWI.js +2 -0
- package/dist/cli/chunks/{real-embeddings-2PUCC7FG.js → real-embeddings-LZD6HTQF.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-WJ5ARGLW.js → roocode-installer-6TTG7VSH.js} +2 -2
- package/dist/cli/chunks/router-CRGHUAVR.js +2 -0
- package/dist/cli/chunks/routing-feedback-BVX5ZBCF.js +2 -0
- package/dist/cli/chunks/{routing-handler-CU6657SZ.js → routing-handler-SW442GK7.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-IIF6VSFW.js → ruvector-commands-CLFGKXMW.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-YMQI7XO2.js → rvf-dual-writer-EVPPXXXS.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-HDE3PR2W.js → rvf-migration-adapter-NOHDIRIP.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-MQV5OA7K.js → rvf-migration-coordinator-BYJ3M7WZ.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-FZJSQOJM.js +2 -0
- package/dist/cli/chunks/safe-db-USYNEOC6.js +2 -0
- package/dist/cli/chunks/schedule-KCRCQ3PS.js +2 -0
- package/dist/cli/chunks/scheduler-CX3UHI4U.js +2 -0
- package/dist/cli/chunks/{security-UM3IGDSM.js → security-IXDKBPSG.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-I3SOJ6M4.js → shared-rvf-adapter-VCOK3OVD.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-KQGC2UO7.js → shared-rvf-dual-writer-FFKBKYNL.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-K23C4TFH.js +2 -0
- package/dist/cli/chunks/{status-handler-OX4CJZME.js → status-handler-M5W64S5U.js} +2 -2
- package/dist/cli/chunks/{structural-health-PYUMVBXJ.js → structural-health-55X6BTLT.js} +2 -2
- package/dist/cli/chunks/{sync-VALFNTA6.js → sync-BUGDXW3Y.js} +2 -2
- package/dist/cli/chunks/{sync-2TED3YTY.js → sync-NUG67HGK.js} +2 -2
- package/dist/cli/chunks/{task-handler-VPGAJVPC.js → task-handler-T6ZKXV4S.js} +2 -2
- package/dist/cli/chunks/{task-handlers-IB4UAMU6.js → task-handlers-H63TB2UI.js} +3 -3
- package/dist/cli/chunks/{test-OMRJOZB6.js → test-VEK76SBT.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-ZL3YFPBU.js → test-scheduling-QZM6PNZH.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-DNWZI7SH.js → token-bootstrap-W5IAMJW4.js} +2 -2
- package/dist/cli/chunks/{token-usage-IYO7RGFF.js → token-usage-OBY6UEUR.js} +2 -2
- package/dist/cli/chunks/{transformers-53ALC34T.js → transformers-EFNY2MRX.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-WUKJ2I2Q.js → tree-sitter-wasm-parser-EU2S5NVM.js} +2 -2
- package/dist/cli/chunks/{types-47FTEPMV.js → types-3DYRKX23.js} +2 -2
- package/dist/cli/chunks/unified-memory-NCDBQLLF.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-T7NSGQ2H.js +2 -0
- package/dist/cli/chunks/unified-persistence-XUAYDCMM.js +2 -0
- package/dist/cli/chunks/{upgrade-QPLMJA5Z.js → upgrade-H5V53FRF.js} +2 -2
- package/dist/cli/chunks/{validate-3GVKZOVF.js → validate-IL22VB5I.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XCRTLVM6.js → validate-swarm-WZKECK3W.js} +2 -2
- package/dist/cli/chunks/{vibium-CH4VPKVZ.js → vibium-KKM23OTQ.js} +2 -2
- package/dist/cli/chunks/visual-security-3TUC4GPP.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-JDBNAZTV.js → web-tree-sitter-NJM5YBOY.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-3MNPVJBP.js → windsurf-installer-SLP43TVT.js} +2 -2
- package/dist/cli/chunks/witness-chain-QLOKUZXC.js +2 -0
- package/dist/cli/chunks/{witness-chain-HR5UBV5J.js → witness-chain-XBEPT4XD.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-G5SQTIBZ.js → witness-key-manager-DAAMNYOW.js} +2 -2
- package/dist/cli/chunks/{workflow-43EMD5FY.js → workflow-SZOOU6D3.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-6JAYTZ7L.js +2 -0
- package/dist/cli/chunks/{wrappers-3N7AYNM3.js → wrappers-I2CBKWGF.js} +2 -2
- package/dist/cli/commands/quality-gate.d.ts +24 -0
- package/dist/cli/commands/quality-gate.js +135 -0
- package/dist/cli/index.js +5 -0
- package/dist/coordination/mincut/dream-integration.d.ts +11 -0
- package/dist/coordination/mincut/dream-integration.js +39 -12
- package/dist/init/init-wizard-hooks.js +11 -25
- package/dist/init/phases/07-hooks.js +15 -25
- package/dist/init/settings-merge.d.ts +44 -0
- package/dist/init/settings-merge.js +119 -4
- package/dist/integrations/ruvector/feature-flags.js +7 -0
- package/dist/learning/pattern-lifecycle.d.ts +16 -0
- package/dist/learning/pattern-lifecycle.js +77 -1
- package/dist/learning/provenance-tier.d.ts +52 -0
- package/dist/learning/provenance-tier.js +64 -0
- package/dist/learning/qe-flywheel/corpus-scorer.d.ts +55 -0
- package/dist/learning/qe-flywheel/corpus-scorer.js +293 -0
- package/dist/learning/qe-flywheel/coupled-anchor.d.ts +91 -0
- package/dist/learning/qe-flywheel/coupled-anchor.js +181 -0
- package/dist/learning/qe-flywheel/generation.d.ts +121 -0
- package/dist/learning/qe-flywheel/generation.js +167 -0
- package/dist/learning/qe-flywheel/policy.d.ts +37 -0
- package/dist/learning/qe-flywheel/policy.js +66 -0
- package/dist/learning/qe-flywheel/receipt-store.d.ts +31 -0
- package/dist/learning/qe-flywheel/receipt-store.js +89 -0
- package/dist/learning/qe-flywheel/receipt.d.ts +62 -0
- package/dist/learning/qe-flywheel/receipt.js +97 -0
- package/dist/mcp/bundle.js +396 -390
- package/dist/mcp/tools/quality-assessment/gate.d.ts +38 -0
- package/dist/mcp/tools/quality-assessment/gate.js +86 -0
- package/dist/mcp/tools/registry.d.ts +1 -0
- package/dist/mcp/tools/registry.js +3 -0
- package/dist/shared/safe-db.js +23 -4
- package/dist/validation/anchor-set.d.ts +74 -0
- package/dist/validation/anchor-set.js +78 -0
- package/dist/validation/frontier-judge.d.ts +99 -0
- package/dist/validation/frontier-judge.js +234 -0
- package/dist/validation/gate-reexecute.d.ts +165 -0
- package/dist/validation/gate-reexecute.js +255 -0
- package/dist/validation/quality-gate-runner.d.ts +49 -0
- package/dist/validation/quality-gate-runner.js +62 -0
- package/dist/validation/quality-verdict.d.ts +94 -0
- package/dist/validation/quality-verdict.js +120 -0
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-KNM5R47J.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +0 -2
- package/dist/cli/chunks/base-X4EXQ2AS.js +0 -2
- package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +0 -2
- package/dist/cli/chunks/chunk-FHTYEAQ3.js +0 -2
- package/dist/cli/chunks/chunk-MIU5RUBJ.js +0 -149
- package/dist/cli/chunks/chunk-SK754ZSH.js +0 -316
- package/dist/cli/chunks/chunk-V6NAB5UZ.js +0 -2
- package/dist/cli/chunks/chunk-YR2JKBZO.js +0 -2
- package/dist/cli/chunks/chunk-ZMPAM4DY.js +0 -2
- package/dist/cli/chunks/client-AHXNCOHK.js +0 -2
- package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +0 -2
- package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +0 -2
- package/dist/cli/chunks/dream-4K3BK4IG.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +0 -2
- package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +0 -2
- package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +0 -2
- package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +0 -2
- package/dist/cli/chunks/init-wizard-AIOA5KOY.js +0 -2
- package/dist/cli/chunks/kernel-SQALRU6Q.js +0 -2
- package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +0 -2
- package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +0 -2
- package/dist/cli/chunks/load-test-JEIFJKNN.js +0 -2
- package/dist/cli/chunks/memory-backend-NT7I37CP.js +0 -2
- package/dist/cli/chunks/memory-handlers-746D7NE7.js +0 -2
- package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +0 -2
- package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +0 -2
- package/dist/cli/chunks/provider-manager-OATJ7R3D.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +0 -2
- package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +0 -2
- package/dist/cli/chunks/router-XKQRT5JK.js +0 -2
- package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +0 -2
- package/dist/cli/chunks/safe-db-LCPUYMX4.js +0 -2
- package/dist/cli/chunks/schedule-HIQJCWXG.js +0 -2
- package/dist/cli/chunks/scheduler-QE5EJ5LE.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +0 -2
- package/dist/cli/chunks/unified-memory-CJLMC2I4.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +0 -2
- package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +0 -2
- package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +0 -2
- package/dist/cli/chunks/witness-chain-73QC33ED.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +0 -2
|
@@ -0,0 +1,153 @@
|
|
|
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.12.1");process.exit(0)}
|
|
2
|
+
import{a as S}from"./chunk-4KI72C2E.js";import{b as w}from"./chunk-GXMNCW2M.js";import{e as P}from"./chunk-3W2FZXFD.js";import{a as O}from"./chunk-FNMEVLSN.js";import{c as A}from"./chunk-NOCPO55P.js";import{b as h,d as U}from"./chunk-O65OPAZH.js";import{S as k,j as f}from"./chunk-USTUWUCE.js";U();var F=["oracle:test-exec","judge:llm","proxy:structural"],u="proxy:structural";function I(r){return r&&F.includes(r)?r:u}function p(r,e={}){switch(I(r)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as D}from"node:crypto";var M=r=>p(r.provenanceTier,{allowJudgeTier:r.allowJudgeTier})?r.candidateHeldOut>r.baselineHeldOut?w(r.candidateAnchorMean,r.baselineAnchorMean,r.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${r.candidateAnchorMean} < ${r.baselineAnchorMean} - ${r.anchorTol}`}:{promote:!1,reason:`held-out ${r.candidateHeldOut} did not beat baseline ${r.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${r.provenanceTier}' not allowed to promote`},Y=Object.freeze({"accept/v1":M});function E(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map(E).join(",")}]`;let e=r;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${E(e[n])}`).join(",")}}`}var H="aqe:promotion-path-rule:v1+sig",q=r=>p(r.provenanceTier,{allowJudgeTier:r.allowJudgeTier})?r.reward===void 0||r.rewardThreshold===void 0||!(r.reward>=r.rewardThreshold)?{promote:!1,reason:`reward ${r.reward} below threshold ${r.rewardThreshold}`}:r.occurrences===void 0||r.occurrenceThreshold===void 0||!(r.occurrences>=r.occurrenceThreshold)?{promote:!1,reason:`occurrences ${r.occurrences} below threshold ${r.occurrenceThreshold}`}:r.successRate===void 0||r.successRateThreshold===void 0||!(r.successRate>=r.successRateThreshold)?{promote:!1,reason:`success rate ${r.successRate} below threshold ${r.successRateThreshold}`}:r.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${r.provenanceTier}' not allowed to promote`},W=r=>p(r.provenanceTier,{allowJudgeTier:r.allowJudgeTier})?r.insightConfidence===void 0||r.insightConfidenceThreshold===void 0||!(r.insightConfidence>=r.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${r.insightConfidence} below threshold ${r.insightConfidenceThreshold}`}:r.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${r.provenanceTier}' not allowed to apply`},L=Object.freeze({"pattern-promote/v1":q,"dream-apply/v1":W});function T(r){return D("sha256").update(E(r)).digest("hex")}function _(r){if(!(r in L))throw new Error(`Unknown promotion-path rule version '${r}' \u2014 cannot fingerprint an unregistered rule.`);return D("sha256").update(H).update("\0").update(r).digest("hex")}function y(r,e){let t=L[r];if(!t)throw new Error(`Unknown promotion-path rule version '${r}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function C(r,e={}){let t=[],n=T(r.sealed)===r.sealedHash;n||t.push("sealIntact");let a=!1;try{let c=_(r.ruleVersion);a=r.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||r.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;n&&a&&(s=(y(r.ruleVersion,r.sealed).promote?"promote":"reject")===r.recordedVerdict),s||t.push("gateReExecutes");let i=t.length===0;return{valid:i,checks:{sealIntact:n,gateUnchanged:a,gateReExecutes:s},failures:t,reason:i?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}O();k();var d=A.create("pattern-lifecycle"),$={promotionRewardThreshold:.7,promotionMinOccurrences:P,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},x=5,j=.9,V=2;function Q(r,e){return e<x||!Number.isFinite(r)?0:Math.min(Math.max(r,0),1)}var b=class{constructor(e,t={}){this.db=e;this.config={...$,...t},this.asymmetricEngine=new S(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
|
|
3
|
+
SELECT deprecated_at FROM qe_patterns LIMIT 1
|
|
4
|
+
`).get()}catch(e){d.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
5
|
+
ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
|
|
6
|
+
`),console.log("[PatternLifecycle] Added deprecated_at column to qe_patterns")}try{this.db.prepare(`
|
|
7
|
+
SELECT consecutive_failures FROM qe_patterns LIMIT 1
|
|
8
|
+
`).get()}catch(e){d.debug("Adding missing consecutive_failures column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
9
|
+
ALTER TABLE qe_patterns ADD COLUMN consecutive_failures INTEGER DEFAULT 0
|
|
10
|
+
`),console.log("[PatternLifecycle] Added consecutive_failures column to qe_patterns")}try{this.db.prepare(`
|
|
11
|
+
SELECT promotion_date FROM qe_patterns LIMIT 1
|
|
12
|
+
`).get()}catch(e){d.debug("Adding missing promotion_date column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
13
|
+
ALTER TABLE qe_patterns ADD COLUMN promotion_date TEXT DEFAULT NULL
|
|
14
|
+
`),console.log("[PatternLifecycle] Added promotion_date column to qe_patterns")}try{this.db.prepare(`
|
|
15
|
+
SELECT provenance_tier FROM qe_patterns LIMIT 1
|
|
16
|
+
`).get()}catch(e){d.debug("Adding missing provenance_tier column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
|
|
17
|
+
ALTER TABLE qe_patterns ADD COLUMN provenance_tier TEXT DEFAULT '${u}'
|
|
18
|
+
`),console.log(`[PatternLifecycle] Added provenance_tier column to qe_patterns (backfilled '${u}')`)}}getRecentExperiences(e={}){let t=e.minReward??this.config.promotionRewardThreshold,n=e.limit??100,a=e.sinceDays??7;if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return d.debug("captured_experiences table not found"),[];let i=new Date(Date.now()-a*864e5).toISOString().replace("T"," ").slice(0,19);return this.db.prepare(`
|
|
19
|
+
SELECT
|
|
20
|
+
domain as task_type,
|
|
21
|
+
COUNT(*) as count,
|
|
22
|
+
AVG(quality) as avg_reward,
|
|
23
|
+
MAX(quality) as max_reward,
|
|
24
|
+
MIN(quality) as min_reward,
|
|
25
|
+
SUM(CASE WHEN quality >= ? THEN 1 ELSE 0 END) as success_count,
|
|
26
|
+
GROUP_CONCAT(DISTINCT agent) as actions,
|
|
27
|
+
MAX(started_at) as latest_at
|
|
28
|
+
FROM captured_experiences
|
|
29
|
+
WHERE started_at >= ?
|
|
30
|
+
AND quality >= ?
|
|
31
|
+
AND agent != 'cli-hook'
|
|
32
|
+
GROUP BY domain
|
|
33
|
+
HAVING COUNT(*) >= ?
|
|
34
|
+
ORDER BY avg_reward DESC
|
|
35
|
+
LIMIT ?
|
|
36
|
+
`).all(t,i,t*.5,this.config.promotionMinOccurrences,n).map(o=>({taskType:o.task_type,domain:this.taskTypeToQEDomain(o.task_type),count:o.count,avgReward:o.avg_reward,maxReward:o.max_reward,minReward:o.min_reward,actions:o.actions?o.actions.split(",").filter(Boolean):[],successCount:o.success_count,latestAt:new Date(o.latest_at)}))}taskTypeToQEDomain(e){let t={generate:"test-generation","test-generation":"test-generation",test:"test-generation",analyze:"coverage-analysis",coverage:"coverage-analysis","coverage-analysis":"coverage-analysis",run:"test-execution",execute:"test-execution","test-execution":"test-execution",report:"quality-assessment",quality:"quality-assessment",assessment:"quality-assessment",security:"security-compliance",sast:"security-compliance",audit:"security-compliance",defect:"defect-intelligence",predict:"defect-intelligence",bug:"defect-intelligence",requirements:"requirements-validation",validation:"requirements-validation",code:"code-intelligence",complexity:"code-intelligence",contract:"contract-testing",api:"contract-testing",visual:"visual-accessibility",a11y:"visual-accessibility",accessibility:"visual-accessibility",chaos:"chaos-resilience",resilience:"chaos-resilience",flaky:"chaos-resilience",learning:"learning-optimization",optimize:"learning-optimization"},n=e.toLowerCase();for(let[a,s]of Object.entries(t))if(n.includes(a))return s;return null}taskTypeToPatternType(e){let t={generate:"test-template",test:"test-template",coverage:"coverage-strategy",analyze:"coverage-strategy",mock:"mock-pattern",stub:"mock-pattern",assert:"assertion-pattern",expect:"assertion-pattern",security:"assertion-pattern",contract:"api-contract",api:"api-contract",visual:"visual-baseline",screenshot:"visual-baseline",a11y:"a11y-check",accessibility:"a11y-check",perf:"perf-benchmark",load:"perf-benchmark",stress:"perf-benchmark",flaky:"flaky-fix",retry:"flaky-fix",refactor:"refactor-safe",error:"error-handling",exception:"error-handling"},n=e.toLowerCase();for(let[a,s]of Object.entries(t))if(n.includes(a))return s;return"test-template"}findPatternCandidates(e){let t=[];for(let n of e){let a=n.avgReward>=this.config.promotionRewardThreshold,s=n.count>=this.config.promotionMinOccurrences,i=n.successCount/n.count,c=i>=this.config.promotionMinSuccessRate;if(a&&s&&c){let o=n.domain||"code-intelligence",l=this.taskTypeToPatternType(n.taskType);if(this.findExistingPattern(n.taskType,o))continue;t.push({name:`${n.taskType}-success-pattern`,domain:o,patternType:l,confidence:Math.min(.95,n.avgReward*.9),sourceExperiences:n.count,avgReward:n.avgReward,successRate:i,actions:n.actions.slice(0,5),templateContent:this.generateTemplateContent(n)})}}return t}findExistingPattern(e,t){let n=this.db.prepare(`
|
|
37
|
+
SELECT * FROM qe_patterns
|
|
38
|
+
WHERE name LIKE ? AND qe_domain = ? AND deprecated_at IS NULL
|
|
39
|
+
LIMIT 1
|
|
40
|
+
`).get(`%${e}%`,t);return n?this.rowToPattern(n):null}generateTemplateContent(e){let t=e.actions.map((n,a)=>`${a+1}. ${n}`).join(`
|
|
41
|
+
`);return`Task Type: ${e.taskType}
|
|
42
|
+
Domain: ${e.domain||"general"}
|
|
43
|
+
Average Reward: ${e.avgReward.toFixed(3)}
|
|
44
|
+
Success Rate: ${(e.successCount/e.count*100).toFixed(1)}%
|
|
45
|
+
|
|
46
|
+
Typical Actions:
|
|
47
|
+
${t||"N/A"}
|
|
48
|
+
|
|
49
|
+
Pattern extracted from ${e.count} successful experiences.`}getProvenanceTier(e){try{return this.db.prepare("SELECT provenance_tier FROM qe_patterns WHERE id = ?").get(e)?.provenance_tier??u}catch{return u}}checkPromotion(e){let t=this.getPattern(e);if(!t)return{shouldPromote:!1,meetsRewardThreshold:!1,meetsOccurrenceThreshold:!1,meetsSuccessRateThreshold:!1,meetsActivityWindow:!1,currentReward:0,currentOccurrences:0,currentSuccessRate:0,provenanceTier:u,meetsProvenanceTier:!1};let n=t.qualityScore,a=n>=this.config.promotionRewardThreshold,s=t.usageCount>=this.config.promotionMinOccurrences,i=t.successRate>=this.config.promotionMinSuccessRate,c=this.getProvenanceTier(e),o=p(c,{allowJudgeTier:this.config.allowJudgeTierPromotion}),l=this.config.promotionActivityWindowDays*24*60*60*1e3,R=t.lastUsedAt?.getTime()??t.createdAt.getTime(),v=Date.now()-R<l;return{shouldPromote:t.tier==="short-term"&&o&&a&&s&&i&&v,meetsRewardThreshold:a,meetsOccurrenceThreshold:s,meetsSuccessRateThreshold:i,meetsActivityWindow:v,provenanceTier:c,meetsProvenanceTier:o,currentReward:n,currentOccurrences:t.usageCount,currentSuccessRate:t.successRate}}promotePattern(e){let t=this.checkPromotion(e);if(!t.shouldPromote)return!1;let n={provenanceTier:t.provenanceTier,allowJudgeTier:this.config.allowJudgeTierPromotion,reward:t.currentReward,rewardThreshold:this.config.promotionRewardThreshold,occurrences:t.currentOccurrences,occurrenceThreshold:this.config.promotionMinOccurrences,successRate:t.currentSuccessRate,successRateThreshold:this.config.promotionMinSuccessRate,withinActivityWindow:t.meetsActivityWindow},a=y("pattern-promote/v1",n),s={ruleVersion:"pattern-promote/v1",ruleFingerprint:_("pattern-promote/v1"),sealedHash:T(n),sealed:n,recordedVerdict:a.promote?"promote":"reject"},i=C(s);return!i.valid||!a.promote?(console.warn(`[PatternLifecycle] Refusing to promote ${e}: ${a.reason} (${i.reason})`),!1):(this.db.prepare(`
|
|
50
|
+
UPDATE qe_patterns
|
|
51
|
+
SET tier = 'long-term',
|
|
52
|
+
promotion_date = datetime('now'),
|
|
53
|
+
confidence = MIN(1.0, confidence + 0.1),
|
|
54
|
+
updated_at = datetime('now')
|
|
55
|
+
WHERE id = ?
|
|
56
|
+
`).run(e),console.log(`[PatternLifecycle] Promoted pattern ${e} to long-term`),!0)}promoteEligiblePatterns(){let e=this.db.prepare(`
|
|
57
|
+
SELECT id FROM qe_patterns
|
|
58
|
+
WHERE tier = 'short-term' AND deprecated_at IS NULL
|
|
59
|
+
`).all(),t=0;for(let{id:n}of e)this.promotePattern(n)&&t++;return{promoted:t,checked:e.length}}runPromotionSweep(){return this.promoteEligiblePatterns()}checkDeprecation(e){let t=this.getPattern(e);if(!t)return{shouldDeprecate:!1,reason:null};if(t.deprecated_at)return{shouldDeprecate:!1,reason:null};let n=t.consecutive_failures||0;if(n>=this.config.deprecationFailureThreshold)return{shouldDeprecate:!0,reason:"failures",consecutiveFailures:n};let a=t.lastUsedAt instanceof Date?t.lastUsedAt.getTime():new Date(t.lastUsedAt).getTime(),s=(Date.now()-a)/(1e3*60*60*24),i=Q(t.successRate,t.usageCount),c=this.config.staleDaysThreshold*(1+i*V);if(s>=c)return{shouldDeprecate:!0,reason:"stale",daysSinceLastUse:s};if(t.confidence<this.config.minActiveConfidence)return{shouldDeprecate:!0,reason:"low_confidence",currentConfidence:t.confidence};let o=t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),l=(Date.now()-o)/(1e3*60*60*24);return l>=this.config.maxAgeForActivePatterns&&t.usageCount<5?{shouldDeprecate:!0,reason:"age",ageInDays:l}:{shouldDeprecate:!1,reason:null}}deprecatePattern(e,t){let n=this.checkDeprecation(e);if(!n.shouldDeprecate&&!t)return!1;let a=t||n.reason||"manual";this.db.prepare(`
|
|
60
|
+
UPDATE qe_patterns
|
|
61
|
+
SET deprecated_at = datetime('now'),
|
|
62
|
+
updated_at = datetime('now')
|
|
63
|
+
WHERE id = ?
|
|
64
|
+
`).run(e);let s=this.getPattern(e);if(s){let i={deprecation_reason:a,deprecated_at:new Date().toISOString(),final_confidence:s.confidence,final_success_rate:s.successRate,total_usage:s.usageCount};this.db.prepare(`
|
|
65
|
+
UPDATE qe_patterns
|
|
66
|
+
SET context_json = json_patch(COALESCE(context_json, '{}'), ?)
|
|
67
|
+
WHERE id = ?
|
|
68
|
+
`).run(JSON.stringify({deprecation_metadata:i}),e)}return console.log(`[PatternLifecycle] Deprecated pattern ${e}: ${a}`),!0}deprecateStalePatterns(){let e=this.db.prepare(`
|
|
69
|
+
SELECT id FROM qe_patterns
|
|
70
|
+
WHERE deprecated_at IS NULL
|
|
71
|
+
`).all(),t=0;for(let{id:n}of e){let a=this.checkDeprecation(n);a.shouldDeprecate&&(this.deprecatePattern(n,a.reason||void 0),t++)}return{deprecated:t,checked:e.length}}applyConfidenceDecay(e=1){let t=this.config.confidenceDecayRate*e,n=Date.now()-e*24*60*60*1e3,a=this.db.prepare(`
|
|
72
|
+
UPDATE qe_patterns
|
|
73
|
+
SET confidence = MAX(?, confidence * (1 - ? * (1 - ? *
|
|
74
|
+
(CASE WHEN usage_count >= ?
|
|
75
|
+
THEN MIN(MAX(COALESCE(success_rate, 0.0), 0.0), 1.0)
|
|
76
|
+
ELSE 0.0 END)))),
|
|
77
|
+
updated_at = datetime('now')
|
|
78
|
+
WHERE deprecated_at IS NULL
|
|
79
|
+
AND (last_used_at IS NULL OR datetime(last_used_at) < datetime(?, 'unixepoch'))
|
|
80
|
+
`).run(this.config.minActiveConfidence,t,j,x,n/1e3);return{updated:a.changes,decayed:a.changes}}recordUsage(e,t){t?this.db.prepare(`
|
|
81
|
+
UPDATE qe_patterns
|
|
82
|
+
SET usage_count = usage_count + 1,
|
|
83
|
+
successful_uses = successful_uses + 1,
|
|
84
|
+
consecutive_failures = 0,
|
|
85
|
+
confidence = MIN(1.0, confidence + 0.02),
|
|
86
|
+
success_rate = CAST(successful_uses + 1 AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
87
|
+
last_used_at = datetime('now'),
|
|
88
|
+
updated_at = datetime('now')
|
|
89
|
+
WHERE id = ?
|
|
90
|
+
`).run(e):this.db.prepare(`
|
|
91
|
+
UPDATE qe_patterns
|
|
92
|
+
SET usage_count = usage_count + 1,
|
|
93
|
+
consecutive_failures = consecutive_failures + 1,
|
|
94
|
+
confidence = MAX(0.1, confidence - 0.05),
|
|
95
|
+
success_rate = CAST(successful_uses AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
96
|
+
last_used_at = datetime('now'),
|
|
97
|
+
updated_at = datetime('now')
|
|
98
|
+
WHERE id = ?
|
|
99
|
+
`).run(e),this.db.prepare(`
|
|
100
|
+
UPDATE qe_patterns
|
|
101
|
+
SET quality_score = confidence * 0.3 + (MIN(usage_count, 100) / 100.0) * 0.2 + success_rate * 0.5
|
|
102
|
+
WHERE id = ?
|
|
103
|
+
`).run(e)}recordAsymmetricOutcome(e,t,n){let a=this.getPattern(e);if(!a)return;let s=a.confidence,i=this.asymmetricEngine.computeConfidenceUpdate(s,t?"success":"failure",n);this.db.prepare(`
|
|
104
|
+
UPDATE qe_patterns
|
|
105
|
+
SET confidence = ?,
|
|
106
|
+
usage_count = usage_count + 1,
|
|
107
|
+
successful_uses = CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END,
|
|
108
|
+
consecutive_failures = CASE WHEN ? THEN 0 ELSE consecutive_failures + 1 END,
|
|
109
|
+
success_rate = CAST(CASE WHEN ? THEN successful_uses + 1 ELSE successful_uses END AS REAL) / CAST(usage_count + 1 AS REAL),
|
|
110
|
+
last_used_at = datetime('now'),
|
|
111
|
+
updated_at = datetime('now')
|
|
112
|
+
WHERE id = ?
|
|
113
|
+
`).run(i,t?1:0,t?1:0,t?1:0,e),this.asymmetricEngine.shouldQuarantine(i,n).shouldQuarantine&&this.quarantinePattern(e)}quarantinePattern(e){if(this.db.prepare(`
|
|
114
|
+
UPDATE qe_patterns
|
|
115
|
+
SET deprecated_at = datetime('now'),
|
|
116
|
+
updated_at = datetime('now')
|
|
117
|
+
WHERE id = ? AND deprecated_at IS NULL
|
|
118
|
+
`).run(e).changes>0){console.log(`[PatternLifecycle] Quarantined pattern ${e} (asymmetric confidence drop)`);try{this._witnessChain?.append("PATTERN_QUARANTINE",{patternId:e},"pattern-lifecycle")}catch{}return!0}return!1}checkRehabilitation(e,t){return this.asymmetricEngine.checkRehabilitation(t).canRehabilitate}rehabilitatePattern(e){return this.db.prepare(`
|
|
119
|
+
UPDATE qe_patterns
|
|
120
|
+
SET deprecated_at = NULL,
|
|
121
|
+
consecutive_failures = 0,
|
|
122
|
+
confidence = 0.5,
|
|
123
|
+
updated_at = datetime('now')
|
|
124
|
+
WHERE id = ?
|
|
125
|
+
`).run(e).changes>0?(console.log(`[PatternLifecycle] Rehabilitated pattern ${e} (10+ consecutive successes)`),!0):!1}getAsymmetricEngine(){return this.asymmetricEngine}compressPatternEmbedding(e){if(!f()||!this._compressionService)return null;let t=this.getPattern(e);if(!t||!t.embedding||t.embedding.length===0)return null;let n=t.lastUsedAt??t.createdAt,a=this._compressionService.classifyTier(n),s=new Float32Array(t.embedding),i=this._compressionService.compress(s,a);return d.debug("Compressed pattern embedding",{patternId:e,tier:a,ratio:(i.originalByteSize/i.compressedByteSize).toFixed(1)}),i}decompressPatternEmbedding(e){return this._compressionService?this._compressionService.decompress(e):null}compressAllPatternEmbeddings(){if(!f()||!this._compressionService)return 0;let e=this.db.prepare(`
|
|
126
|
+
SELECT id FROM qe_patterns
|
|
127
|
+
WHERE deprecated_at IS NULL
|
|
128
|
+
`).all(),t=0;for(let{id:n}of e)this.compressPatternEmbedding(n)&&t++;return d.info("Bulk pattern embedding compression complete",{total:e.length,compressed:t}),t}getStats(){let e=this.db.prepare(`
|
|
129
|
+
SELECT
|
|
130
|
+
COUNT(*) as total,
|
|
131
|
+
SUM(CASE WHEN deprecated_at IS NULL THEN 1 ELSE 0 END) as active,
|
|
132
|
+
SUM(CASE WHEN deprecated_at IS NOT NULL THEN 1 ELSE 0 END) as deprecated,
|
|
133
|
+
SUM(CASE WHEN tier = 'long-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as promoted,
|
|
134
|
+
SUM(CASE WHEN tier = 'short-term' AND deprecated_at IS NULL THEN 1 ELSE 0 END) as short_term,
|
|
135
|
+
SUM(CASE WHEN tier = 'long-term' THEN 1 ELSE 0 END) as long_term,
|
|
136
|
+
AVG(CASE WHEN deprecated_at IS NULL THEN confidence ELSE NULL END) as avg_confidence,
|
|
137
|
+
AVG(CASE WHEN deprecated_at IS NULL THEN success_rate ELSE NULL END) as avg_success_rate
|
|
138
|
+
FROM qe_patterns
|
|
139
|
+
`).get(),t=this.db.prepare(`
|
|
140
|
+
SELECT COUNT(*) as count
|
|
141
|
+
FROM qe_patterns
|
|
142
|
+
WHERE deprecated_at IS NULL
|
|
143
|
+
AND (
|
|
144
|
+
consecutive_failures >= ?
|
|
145
|
+
OR confidence < ?
|
|
146
|
+
OR (julianday('now') - julianday(COALESCE(last_used_at, created_at))) >= ?
|
|
147
|
+
)
|
|
148
|
+
`).get(this.config.deprecationFailureThreshold-1,this.config.minActiveConfidence+.1,this.config.staleDaysThreshold-7);return{totalPatterns:e.total||0,activePatterns:e.active||0,deprecatedPatterns:e.deprecated||0,promotedPatterns:e.promoted||0,shortTermPatterns:e.short_term||0,longTermPatterns:e.long_term||0,avgConfidence:e.avg_confidence||0,avgSuccessRate:e.avg_success_rate||0,patternsNearDeprecation:t.count||0}}getPattern(e){let t=this.db.prepare(`
|
|
149
|
+
SELECT * FROM qe_patterns WHERE id = ?
|
|
150
|
+
`).get(e);return t?this.rowToPattern(t):null}rowToPattern(e){return{id:e.id,patternType:e.pattern_type,qeDomain:e.qe_domain,domain:e.domain,name:e.name,description:e.description||"",confidence:e.confidence,usageCount:e.usage_count,successRate:e.success_rate,qualityScore:e.quality_score,tier:e.tier,template:h(e.template_json||"{}"),context:h(e.context_json||"{}"),createdAt:new Date(e.created_at),lastUsedAt:e.last_used_at?new Date(e.last_used_at):new Date(e.created_at),successfulUses:e.successful_uses,reusable:e.reusable===1,reuseCount:e.reuse_count||0,averageTokenSavings:e.average_token_savings||0,deprecated_at:e.deprecated_at??null,consecutive_failures:e.consecutive_failures??0}}};function ie(r,e){return new b(r,e)}import*as m from"fs";import*as g from"path";var J={"pattern-learned":"\u{1F9E0}","pattern-promoted":"\u2B06\uFE0F","pattern-quarantined":"\u{1F512}","experience-captured":"\u{1F4F8}","search-performed":"\u{1F50D}","reward-assigned":"\u{1F3AF}"},N=class{config;buffer=[];flushTimer=null;constructor(e){this.config={logDir:e?.logDir??g.join(process.cwd(),".agentic-qe","logs"),enabled:e?.enabled??!0,maxEntriesPerDay:e?.maxEntriesPerDay??500}}log(e){this.config.enabled&&(this.buffer.push(e),this.buffer.length>=10&&this.flush())}flush(){if(this.buffer.length===0)return;let e=new Date().toISOString().split("T")[0],t=g.join(this.config.logDir,`${e}.md`);try{m.mkdirSync(this.config.logDir,{recursive:!0});let n=this.buffer.splice(0,this.buffer.length),a=[];m.existsSync(t)||(a.push(`# AQE Daily Log \u2014 ${e}
|
|
151
|
+
`),a.push("| Time | Event | Summary |"),a.push("|------|-------|---------|"));for(let s of n){let i=s.timestamp.toISOString().split("T")[1]?.slice(0,8)??"00:00:00",c=J[s.type]??"\u{1F4DD}",o=s.summary.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\n/g," ");a.push(`| ${i} | ${c} ${s.type} | ${o} |`)}m.appendFileSync(t,a.join(`
|
|
152
|
+
`)+`
|
|
153
|
+
`)}catch(n){console.debug("[DailyLog] Write failed:",n)}}getTodayLogPath(){let e=new Date().toISOString().split("T")[0];return g.join(this.config.logDir,`${e}.md`)}dispose(){this.flush(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}};export{ie as a,N as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{b as pe}from"./chunk-D45QLJEL.js";import{a as dt}from"./chunk-O7J54OHN.js";import{a as mt,b as gt}from"./chunk-I3ANRYQ6.js";import{j as I}from"./chunk-B2VBDMDI.js";import{a as lt,b as ut}from"./chunk-VN2HHBZN.js";import{a as nt}from"./chunk-VMWRMINE.js";import{a as at,b as ot,c as ct}from"./chunk-PW72M2FE.js";import{b as st}from"./chunk-UBI2EOS3.js";import{a as ge}from"./chunk-MCHEUSY4.js";import{i as w,m as me}from"./chunk-NCSXLMDL.js";import{a as an}from"./chunk-ZMPAM4DY.js";import{c as it}from"./chunk-Y25PO65W.js";import{b as M,d as rt}from"./chunk-CKOF27L7.js";import{a as v,b,c as y}from"./chunk-5WMU7XCF.js";import{a as h,b as tt,c as k}from"./chunk-RKXZLTWR.js";import{i as T}from"./chunk-K4I7UIU5.js";import{R as on,S as cn}from"./chunk-GODAWJMZ.js";import{c as z,e as sn,g as et}from"./chunk-C4EZNOWK.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};sn(vt,{NeuralTinyDancerRouter:()=>q,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new q(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,q,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},q=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=Cn[s],l=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),f=1-m[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let s=.55,o=.35,l=Math.min(r/25,1),c=s+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},G=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new G(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.getDatabase().prepare(`
|
|
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.12.1");process.exit(0)}
|
|
2
|
+
import{b as pe}from"./chunk-HDI3FD4G.js";import{a as dt}from"./chunk-SHKOPOPD.js";import{a as mt,b as gt}from"./chunk-BBNQDHGF.js";import{j as I}from"./chunk-HHMTQQUE.js";import{a as lt,b as ut}from"./chunk-XYV6YUWS.js";import{a as nt}from"./chunk-CP4GSICY.js";import{a as at,b as ot,c as ct}from"./chunk-RIASOMB2.js";import{b as st}from"./chunk-42PYEEYQ.js";import{a as ge}from"./chunk-3W2FZXFD.js";import{i as w,m as me}from"./chunk-XDRAU3W6.js";import{a as an}from"./chunk-FNMEVLSN.js";import{c as it}from"./chunk-NOCPO55P.js";import{b as M,d as rt}from"./chunk-O65OPAZH.js";import{a as v,b,c as y}from"./chunk-4LKQZW2H.js";import{a as h,b as tt,c as k}from"./chunk-UBPJQKYS.js";import{i as T}from"./chunk-75AVUS5U.js";import{R as on,S as cn}from"./chunk-USTUWUCE.js";import{c as z,e as sn,g as et}from"./chunk-U5ITD7ZD.js";function ft(a){let e=[],t=0;if(a.fileCount!==void 0&&(a.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${a.fileCount} files (>20)`})):a.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${a.fileCount} files (>10)`})):a.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${a.fileCount} files (>5)`}))),a.domain&&(dn.includes(a.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${a.domain}' requires complex reasoning`})):mn.includes(a.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${a.domain}' has moderate complexity`}))),a.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),a.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):a.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),a.requiredCapabilities){let r=a.requiredCapabilities.filter(s=>gn.includes(s)).length;if(r>0){let s=Math.min(20,r*10);t+=s,e.push({name:"complex-capabilities",weight:s,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}a.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),a.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),a.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),a.estimatedLinesAffected!==void 0&&(a.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${a.estimatedLinesAffected} lines affected (>500)`})):a.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${a.estimatedLinesAffected} lines affected (>200)`}))),(a.type==="security-scan"||a.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let s=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(s,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let s=0;s<4;s++)r+=e[s]*this.weightsInputHidden[s*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let s=0;s<32;s++)r+=t[s]*this.weightsHiddenOutput[s*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let s=0;s<e.length;s++)n[s]=Math.exp(e[s]-t),i+=n[s];let r=[];for(let s=0;s<e.length;s++)r.push(n[s]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let s=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-s[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};sn(vt,{NeuralTinyDancerRouter:()=>q,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(a){return new q(a)}var hn,fn,yn,Tn,vn,Cn,bn,kn,q,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},q=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let s=this.argmax(r),o=Cn[s],l=r[s];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,s=(i+r)/4,o=Math.min(1,s/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,s=0){this.ruleRouter.recordOutcome(e,t,n,i,r,s);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),p=this.argmax(m),f=1-m[u];this.calibrationScores.push(f),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),s=Math.ceil(.9*r.length)-1,o=r[Math.min(s,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let s=[];return s.push(`[Neural] Routing to ${e.toUpperCase()}`),s.push(`with ${(t*100).toFixed(0)}% neural confidence.`),s.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),s.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),s.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&s.push(`Rule-based would choose ${i.model.toUpperCase()}.`),s.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),s.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),s.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(a){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(a)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(a)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,s=this.isSecurityTask(e),o=s&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||s&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,s,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let s=.55,o=.35,l=Math.min(r/25,1),c=s+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(s=>n.includes(s)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(s=>r.includes(s))}buildReasoning(e,t,n,i,r){let s=[];if(s.push(`Routing to ${e.recommendedModel.toUpperCase()}`),s.push(`(complexity: ${e.complexity}, score: ${e.score})`),s.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");s.push(`Key factors: ${o}.`)}return n&&s.push("Security-sensitive task detected."),i&&s.push("Multi-model verification recommended due to uncertainty."),r&&s.push("Human review flagged due to high uncertainty or criticality."),s.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,s=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:s,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},G=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",s=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${s}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(a){return new G(a)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=T();return this.memory.getDatabase().prepare(`
|
|
3
3
|
INSERT INTO mincut_snapshots (
|
|
4
4
|
id, timestamp, vertex_count, edge_count, total_weight,
|
|
5
5
|
is_connected, component_count, vertices_json, edges_json
|
|
@@ -177,4 +177,4 @@ import{b as pe}from"./chunk-D45QLJEL.js";import{a as dt}from"./chunk-O7J54OHN.js
|
|
|
177
177
|
`;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
|
|
178
178
|
`;for(let r of i)t+=`- ${r}
|
|
179
179
|
`;t+=`
|
|
180
|
-
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ge=null;function qt(a){return Ge||(Ge=new qe(a)),Ge}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=qt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&<(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-CJLMC2I4.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map,t=0;for(let l of v){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,s=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:s,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
|
|
180
|
+
`}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,s]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(s))?s:Number(s),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ge=null;function qt(a){return Ge||(Ge=new qe(a)),Ge}function jt(a,e){let t=[];for(let s of e){let o=a.router.subscribeToDoamin(s,async l=>{await ai(a,l)});t.push(o)}let n=a.router.subscribeToEventType("TaskCompleted",async s=>{await oi(a,s)});t.push(n);let i=a.router.subscribeToEventType("TaskFailed",async s=>{await ci(a,s)});t.push(i);let r=a.router.subscribeToEventType("AgentStatusChanged",async s=>{await li(a,s)});return t.push(r),t}async function ai(a,e){a.domainLastActivity.set(e.source,new Date),await a.processQueue()}async function oi(a,e){let{taskId:t,result:n}=e.payload,i=a.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;a.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),a.tasksCompleted++,a.taskDurations.push(r),a.auditLogger.logComplete(t,i.assignedAgents[0]);try{let s=qt(),o=i.assignedAgents[0];o&&await s.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(s){console.warn("[QueenCoordinator] Cross-phase hook error:",s)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(s){console.warn("[QueenCoordinator] Governance tracking error:",s)}if(a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),a.traceCollector){let s=a.taskTraceContexts.get(t);s&&(a.traceCollector.completeSpan(s.spanId),a.taskTraceContexts.delete(t))}if(a.taskCompletedHook)try{let s=typeof n=="object"&&n!==null?n:null;if(s===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(s,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:s,metrics:o,duration:r,timestamp:Date.now()};a.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(s){console.warn("[QueenCoordinator] Pattern training setup error:",s)}}await a.processQueue()}async function ci(a,e){let{taskId:t,error:n}=e.payload,i=a.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1)),a.domainBreakerRegistry&&i.assignedDomain&&a.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),a.traceCollector){let r=a.taskTraceContexts.get(t);r&&(a.traceCollector.failSpan(r.spanId,n||"Task failed"),a.taskTraceContexts.delete(t))}if(i.retryCount<a.config.taskRetryLimit){a.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};a.tasks.set(t,r),a.enqueueTask(i.task)}else{a.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),a.tasksFailed++,a.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(a.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",s=a.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);a.hypothesisManager.addHypothesis(s.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),a.hypothesisManager.addHypothesis(s.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${s.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await a.processQueue()}async function li(a,e){let{agentId:t,status:n,domain:i}=e.payload;a.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await a.processQueue()}function ui(a,e){if("metrics"in a&&typeof a.metrics=="object"&&a.metrics!==null){let t=a.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in a||"testsFailed"in a?{testsPassed:typeof a.testsPassed=="number"?a.testsPassed:void 0,testsFailed:typeof a.testsFailed=="number"?a.testsFailed:void 0,coverageChange:typeof a.coverageChange=="number"?a.coverageChange:void 0,securityIssues:typeof a.securityIssues=="number"?a.securityIssues:void 0,performanceMs:typeof a.performanceMs=="number"?a.performanceMs:void 0,linesChanged:typeof a.linesChanged=="number"?a.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(a).join(", ")})`),null)}function Wt(a,e,t){let n=a.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,s=n.filter(l=>l.status==="failed").length,o;return s>0&&s>=n.length/2?o="unhealthy":s>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:s},lastActivity:t,errors:[]}}var di=ut();function Vt(a,e,t){let n=a.get(t.priority);n&<(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(a,e,t){let n=a.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let s=r.findIndex(o=>o.id===t.id);s!==-1&&r.splice(s,1)}}}function je(a,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=a.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(a){if(!(a.runningTaskCounter>=a.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=a.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(a.taskQueue,a.domainQueues,n),a.runningTaskCounter++;try{await Ve(a,n)}catch(i){throw a.runningTaskCounter--,i}if(a.runningTaskCounter>=a.config.maxConcurrentTasks)return}}}function Kt(a,e){let t=Array.from(a.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(a,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return y(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let s=a.getDomainLoad(r);a.getDomainHealth(r)?.status!=="unhealthy"&&s<i&&(i=s,n=r)}return n?Ke(a,e,n):y(new Error("No healthy domain available for task"))}async function Ke(a,e,t){let n;if(a.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await a.tinyDancerRouter.route(u),a.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(a.domainBreakerRegistry&&!a.domainBreakerRegistry.canExecuteInDomain(t))return y(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(a.domainTeamManager)try{if(!a.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;a.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],s=await a.requestAgentSpawn(t,i,r),o=[];s.success&&o.push(s.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};a.tasks.set(e.id,l),a.domainLastActivity.set(t,new Date);for(let c of o)a.auditLogger.logAssign(e.id,c,t);if(await a.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),a.domainPlugins){let c=a.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(a,m));return d.success?b(e.id):(a.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.tasksFailed++,a.auditLogger.logFail(e.id,o[0],d.error.message),y(d.error))}if(c)try{await c.handleEvent({id:T(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return b(e.id)}async function mi(a,e){let t=a.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(a.tasks.set(e.taskId,n),e.success?(a.tasksCompleted++,a.taskDurations.push(e.duration),a.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(a.tasksFailed++,a.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),a.runningTaskCounter=Math.max(0,a.runningTaskCounter-1),a.coExecutionRepo&&t.assignedAgents.length>=2)try{a.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await a.agentCoordinator.stop(i);await a.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(a)}function Yt(a,e){return(P[e.type]||[]).includes(a)}k();async function Zt(a){let e=0,t=a.getIdleDomains(),n=a.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>a.getDomainLoad(r)-a.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=a.domainQueues.get(i)||[],s=Math.min(r.length,a.config.workStealing.stealBatchSize);for(let o=0;o<s&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();a.removeFromQueues(l),a.auditLogger.logSteal(l.id,i,c),await a.assignTaskToDomain(l,c),e++,a.tasksStolen++,await a.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(a,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let s=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${s}ms`,h(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,s))}},a.workStealing.checkInterval);return i}function Ze(a){return typeof a.setMinCutBridge=="function"}function Xt(a,e){for(let[t,n]of a)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(a,e,t){try{let n=await a.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(a,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await a.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(a){return setInterval(async()=>{let e=a.getMetrics();if(await a.publishEvent("MetricsCollected",{metrics:e}),await a.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:86400,namespace:"queen-coordinator"}),a.dynamicScaler)try{let t=a.getAverageTaskDuration(),n={queueDepth:a.getQueuedTaskCount(),activeAgents:a.getActiveAgentCount(),idleAgents:a.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:a.getTasksReceived()>0?a.getTasksFailed()/a.getTasksReceived():0,throughput:e.uptime>0?a.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};a.dynamicScaler.recordMetrics(n);let i=a.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),a.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},a.config.metricsInterval)}function Xe(a,e,t=36e5){let n=Date.now(),i=0;for(let[s,o]of a)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(a.delete(s),e.delete(s),i++)}let r=1e4;if(e.size>r){let s=e.size-r,o=e.keys();for(let l=0;l<s;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${s} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(a,e){return a&&a.size>0?Array.from(a.keys()):[...e]}var g=it.create("QueenCoordinator");zt(v);var Je=class{constructor(e,t,n,i,r,s,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=s;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),v.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=dt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-NCDBQLLF.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:v}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return y(new Error("Queen Coordinator not initialized"));let t=`task_${T()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),y(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),b(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return y(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return y(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),b(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return v.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return v.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return y(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let s=r.dependencies.mcpServers;if(!s||s.length===0)continue;let o=s.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,v);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let s=this.agentCoordinator.listAgents(),o=s.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:s.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map,t=0;for(let l of v){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,s=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:s,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new ae(e);this.taskCompletedHook=new se({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return y(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return y(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),b(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),v)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:T(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),b(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(a,e,t,n,i,r){return new Je(a.eventBus,a.coordinator,a.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
|
|
@@ -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.
|
|
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.12.1");process.exit(0)}
|
|
2
2
|
import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
|
|
3
3
|
`),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
|
|
4
4
|
|