agentic-qe 3.10.8 → 3.10.9

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.
Files changed (354) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +37 -1
  3. package/dist/cli/bundle.js +5 -5
  4. package/dist/cli/chunks/adapter-TRSV37EA.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-4JSL6LF6.js → agent-booster-wasm-RPAOJXZ3.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-6YOFH7KL.js → agent-handler-SMD5CAS6.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-O3IBK4BY.js → agent-memory-branch-3IOQIQ7Y.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-CVJRJOSO.js +2 -0
  9. package/dist/cli/chunks/{arena-KLGRZTTU.js → arena-AP2J62WO.js} +4 -4
  10. package/dist/cli/chunks/{arena-BLCAZNAY.js → arena-GT3D6EAO.js} +2 -2
  11. package/dist/cli/chunks/{audit-FKKLR22S.js → audit-Q3GJ5354.js} +2 -2
  12. package/dist/cli/chunks/base-BX4A2D4V.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-PNPV64M3.js → better-sqlite3-6A6EAXAT.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-YTGYC2QW.js → brain-handler-2Z4ILQF3.js} +3 -3
  15. package/dist/cli/chunks/{branch-enumerator-KIIBEJ5S.js → branch-enumerator-EZWGL4UM.js} +2 -2
  16. package/dist/cli/chunks/{browser-7YZLTV2C.js → browser-YZELFPLJ.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-O3RL7EYT.js +2 -0
  18. package/dist/cli/chunks/{chunk-DDMKCHYT.js → chunk-246Z3PH6.js} +2 -2
  19. package/dist/cli/chunks/{chunk-DI7REPYC.js → chunk-2I5QLMQF.js} +2 -2
  20. package/dist/cli/chunks/{chunk-D7IH2A3C.js → chunk-2K2X75UF.js} +2 -2
  21. package/dist/cli/chunks/{chunk-Y4XTPEAC.js → chunk-2WRVNEIR.js} +2 -2
  22. package/dist/cli/chunks/{chunk-FXPAGKVS.js → chunk-2WSEJHFQ.js} +1 -1
  23. package/dist/cli/chunks/{chunk-JQBD4JO2.js → chunk-352W5G4G.js} +2 -2
  24. package/dist/cli/chunks/{chunk-OZDRAKFF.js → chunk-3HT4CT6F.js} +2 -2
  25. package/dist/cli/chunks/{chunk-KTEWRRDZ.js → chunk-3YKJGKOY.js} +4 -4
  26. package/dist/cli/chunks/{chunk-4G2GTX2V.js → chunk-42FBJF73.js} +1 -1
  27. package/dist/cli/chunks/{chunk-MSWBVPVQ.js → chunk-4BB75U6N.js} +2 -2
  28. package/dist/cli/chunks/{chunk-77BVW2CT.js → chunk-4D3LVXUD.js} +2 -2
  29. package/dist/cli/chunks/{chunk-RXWPYY6H.js → chunk-4EJTE5TL.js} +1 -1
  30. package/dist/cli/chunks/{chunk-CP4CSI5R.js → chunk-4MUZGQPE.js} +2 -2
  31. package/dist/cli/chunks/{chunk-CCUUTTTJ.js → chunk-57XCLC55.js} +2 -2
  32. package/dist/cli/chunks/{chunk-ZSMHQENA.js → chunk-5HLOQEKL.js} +1 -1
  33. package/dist/cli/chunks/{chunk-MTWBYHMS.js → chunk-5U5SEO7C.js} +2 -2
  34. package/dist/cli/chunks/{chunk-FWQZZ22V.js → chunk-5X73HV2P.js} +1 -1
  35. package/dist/cli/chunks/{chunk-YUK4KU2B.js → chunk-62MH7QAQ.js} +2 -2
  36. package/dist/cli/chunks/{chunk-WKLI5Z3L.js → chunk-6HPI6YX3.js} +2 -2
  37. package/dist/cli/chunks/{chunk-6B3COND2.js → chunk-6TR3OM7C.js} +2 -2
  38. package/dist/cli/chunks/{chunk-Z57UERQZ.js → chunk-757YHKIJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-HEC2UWY3.js → chunk-7C5HI4ZA.js} +4 -4
  40. package/dist/cli/chunks/{chunk-O75ODKCX.js → chunk-7D5JE46U.js} +2 -2
  41. package/dist/cli/chunks/{chunk-7NKVEEXD.js → chunk-7NT34MLU.js} +1 -1
  42. package/dist/cli/chunks/{chunk-LZVKR7HV.js → chunk-7PYEJ4NV.js} +2 -2
  43. package/dist/cli/chunks/{chunk-PG7KISET.js → chunk-7S6D5K4X.js} +2 -2
  44. package/dist/cli/chunks/{chunk-SDGRU6SG.js → chunk-ABJPFKHE.js} +1 -1
  45. package/dist/cli/chunks/{chunk-4AG2TQEF.js → chunk-ABVBHH7P.js} +3 -3
  46. package/dist/cli/chunks/{chunk-ALFF4AAM.js → chunk-AHUX7QSE.js} +2 -2
  47. package/dist/cli/chunks/{chunk-54PBHRRW.js → chunk-AU4DQMLJ.js} +4 -4
  48. package/dist/cli/chunks/{chunk-HWJEHXPQ.js → chunk-BG2FN5K2.js} +2 -2
  49. package/dist/cli/chunks/{chunk-SSRMFU4P.js → chunk-BM52ZEAD.js} +2 -2
  50. package/dist/cli/chunks/{chunk-LJEO5R32.js → chunk-BSMUT672.js} +2 -2
  51. package/dist/cli/chunks/{chunk-NL4EKO2J.js → chunk-BVEQPMOF.js} +2 -2
  52. package/dist/cli/chunks/{chunk-PTPGYUT2.js → chunk-BYVARYGB.js} +2 -2
  53. package/dist/cli/chunks/{chunk-UU422SST.js → chunk-C6GQIUKW.js} +2 -2
  54. package/dist/cli/chunks/{chunk-LBR5FXPD.js → chunk-C6JULAWA.js} +2 -2
  55. package/dist/cli/chunks/{chunk-XNFYQRJ2.js → chunk-CDJIYJIA.js} +1 -1
  56. package/dist/cli/chunks/{chunk-2UL4UK6V.js → chunk-CLJNAQXB.js} +2 -2
  57. package/dist/cli/chunks/{chunk-X4CHPEOQ.js → chunk-CLSHSVMY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-SDVL5TZK.js → chunk-CREORFJV.js} +1 -1
  59. package/dist/cli/chunks/{chunk-T2Z3M6HA.js → chunk-CVRTXIYP.js} +1 -1
  60. package/dist/cli/chunks/{chunk-OIU6PKLF.js → chunk-CWRSQQHV.js} +2 -2
  61. package/dist/cli/chunks/{chunk-S6PGWJDK.js → chunk-D2JCSWYM.js} +2 -2
  62. package/dist/cli/chunks/{chunk-4OHLPG6B.js → chunk-D7NWDUY3.js} +2 -2
  63. package/dist/cli/chunks/{chunk-ON6C2OYG.js → chunk-DK6WWNCL.js} +2 -2
  64. package/dist/cli/chunks/{chunk-LCDMB5SP.js → chunk-DNE6MVNA.js} +1 -1
  65. package/dist/cli/chunks/{chunk-X3NEQ3SL.js → chunk-DZWZASDV.js} +1 -1
  66. package/dist/cli/chunks/{chunk-RNJRKFMX.js → chunk-EL6F72JN.js} +2 -2
  67. package/dist/cli/chunks/{chunk-XLQX77KP.js → chunk-EYGRNXQT.js} +1 -1
  68. package/dist/cli/chunks/{chunk-DNEYBK7X.js → chunk-FALB6Z2Y.js} +1 -1
  69. package/dist/cli/chunks/{chunk-PRYSWF6F.js → chunk-FD37QFXW.js} +1 -1
  70. package/dist/cli/chunks/{chunk-K5Y64X2U.js → chunk-G4KVGUQN.js} +2 -2
  71. package/dist/cli/chunks/{chunk-QNNH5TDV.js → chunk-G7V2HDTH.js} +3 -3
  72. package/dist/cli/chunks/{chunk-WYAHOUK2.js → chunk-GPALZJD3.js} +1 -1
  73. package/dist/cli/chunks/{chunk-AGQIJWAD.js → chunk-H4SHHYRD.js} +2 -2
  74. package/dist/cli/chunks/{chunk-Q32LITZL.js → chunk-H7AQ7M3J.js} +1 -1
  75. package/dist/cli/chunks/{chunk-GDHJZPNC.js → chunk-HAC7NB6R.js} +2 -2
  76. package/dist/cli/chunks/{chunk-YMJ5AVVU.js → chunk-HGKZOSAI.js} +1 -1
  77. package/dist/cli/chunks/{chunk-VKLPSPPI.js → chunk-HQZX4XYH.js} +2 -2
  78. package/dist/cli/chunks/{chunk-4B676LUC.js → chunk-HZSYCVLC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-YQYTQRTR.js → chunk-I5C7O5IQ.js} +2 -2
  80. package/dist/cli/chunks/{chunk-7LHN6WBX.js → chunk-I7RTTJH5.js} +2 -2
  81. package/dist/cli/chunks/{chunk-OK6CSJOX.js → chunk-ILPIH4Z6.js} +1 -1
  82. package/dist/cli/chunks/{chunk-6R6RC6YJ.js → chunk-IR7PJUO7.js} +2 -2
  83. package/dist/cli/chunks/{chunk-BALWMVCX.js → chunk-J6GKKXCP.js} +2 -2
  84. package/dist/cli/chunks/{chunk-34LWJDCM.js → chunk-JZNMU63B.js} +2 -2
  85. package/dist/cli/chunks/{chunk-C6TUX7YJ.js → chunk-K23XK33X.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GHIHW3IE.js → chunk-KAMFT25W.js} +2 -2
  87. package/dist/cli/chunks/{chunk-OV3ESWN4.js → chunk-KJA5A3TV.js} +2 -2
  88. package/dist/cli/chunks/{chunk-HE3KLHNO.js → chunk-KRAWWBX5.js} +2 -2
  89. package/dist/cli/chunks/{chunk-LT4OZHMK.js → chunk-L5IO7QNO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-OLOKPY5O.js → chunk-L5NEEGKO.js} +2 -2
  91. package/dist/cli/chunks/{chunk-IFQPGBKQ.js → chunk-LHKQW72O.js} +1 -1
  92. package/dist/cli/chunks/{chunk-6B32USSC.js → chunk-LT6QHDPK.js} +2 -2
  93. package/dist/cli/chunks/{chunk-B3B5QZYN.js → chunk-MDED3HJI.js} +2 -2
  94. package/dist/cli/chunks/{chunk-FPEFIJQ6.js → chunk-NLUWPS2H.js} +3 -3
  95. package/dist/cli/chunks/{chunk-Q7B7T4YK.js → chunk-NMQEU4BG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-4IGSL7CX.js → chunk-NOWGQ6YZ.js} +1 -1
  97. package/dist/cli/chunks/{chunk-M5PBVK3V.js → chunk-NYBAH76S.js} +3 -3
  98. package/dist/cli/chunks/{chunk-LIOK7WBX.js → chunk-O36VC7B7.js} +2 -2
  99. package/dist/cli/chunks/{chunk-WDZT344G.js → chunk-OD4OIPXO.js} +15 -13
  100. package/dist/cli/chunks/{chunk-JZYXYHEE.js → chunk-OF3EMOWN.js} +2 -2
  101. package/dist/cli/chunks/{chunk-2F4VRCT6.js → chunk-OIN3Y4BY.js} +1 -1
  102. package/dist/cli/chunks/chunk-OPKEQYAC.js +2 -0
  103. package/dist/cli/chunks/{chunk-XYXRO7VP.js → chunk-OQUH7657.js} +2 -2
  104. package/dist/cli/chunks/{chunk-R2LWUBET.js → chunk-OSP5AJAB.js} +2 -2
  105. package/dist/cli/chunks/{chunk-XPAH7SEX.js → chunk-PFGH7TWL.js} +2 -2
  106. package/dist/cli/chunks/{chunk-DNC27OP7.js → chunk-PYQZ4OA3.js} +2 -2
  107. package/dist/cli/chunks/{chunk-5KUINS3D.js → chunk-QAP5S7YC.js} +3 -3
  108. package/dist/cli/chunks/{chunk-XKIVOADM.js → chunk-QE3CZGAC.js} +3 -3
  109. package/dist/cli/chunks/{chunk-NKKDO5W4.js → chunk-QFIKEZB5.js} +2 -2
  110. package/dist/cli/chunks/{chunk-5GPOSKGP.js → chunk-QHICG2NI.js} +2 -2
  111. package/dist/cli/chunks/{chunk-HVE3EH36.js → chunk-QHPLU5BU.js} +3 -3
  112. package/dist/cli/chunks/{chunk-XRJH5KXF.js → chunk-QL6ZJ7RV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-3AG2MM7U.js → chunk-QL7OOCPO.js} +2 -2
  114. package/dist/cli/chunks/{chunk-NFZY6ZVY.js → chunk-QWXJRZEH.js} +1 -1
  115. package/dist/cli/chunks/{chunk-E5GUTKET.js → chunk-R2M3RMCN.js} +2 -2
  116. package/dist/cli/chunks/{chunk-2KP5TJS2.js → chunk-RHOBDQXA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-HVFHPDXV.js → chunk-RRSJ7BMF.js} +1 -1
  118. package/dist/cli/chunks/{chunk-KTBBSOZG.js → chunk-RSWQY4NZ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-JITZAJJN.js → chunk-S73EBPI5.js} +2 -2
  120. package/dist/cli/chunks/{chunk-CO6UY7ZU.js → chunk-TIR3Z6TE.js} +1 -1
  121. package/dist/cli/chunks/{chunk-474ZUVGP.js → chunk-TKZABUHO.js} +1 -1
  122. package/dist/cli/chunks/{chunk-2RDWYJJY.js → chunk-TOGD2JH2.js} +2 -2
  123. package/dist/cli/chunks/{chunk-33CLP2NE.js → chunk-TVU6NMO3.js} +3 -3
  124. package/dist/cli/chunks/{chunk-BMSMDD72.js → chunk-TXWUV3S5.js} +2 -2
  125. package/dist/cli/chunks/{chunk-VM5C4DIV.js → chunk-U6TZVACK.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KWKGROPS.js → chunk-UJBIHPU5.js} +1 -1
  127. package/dist/cli/chunks/{chunk-JFTRHS5V.js → chunk-UPGKS6Z3.js} +2 -2
  128. package/dist/cli/chunks/{chunk-H35FNLQJ.js → chunk-UU7OCRZM.js} +2 -2
  129. package/dist/cli/chunks/{chunk-MWAEUJDC.js → chunk-UUA2NVUN.js} +8 -8
  130. package/dist/cli/chunks/{chunk-NWIKNQLJ.js → chunk-UX4UHYLE.js} +1 -1
  131. package/dist/cli/chunks/{chunk-Z4WAJ647.js → chunk-VDL277DX.js} +2 -2
  132. package/dist/cli/chunks/{chunk-VL4MSE3J.js → chunk-VHCHBMZC.js} +2 -2
  133. package/dist/cli/chunks/{chunk-G73PIM7X.js → chunk-VHYNRISI.js} +2 -2
  134. package/dist/cli/chunks/{chunk-TXLLF7XR.js → chunk-VIHFC67B.js} +1 -1
  135. package/dist/cli/chunks/{chunk-QHLENBGB.js → chunk-WOGWIMQK.js} +2 -2
  136. package/dist/cli/chunks/{chunk-H73AA2JI.js → chunk-WPBVLIWQ.js} +10 -10
  137. package/dist/cli/chunks/{chunk-CHPL7TA4.js → chunk-WWGGL3TR.js} +1 -1
  138. package/dist/cli/chunks/{chunk-D7ZVIL3C.js → chunk-X6YUGKMM.js} +1 -1
  139. package/dist/cli/chunks/{chunk-G2J7WGOG.js → chunk-X7677BX3.js} +2 -2
  140. package/dist/cli/chunks/{chunk-GXKCRIHK.js → chunk-XEMP2PNW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-Z7FWPSOK.js → chunk-XLK4GP3I.js} +2 -2
  142. package/dist/cli/chunks/{chunk-YATW2RWQ.js → chunk-XYRJL7YN.js} +2 -2
  143. package/dist/cli/chunks/{chunk-W72CUJRB.js → chunk-YB3PQ3UV.js} +1 -1
  144. package/dist/cli/chunks/{chunk-QHGHWATK.js → chunk-YHFCLJMY.js} +1 -1
  145. package/dist/cli/chunks/{chunk-CDNXXNQM.js → chunk-YQBL5XTM.js} +1 -1
  146. package/dist/cli/chunks/chunk-Z6FRNWQA.js +6 -0
  147. package/dist/cli/chunks/{chunk-NOP5ZJ7E.js → chunk-ZT2DGSIO.js} +2 -2
  148. package/dist/cli/chunks/{chunk-DPSLJ6IW.js → chunk-ZVF7QY4R.js} +1 -1
  149. package/dist/cli/chunks/{ci-2G4BBIQD.js → ci-KDEFR2X3.js} +2 -2
  150. package/dist/cli/chunks/{ci-output-SI3ME52L.js → ci-output-Z3WXRRFI.js} +2 -2
  151. package/dist/cli/chunks/{circuit-breaker-KTICF3EC.js → circuit-breaker-GS44DEW2.js} +2 -2
  152. package/dist/cli/chunks/{claude-flow-setup-F44PULFU.js → claude-flow-setup-OHVMHAAH.js} +2 -2
  153. package/dist/cli/chunks/client-T263ZXVV.js +2 -0
  154. package/dist/cli/chunks/cline-installer-5TCF4MZD.js +4 -0
  155. package/dist/cli/chunks/{code-EDLIBN77.js → code-3KCGTG7Z.js} +2 -2
  156. package/dist/cli/chunks/{code-index-extractor-P4NBWGTV.js → code-index-extractor-LJBI54MZ.js} +2 -2
  157. package/dist/cli/chunks/codex-installer-IB62Z6LA.js +8 -0
  158. package/dist/cli/chunks/{completions-XPCXB5SR.js → completions-JDXX7KKB.js} +2 -2
  159. package/dist/cli/chunks/{complexity-analyzer-LAL5RSB7.js → complexity-analyzer-6JVDXXXP.js} +2 -2
  160. package/dist/cli/chunks/continuedev-installer-PUB45QVR.js +15 -0
  161. package/dist/cli/chunks/copilot-installer-QWJ36P22.js +3 -0
  162. package/dist/cli/chunks/core-handlers-ODKKGCFK.js +2 -0
  163. package/dist/cli/chunks/{cost-tracker-EUJFKHGT.js → cost-tracker-J3KEJDL5.js} +2 -2
  164. package/dist/cli/chunks/{coverage-C75LPZYB.js → coverage-FWKRI2EY.js} +3 -3
  165. package/dist/cli/chunks/cross-domain-router-APU725GC.js +2 -0
  166. package/dist/cli/chunks/cursor-installer-2HYCUCTH.js +3 -0
  167. package/dist/cli/chunks/{daemon-JR2MSTSK.js → daemon-BVP66DIZ.js} +4 -4
  168. package/dist/cli/chunks/{daemon-BPVBZZQO.js → daemon-G3DBRWDQ.js} +3 -3
  169. package/dist/cli/chunks/{dag-attention-scheduler-I5H7DBNU.js → dag-attention-scheduler-2AQLNB4B.js} +2 -2
  170. package/dist/cli/chunks/{detect-O5TMML24.js → detect-RUM5SHNE.js} +2 -2
  171. package/dist/cli/chunks/{dist-node-MDZ6UQ3V.js → dist-node-GX7MJHFT.js} +2 -2
  172. package/dist/cli/chunks/{domain-handler-BGBTZETG.js → domain-handler-OFBGZ2U5.js} +2 -2
  173. package/dist/cli/chunks/{domain-transfer-C2D2IEYV.js → domain-transfer-6CGRPRGR.js} +2 -2
  174. package/dist/cli/chunks/dream-PJ5GKY3J.js +2 -0
  175. package/dist/cli/chunks/{embed-and-insert-pattern-UJREBJF5.js → embed-and-insert-pattern-MUOEVQX2.js} +2 -2
  176. package/dist/cli/chunks/{eval-BDD24HQC.js → eval-SJMG67DE.js} +2 -2
  177. package/dist/cli/chunks/{experience-capture-middleware-KLVXIIYH.js → experience-capture-middleware-ICKN6IXX.js} +3 -3
  178. package/dist/cli/chunks/{fast-paths-5HIKAQZ7.js → fast-paths-HXLBG3J4.js} +2 -2
  179. package/dist/cli/chunks/{feature-flags-YE5SJPDS.js → feature-flags-CRUB2ASU.js} +2 -2
  180. package/dist/cli/chunks/{feature-flags-NM3S7OEW.js → feature-flags-JYZSSQJC.js} +2 -2
  181. package/dist/cli/chunks/{file-discovery-PWRQZNJQ.js → file-discovery-YHHC7NTJ.js} +2 -2
  182. package/dist/cli/chunks/{fleet-UIPKNQX3.js → fleet-2VGDL4YL.js} +3 -3
  183. package/dist/cli/chunks/{gnn-wrapper-GWGKZRTO.js → gnn-wrapper-7ZAGD4S4.js} +2 -2
  184. package/dist/cli/chunks/{heartbeat-handler-GQHJPNAY.js → heartbeat-handler-HAW3JRHN.js} +4 -4
  185. package/dist/cli/chunks/heartbeat-scheduler-4ZHUIW3Q.js +2 -0
  186. package/dist/cli/chunks/hnsw-adapter-UVJJ6TTP.js +2 -0
  187. package/dist/cli/chunks/hnsw-index-K6HS34JZ.js +2 -0
  188. package/dist/cli/chunks/{hnsw-legacy-bridge-NE5JIRG3.js → hnsw-legacy-bridge-BO325POX.js} +2 -2
  189. package/dist/cli/chunks/{better-sqlite3-MROES2Y7.js → hnswlib-node-YTK7S7GL.js} +2 -2
  190. package/dist/cli/chunks/{hooks-3NBBUOB6.js → hooks-HKM3JTFQ.js} +10 -10
  191. package/dist/cli/chunks/hybrid-router-25S7OH2Y.js +2 -0
  192. package/dist/cli/chunks/{hypergraph-engine-6NRFVDV7.js → hypergraph-engine-LGLGHK6B.js} +2 -2
  193. package/dist/cli/chunks/{hypergraph-handler-F3OOGTXF.js → hypergraph-handler-6QDVREZA.js} +3 -3
  194. package/dist/cli/chunks/impact-analyzer-UP4RDMJH.js +2 -0
  195. package/dist/cli/chunks/{init-handler-DOTXTVUI.js → init-handler-XUQ7XHIE.js} +22 -21
  196. package/dist/cli/chunks/init-wizard-2PAJ3GEC.js +2 -0
  197. package/dist/cli/chunks/kernel-7WOQGMMT.js +2 -0
  198. package/dist/cli/chunks/kilocode-installer-6CEZLVIX.js +4 -0
  199. package/dist/cli/chunks/{kiro-installer-WBJDXY7Q.js → kiro-installer-6CJGATOS.js} +4 -4
  200. package/dist/cli/chunks/knowledge-graph-FN2AWHGR.js +2 -0
  201. package/dist/cli/chunks/{learning-BC5N4V3D.js → learning-EIYTYZJY.js} +3 -3
  202. package/dist/cli/chunks/{llm-router-T427WD6R.js → llm-router-J4CI7VHU.js} +4 -4
  203. package/dist/cli/chunks/llm-router-service-C3UPBAS3.js +2 -0
  204. package/dist/cli/chunks/{load-M6SL2O3M.js → load-CQPWGLQQ.js} +2 -2
  205. package/dist/cli/chunks/load-test-PQSGLDXJ.js +2 -0
  206. package/dist/cli/chunks/mcp-THOATWCO.js +2 -0
  207. package/dist/cli/chunks/{memory-FJAO3CSF.js → memory-NZHMHMRK.js} +5 -5
  208. package/dist/cli/chunks/memory-backend-6FR4RT5O.js +2 -0
  209. package/dist/cli/chunks/{memory-handlers-S3W6IQJL.js → memory-handlers-L2J54AQE.js} +2 -2
  210. package/dist/cli/chunks/{multi-model-executor-FYOVZ4OH.js → multi-model-executor-3P5E773H.js} +2 -2
  211. package/dist/cli/chunks/{opencode-installer-APSBE4UR.js → opencode-installer-IRZMKSNG.js} +2 -2
  212. package/dist/cli/chunks/{orchestrator-LN53EQ45.js → orchestrator-UADLXTKP.js} +16 -16
  213. package/dist/cli/chunks/pattern-null-store-B2UX4NZY.js +2 -0
  214. package/dist/cli/chunks/{pipeline-BYWXY2NO.js → pipeline-QEH3XHXJ.js} +2 -2
  215. package/dist/cli/chunks/{platform-CZ774YPS.js → platform-NEZ3NXLT.js} +2 -2
  216. package/dist/cli/chunks/{plugin-72NXRX5Z.js → plugin-O33HR2VO.js} +2 -2
  217. package/dist/cli/chunks/{prime-radiant-advanced-wasm-G4DE6YKJ.js → prime-radiant-advanced-wasm-MBUMFEX7.js} +2 -2
  218. package/dist/cli/chunks/protocol-executor-OQ6SL7SR.js +2 -0
  219. package/dist/cli/chunks/{protocol-handler-UH6CV63V.js → protocol-handler-L455UOUT.js} +2 -2
  220. package/dist/cli/chunks/{prove-V7FAT5HF.js → prove-3XA3SMAA.js} +2 -2
  221. package/dist/cli/chunks/provider-manager-DQWHW2RG.js +2 -0
  222. package/dist/cli/chunks/qe-reasoning-bank-3JS2CZAE.js +2 -0
  223. package/dist/cli/chunks/{quality-N2K62FQM.js → quality-H6Z5JH5B.js} +2 -2
  224. package/dist/cli/chunks/queen-coordinator-KXCWEM3Y.js +2 -0
  225. package/dist/cli/chunks/{real-embeddings-TKHUE2RL.js → real-embeddings-5DNJ4KEM.js} +2 -2
  226. package/dist/cli/chunks/roocode-installer-KHXKR2FK.js +4 -0
  227. package/dist/cli/chunks/router-OVLIKT55.js +2 -0
  228. package/dist/cli/chunks/routing-feedback-2BYCXNXX.js +2 -0
  229. package/dist/cli/chunks/{routing-handler-UUWD4IKG.js → routing-handler-WAMGESEM.js} +2 -2
  230. package/dist/cli/chunks/{ruvector-commands-B4WPTGCI.js → ruvector-commands-4J7XC6XY.js} +2 -2
  231. package/dist/cli/chunks/{rvf-dual-writer-MNRJGNIX.js → rvf-dual-writer-3PZEN6XN.js} +2 -2
  232. package/dist/cli/chunks/{rvf-migration-adapter-P2RDBFA4.js → rvf-migration-adapter-OIUNRQSU.js} +2 -2
  233. package/dist/cli/chunks/{rvf-migration-coordinator-DFESZQSS.js → rvf-migration-coordinator-QZXDI4I5.js} +2 -2
  234. package/dist/cli/chunks/rvf-native-adapter-YNUYOQ5C.js +2 -0
  235. package/dist/cli/chunks/safe-db-6TYYEU7C.js +2 -0
  236. package/dist/cli/chunks/schedule-XVH7RTVY.js +2 -0
  237. package/dist/cli/chunks/scheduler-DHZBN5HA.js +2 -0
  238. package/dist/cli/chunks/{security-MHLTNKFX.js → security-5NY77AMD.js} +3 -3
  239. package/dist/cli/chunks/{shared-rvf-adapter-LR7E2EQI.js → shared-rvf-adapter-MHPUZIMW.js} +2 -2
  240. package/dist/cli/chunks/{shared-rvf-dual-writer-RFFON2F3.js → shared-rvf-dual-writer-ITLDYHCX.js} +2 -2
  241. package/dist/cli/chunks/sqlite-persistence-NR5WXTPN.js +2 -0
  242. package/dist/cli/chunks/{status-handler-ROPTYGQC.js → status-handler-7RBRIXZD.js} +2 -2
  243. package/dist/cli/chunks/{structural-health-YGUFXGJ6.js → structural-health-MQPY6GA6.js} +2 -2
  244. package/dist/cli/chunks/{sync-6JTRTDL3.js → sync-66KCEANE.js} +2 -2
  245. package/dist/cli/chunks/{sync-NZZUMTKC.js → sync-USVQTHKN.js} +2 -2
  246. package/dist/cli/chunks/{task-handler-KYMV3AC6.js → task-handler-4UI4FPPW.js} +2 -2
  247. package/dist/cli/chunks/{task-handlers-Z63YBQVU.js → task-handlers-KRII3GVV.js} +3 -3
  248. package/dist/cli/chunks/{test-O6BQ7FGP.js → test-JHN2MVEG.js} +4 -4
  249. package/dist/cli/chunks/{test-scheduling-T3IOXEFI.js → test-scheduling-ZWTEGS3S.js} +3 -3
  250. package/dist/cli/chunks/{token-bootstrap-CTI2ULJF.js → token-bootstrap-YWXL6AS5.js} +2 -2
  251. package/dist/cli/chunks/{token-usage-TNQTNAVT.js → token-usage-INII2XM3.js} +2 -2
  252. package/dist/cli/chunks/{transformers-CJQDNQER.js → transformers-DVFGDNZC.js} +2 -2
  253. package/dist/cli/chunks/{tree-sitter-wasm-parser-RBZWLEVQ.js → tree-sitter-wasm-parser-W2XJT3XF.js} +2 -2
  254. package/dist/cli/chunks/{types-OMFCO364.js → types-GBZ5Q2GP.js} +2 -2
  255. package/dist/cli/chunks/unified-memory-WJEZ5YAK.js +2 -0
  256. package/dist/cli/chunks/unified-memory-hnsw-6ZA2PMYO.js +2 -0
  257. package/dist/cli/chunks/unified-persistence-SWH6R7MA.js +2 -0
  258. package/dist/cli/chunks/{upgrade-KRVOYWN3.js → upgrade-2JEXEGQX.js} +2 -2
  259. package/dist/cli/chunks/{validate-32FKHMKQ.js → validate-GDCM5YTS.js} +2 -2
  260. package/dist/cli/chunks/{validate-swarm-45RPBPPH.js → validate-swarm-QZ5RSJEU.js} +2 -2
  261. package/dist/cli/chunks/{vibium-LCTNDCKK.js → vibium-I5BMT734.js} +2 -2
  262. package/dist/cli/chunks/visual-security-PH5JQZCZ.js +2 -0
  263. package/dist/cli/chunks/{web-tree-sitter-FX2EFCLH.js → web-tree-sitter-3QY2LMLP.js} +2 -2
  264. package/dist/cli/chunks/windsurf-installer-V7OBPLOB.js +7 -0
  265. package/dist/cli/chunks/{witness-chain-YG2UWTYZ.js → witness-chain-BNJ4VSZX.js} +2 -2
  266. package/dist/cli/chunks/witness-chain-WYMBNGSL.js +2 -0
  267. package/dist/cli/chunks/{workflow-AEJ37RNV.js → workflow-3FJSNLPI.js} +4 -4
  268. package/dist/cli/chunks/workflow-orchestrator-56JIXCI4.js +2 -0
  269. package/dist/cli/chunks/{wrappers-GSU6VNU6.js → wrappers-ERTQNIPK.js} +2 -2
  270. package/dist/cli/commands/mcp.js +28 -28
  271. package/dist/cli/handlers/init-handler.d.ts +2 -0
  272. package/dist/cli/handlers/init-handler.js +22 -1
  273. package/dist/init/cline-installer.d.ts +6 -0
  274. package/dist/init/cline-installer.js +3 -1
  275. package/dist/init/codex-installer.d.ts +6 -0
  276. package/dist/init/codex-installer.js +3 -1
  277. package/dist/init/continuedev-installer.d.ts +6 -0
  278. package/dist/init/continuedev-installer.js +10 -3
  279. package/dist/init/copilot-installer.d.ts +6 -0
  280. package/dist/init/copilot-installer.js +3 -1
  281. package/dist/init/cursor-installer.d.ts +6 -0
  282. package/dist/init/cursor-installer.js +3 -1
  283. package/dist/init/kilocode-installer.d.ts +6 -0
  284. package/dist/init/kilocode-installer.js +3 -1
  285. package/dist/init/kiro-installer.d.ts +5 -0
  286. package/dist/init/kiro-installer.js +4 -4
  287. package/dist/init/orchestrator.js +1 -0
  288. package/dist/init/phases/07-hooks.js +5 -0
  289. package/dist/init/phases/08-mcp.js +34 -7
  290. package/dist/init/phases/09-assets.js +30 -27
  291. package/dist/init/phases/11-claude-md.d.ts +1 -0
  292. package/dist/init/phases/11-claude-md.js +8 -0
  293. package/dist/init/phases/13-governance.js +5 -0
  294. package/dist/init/phases/phase-interface.d.ts +8 -0
  295. package/dist/init/platform-config-generator.d.ts +3 -1
  296. package/dist/init/platform-config-generator.js +31 -17
  297. package/dist/init/roocode-installer.d.ts +6 -0
  298. package/dist/init/roocode-installer.js +3 -1
  299. package/dist/init/windsurf-installer.d.ts +6 -0
  300. package/dist/init/windsurf-installer.js +3 -1
  301. package/dist/mcp/bundle.js +297 -296
  302. package/dist/mcp/entry.js +10 -1
  303. package/dist/mcp/protocol-server.js +17 -0
  304. package/dist/optimization/session-cache.d.ts +11 -0
  305. package/dist/optimization/session-cache.js +31 -0
  306. package/package.json +2 -2
  307. package/dist/cli/chunks/adapter-PAMPC2X7.js +0 -2
  308. package/dist/cli/chunks/aqe-learning-engine-DGKLEC6I.js +0 -2
  309. package/dist/cli/chunks/base-6HJR4VJT.js +0 -2
  310. package/dist/cli/chunks/browser-workflow-OWNU5XK7.js +0 -2
  311. package/dist/cli/chunks/chunk-2B2RLPK3.js +0 -2
  312. package/dist/cli/chunks/chunk-NSI3WL6P.js +0 -6
  313. package/dist/cli/chunks/client-E6GK5NWT.js +0 -2
  314. package/dist/cli/chunks/cline-installer-A7G7OXIS.js +0 -4
  315. package/dist/cli/chunks/codex-installer-JB3ULDQP.js +0 -8
  316. package/dist/cli/chunks/continuedev-installer-GSYBLQV7.js +0 -14
  317. package/dist/cli/chunks/copilot-installer-7B56CNU2.js +0 -3
  318. package/dist/cli/chunks/core-handlers-HJUORTFU.js +0 -2
  319. package/dist/cli/chunks/cross-domain-router-35WVZFAZ.js +0 -2
  320. package/dist/cli/chunks/cursor-installer-WXQFM4KJ.js +0 -3
  321. package/dist/cli/chunks/dream-QTZDMP6D.js +0 -2
  322. package/dist/cli/chunks/heartbeat-scheduler-N433NZCG.js +0 -2
  323. package/dist/cli/chunks/hnsw-adapter-MR6W2OA4.js +0 -2
  324. package/dist/cli/chunks/hnsw-index-XC6EMJA2.js +0 -2
  325. package/dist/cli/chunks/hybrid-router-SH4IEAJA.js +0 -2
  326. package/dist/cli/chunks/impact-analyzer-RUTVXE7P.js +0 -2
  327. package/dist/cli/chunks/init-wizard-56NY5BSP.js +0 -2
  328. package/dist/cli/chunks/kernel-7JAN7WCO.js +0 -2
  329. package/dist/cli/chunks/kilocode-installer-3AXYSZTO.js +0 -4
  330. package/dist/cli/chunks/knowledge-graph-ST4LW3V4.js +0 -2
  331. package/dist/cli/chunks/llm-router-service-JNDF5MVJ.js +0 -2
  332. package/dist/cli/chunks/load-test-I3P3DUS5.js +0 -2
  333. package/dist/cli/chunks/mcp-F2V3KKG6.js +0 -2
  334. package/dist/cli/chunks/memory-backend-27BBT57O.js +0 -2
  335. package/dist/cli/chunks/pattern-null-store-SRBYJRNX.js +0 -2
  336. package/dist/cli/chunks/protocol-executor-WJLJHWO2.js +0 -2
  337. package/dist/cli/chunks/provider-manager-UKUHSHAL.js +0 -2
  338. package/dist/cli/chunks/qe-reasoning-bank-IMUECSFZ.js +0 -2
  339. package/dist/cli/chunks/queen-coordinator-EC4SVNMB.js +0 -2
  340. package/dist/cli/chunks/roocode-installer-DFUA6FXW.js +0 -4
  341. package/dist/cli/chunks/router-TVTOUQLL.js +0 -2
  342. package/dist/cli/chunks/routing-feedback-Y4WDXNXW.js +0 -2
  343. package/dist/cli/chunks/rvf-native-adapter-4YSC6QKO.js +0 -2
  344. package/dist/cli/chunks/safe-db-RGAY54O5.js +0 -2
  345. package/dist/cli/chunks/schedule-KJ4GWLPJ.js +0 -2
  346. package/dist/cli/chunks/scheduler-AONSLVA3.js +0 -2
  347. package/dist/cli/chunks/sqlite-persistence-7RZUEPM4.js +0 -2
  348. package/dist/cli/chunks/unified-memory-G3BYQ3WU.js +0 -2
  349. package/dist/cli/chunks/unified-memory-hnsw-F7XUZMKW.js +0 -2
  350. package/dist/cli/chunks/unified-persistence-V35NXJSO.js +0 -2
  351. package/dist/cli/chunks/visual-security-K47U7KUM.js +0 -2
  352. package/dist/cli/chunks/windsurf-installer-I3TSJCNL.js +0 -7
  353. package/dist/cli/chunks/witness-chain-G6GJXZD3.js +0 -2
  354. package/dist/cli/chunks/workflow-orchestrator-SKF7GC5X.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{b as x,c as w,d as U,e as A}from"./chunk-ZSMHQENA.js";import{a as v,b as _}from"./chunk-LCDMB5SP.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-7NKVEEXD.js";import{a as P}from"./chunk-QHGHWATK.js";import{b as I,c as H}from"./chunk-MTWBYHMS.js";import{i as z}from"./chunk-NFZY6ZVY.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{b as x,c as w,d as U,e as A}from"./chunk-5HLOQEKL.js";import{a as v,b as _}from"./chunk-DNE6MVNA.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-7NT34MLU.js";import{a as P}from"./chunk-YHFCLJMY.js";import{b as I,c as H}from"./chunk-5U5SEO7C.js";import{i as z}from"./chunk-QWXJRZEH.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{a as D,b as _,c as $,d as I}from"./chunk-W72CUJRB.js";import{a as X}from"./chunk-HEC2UWY3.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-Z57UERQZ.js";import{b as C,f as G,i as U}from"./chunk-HVFHPDXV.js";import{g as R}from"./chunk-XYXRO7VP.js";import{e as H}from"./chunk-NL4EKO2J.js";import{i as j,m as de}from"./chunk-OLOKPY5O.js";import{a as z}from"./chunk-2B2RLPK3.js";import{c as T}from"./chunk-G73PIM7X.js";import{b as k,c as A}from"./chunk-D7ZVIL3C.js";import{a as h,b as V,c as W}from"./chunk-MTWBYHMS.js";import{S as pe,b as B}from"./chunk-HE3KLHNO.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as D,b as _,c as $,d as I}from"./chunk-YB3PQ3UV.js";import{a as X}from"./chunk-7C5HI4ZA.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-757YHKIJ.js";import{b as C,f as G,i as U}from"./chunk-RRSJ7BMF.js";import{g as R}from"./chunk-OQUH7657.js";import{e as H}from"./chunk-BVEQPMOF.js";import{i as j,m as de}from"./chunk-L5NEEGKO.js";import{a as z}from"./chunk-OPKEQYAC.js";import{c as T}from"./chunk-VHYNRISI.js";import{b as k,c as A}from"./chunk-X6YUGKMM.js";import{a as h,b as V,c as W}from"./chunk-5U5SEO7C.js";import{S as pe,b as B}from"./chunk-KRAWWBX5.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -317,4 +317,4 @@ On promotion:
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-TKHUE2RL.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-TKHUE2RL.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-5DNJ4KEM.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-5DNJ4KEM.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{e as x,f as C,j as y,k as R,q as F}from"./chunk-XPAH7SEX.js";import{b as I,c as k}from"./chunk-MTWBYHMS.js";import{c as w}from"./chunk-SDGRU6SG.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
- Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-LCTNDCKK.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{e as x,f as C,j as y,k as R,q as F}from"./chunk-PFGH7TWL.js";import{b as I,c as k}from"./chunk-5U5SEO7C.js";import{c as w}from"./chunk-ABJPFKHE.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
+ Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-I5BMT734.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
4
4
  Array.from(document.querySelectorAll('${t}'))
5
5
  .map(el => ({
6
6
  tag: el.tagName.toLowerCase(),
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{a as l}from"./chunk-OK6CSJOX.js";import{a as m}from"./chunk-D7ZVIL3C.js";import{i as a}from"./chunk-NFZY6ZVY.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as l}from"./chunk-ILPIH4Z6.js";import{a as m}from"./chunk-X6YUGKMM.js";import{i as a}from"./chunk-QWXJRZEH.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{a as u,c as v,d as p}from"./chunk-GDHJZPNC.js";import{b as l}from"./chunk-VL4MSE3J.js";import{a}from"./chunk-DNC27OP7.js";var P=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function x(e={}){if(e.providerManager){let d=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),f=new a(e.providerManager,d);return await f.initialize(),{router:f,resolvedConfig:d,enabledProviders:y(d)}}if(!p({projectRoot:e.projectRoot,env:e.env}))return null;let r=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),o=g(r,e.env??process.env);if(o.length===0)return null;let{primary:n,fallbacks:t}=R(r,o),i={primary:n,fallbacks:t,providers:m(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},c=new l(i),s=new a(c,r);return await s.initialize(),{router:s,resolvedConfig:r,enabledProviders:o}}function g(e,r=process.env){let o=u(r),n=[],t=i=>{n.includes(i)||!e.providers?.[i]?.enabled||o.has(i)&&n.push(i)};t(e.defaultProvider);for(let i of e.fallbackChain?.entries??[])t(i.provider);for(let i of P)t(i);return n}function y(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function R(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(t=>t!==o);return{primary:o,fallbacks:n}}function m(e,r){let o={};for(let n of r){let t=e.providers?.[n];t&&(o[n]=t)}return o}export{x as a,g as b,R as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as u,c as v,d as p}from"./chunk-HAC7NB6R.js";import{b as l}from"./chunk-VHCHBMZC.js";import{a}from"./chunk-PYQZ4OA3.js";var P=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function x(e={}){if(e.providerManager){let d=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),f=new a(e.providerManager,d);return await f.initialize(),{router:f,resolvedConfig:d,enabledProviders:y(d)}}if(!p({projectRoot:e.projectRoot,env:e.env}))return null;let r=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),o=g(r,e.env??process.env);if(o.length===0)return null;let{primary:n,fallbacks:t}=R(r,o),i={primary:n,fallbacks:t,providers:m(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},c=new l(i),s=new a(c,r);return await s.initialize(),{router:s,resolvedConfig:r,enabledProviders:o}}function g(e,r=process.env){let o=u(r),n=[],t=i=>{n.includes(i)||!e.providers?.[i]?.enabled||o.has(i)&&n.push(i)};t(e.defaultProvider);for(let i of e.fallbackChain?.entries??[])t(i.provider);for(let i of P)t(i);return n}function y(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function R(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(t=>t!==o);return{primary:o,fallbacks:n}}function m(e,r){let o={};for(let n of r){let t=e.providers?.[n];t&&(o[n]=t)}return o}export{x as a,g as b,R as c};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.8");process.exit(0)}
2
- import{a as U,b as G}from"./chunk-2KP5TJS2.js";import{h as N}from"./chunk-5KUINS3D.js";import{a as W}from"./chunk-HEC2UWY3.js";import{e as F}from"./chunk-HVFHPDXV.js";import{b as v,c as x}from"./chunk-G2J7WGOG.js";import{a as re}from"./chunk-2B2RLPK3.js";import{c as O}from"./chunk-G73PIM7X.js";import{b as k,d as q}from"./chunk-DDMKCHYT.js";import{b,c as E}from"./chunk-D7ZVIL3C.js";import{a as y,c as I}from"./chunk-MTWBYHMS.js";import{i as z}from"./chunk-NFZY6ZVY.js";import{S as ae,b as _}from"./chunk-HE3KLHNO.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-G3BYQ3WU.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as U,b as G}from"./chunk-RHOBDQXA.js";import{h as N}from"./chunk-QAP5S7YC.js";import{a as W}from"./chunk-7C5HI4ZA.js";import{e as F}from"./chunk-RRSJ7BMF.js";import{b as v,c as x}from"./chunk-X7677BX3.js";import{a as re}from"./chunk-OPKEQYAC.js";import{c as O}from"./chunk-VHYNRISI.js";import{b as k,d as q}from"./chunk-246Z3PH6.js";import{b,c as E}from"./chunk-X6YUGKMM.js";import{a as y,c as I}from"./chunk-5U5SEO7C.js";import{i as z}from"./chunk-QWXJRZEH.js";import{S as ae,b as _}from"./chunk-KRAWWBX5.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-WJEZ5YAK.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
3
3
  INSERT OR REPLACE INTO qe_trajectories
4
4
  (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -9,4 +9,4 @@ Steps:
9
9
  ${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
10
10
  `)}
11
11
 
12
- Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-RFFON2F3.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-YG2UWTYZ.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-YG2UWTYZ.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-V35NXJSO.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-V35NXJSO.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-SRBYJRNX.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-NM3S7OEW.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-C2D2IEYV.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
12
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-ITLDYHCX.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-BNJ4VSZX.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-BNJ4VSZX.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-SWH6R7MA.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-SWH6R7MA.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-B2UX4NZY.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-JYZSSQJC.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-6CGRPRGR.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};